If you want the table to still be 100% then set one of the columns to have a width:100%; That will extend that column to fill the extra space and allow the other columns to keep their auto width :)
The List<>
class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.
According to MSDN:
...List "Represents a strongly typed list of objects that can be accessed by index."
The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.
You might be getting odd results from your code if you're moving the item later in the list, as your Remove()
will move all of the other items down one place before the call to Insert()
.
Can you boil your code down to something small enough to post?
If you're already using jquery, I don't see why you wouldn't also be able to use a lightweight overlay plugin. Other people have already written some nice ones in jquery, so why re-invent the wheel?
I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.
Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!
Hope to help
You may use
values, counts = np.unique(a, return_counts=True)
ind = np.argmax(counts)
print(values[ind]) # prints the most frequent element
ind = np.argpartition(-counts, kth=10)[:10]
print(values[ind]) # prints the 10 most frequent elements
If some element is as frequent as another one, this code will return only the first element.
You can run node.js server on a typical shared hosting with Linux, Apache and PHP (LAMP). I have successfully installed it, even with NPM, Express and Grunt working fine. Follow the steps:
1) Create a new PHP file on the server with the following code and run it:
<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');
2) The same way install your node app, e.g. jt-js-sample, using npm:
<?php
exec('node/bin/npm install jt-js-sample');
3) Run the node app from PHP:
<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=49999 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:49999/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
//If couldn't connect, try increasing usleep
echo 'Error: ' . curl_error($curl);
} else {
//Split response headers and body
list($head, $body) = explode("\r\n\r\n", $resp, 2);
$headarr = explode("\n", $head);
//Print headers
foreach($headarr as $headval) {
header($headval);
}
//Print body
echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);
Voila! Have a look at the demo of a node app on PHP shared hosting.
EDIT: I started a Node.php project on GitHub.
its even easier:
fileList.Where(item => filterList.Contains(item))
in case you want to filter not for an exact match but for a "contains" you can use this expression:
var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));
Just like this:
alter table document modify column id int(11) auto_increment;
Please check cocoapod Prestyler:
Prestyler.defineRule("$", UIColor.orange)
label.attributedText = "This $text$ is orange".prestyled()
Here is a version of the accepted answer which can also take a minFontSize parameter.
(function($) {
/**
* Resizes an inner element's font so that the inner element completely fills the outer element.
* @author Russ Painter [email protected]
* @author Blake Robertson
* @version 0.2 -- Modified it so a min font parameter can be specified.
*
* @param {Object} Options which are maxFontPixels (default=40), innerTag (default='span')
* @return All outer elements processed
* @example <div class='mybigdiv filltext'><span>My Text To Resize</span></div>
*/
$.fn.textfill = function(options) {
var defaults = {
maxFontPixels: 40,
minFontPixels: 10,
innerTag: 'span'
};
var Opts = jQuery.extend(defaults, options);
return this.each(function() {
var fontSize = Opts.maxFontPixels;
var ourText = $(Opts.innerTag + ':visible:first', this);
var maxHeight = $(this).height();
var maxWidth = $(this).width();
var textHeight;
var textWidth;
do {
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
fontSize = fontSize - 1;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > Opts.minFontPixels);
});
};
})(jQuery);
#include"stdio.h"//rmv coding for randam number access
#include"conio.h"
#include"time.h"
void main()
{
time_t t;
int rmvivek;
srand(time(&t));
rmvivek=1;
while(rmvivek<=5)
{
printf("%c\t",rand()%10);
rmvivek++;
}
getch();
}
The onChange
event bubbles... So you can do something like this:
// A sample form
render () {
<form onChange={setField}>
<input name="input1" />
<input name="input2" />
</form>
}
And your setField method might look like this (assuming you're using ES2015 or later:
setField (e) {
this.setState({[e.target.name]: e.target.value})
}
I use something similar to this in several apps, and it's pretty handy.
If you can use extension methods, this will do it in a safe way regardless of string length:
public static string Right(this string text, int maxLength)
{
if (string.IsNullOrEmpty(text) || maxLength <= 0)
{
return string.Empty;
}
if (maxLength < text.Length)
{
return text.Substring(text.Length - maxLength);
}
return text;
}
And to use it:
string sub = input.Right(5);
Don't forget about spaces:
source=""
samples=("")
if [ $1 = "country" ]; then
source="country"
samples="US Canada Mexico..."
else
echo "try again"
fi
I've written a tutorial that expands on the answer posted by JVitela. Basically, it uses the same idea, but instead of rendering each string to a texture, it renders all characters from a font file to a texture and uses that to allow for full dynamic text rendering with no further slowdowns (once the initialization is complete).
The main advantage of my method, compared to the various font atlas generators, is that you can ship small font files (.ttf .otf) with your project instead of having to ship large bitmaps for every font variation and size. It can generate perfect quality fonts at any resolution using only a font file :)
The tutorial includes full code that can be used in any project :)
Try display: inline-block;
. For it to be cross browser compatible please use the below css code.
div {_x000D_
display: inline-block;_x000D_
display:-moz-inline-stack;_x000D_
zoom:1;_x000D_
*display:inline;_x000D_
border-style: solid;_x000D_
border-color: #0000ff;_x000D_
}
_x000D_
<div>_x000D_
<table>_x000D_
<tr>_x000D_
<td>Column1</td>_x000D_
<td>Column2</td>_x000D_
<td>Column3</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
There are lots of great answers here. But if your looking for a really simple way, and you don't mind a popular library, a great solution is filesize
https://www.npmjs.com/package/filesize
It has lots of options and the usage is simple e.g.
filesize(265318); // "259.1 KB"
Taken from their excellent examples
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
You can do something like this:
// show loading image
$('#loader_img').show();
// main image loaded ?
$('#main_img').on('load', function(){
// hide/remove the loading image
$('#loader_img').hide();
});
You assign load
event to the image which fires when image has finished loading. Before that, you can show your loader image.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
I am days into the MVC4 world.
For what its worth, I have a SitesAPIController, and I needed a custom method, that could be called like:
http://localhost:9000/api/SitesAPI/Disposition/0
With different values for the last parameter to get record with different dispositions.
What Finally worked for me was:
The method in the SitesAPIController:
// GET api/SitesAPI/Disposition/1
[ActionName("Disposition")]
[HttpGet]
public Site Disposition(int disposition)
{
Site site = db.Sites.Where(s => s.Disposition == disposition).First();
return site;
}
And this in the WebApiConfig.cs
// this was already there
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// this i added
config.Routes.MapHttpRoute(
name: "Action",
routeTemplate: "api/{controller}/{action}/{disposition}"
);
For as long as I was naming the {disposition} as {id} i was encountering:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:9000/api/SitesAPI/Disposition/0'.",
"MessageDetail": "No action was found on the controller 'SitesAPI' that matches the request."
}
When I renamed it to {disposition} it started working. So apparently the parameter name is matched with the value in the placeholder.
Feel free to edit this answer to make it more accurate/explanatory.
I've created a new scheme based on my current app.config to get the messages to disappear. I just used the button in Visual Studio that says "Create Schema" and an xsd schema was created for me.
Save the schema in an apropriate place and see the "Properties" tab of the app.config file where there is a property named Schemas. If you click the change button there you can select to use both the original dotnetconfig schema and your own newly created one.
I was calling parentView.removeView(childView) and childView was still showing. I eventually realized that a method was somehow being triggered twice and added the childView to the parentView twice.
So, use parentView.getChildCount() to determine how many children the parent has before you add a view and afterwards. If the child is added too many times then the top most child is being removed and the copy childView remains-which looks like removeView is working even when it is.
Also, you shouldn't use View.GONE to remove a view. If it's truly removed then you won't need to hide it, otherwise it's still there and you're just hiding it from yourself :(
MongoDB has a distinct
command which returns an array of distinct values for a field; you can check the length of the array for a count.
There is a shell db.collection.distinct()
helper as well:
> db.countries.distinct('country');
[ "Spain", "England", "France", "Australia" ]
> db.countries.distinct('country').length
4
I needed to export our security log and wanted the date and time in Coordinated Universal Time. This proved to be a challenge to figure out, but so simple to execute:
wevtutil export-log security c:\users\%username%\SECURITYEVENTLOG-%computername%-$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ")).evtx
The magic code is just this part:
$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ"))
Range("A1").value = Environ("Username")
This is better than Application.Username
, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.
Application Username
is the name of the User set in Excel > Tools > Options Environ("Username")
is the name you registered for Windows; see Control Panel >Systemif you are using oracle 10g expree Edition then:
1. for loading class use
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
2. for connecting to database use
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:username/password@localhost:1521:xe");
As of Apache POI 3.17 you will have to check if the cell is empty using enumerations:
import org.apache.poi.ss.usermodel.CellType;
if(cell == null || cell.getCellTypeEnum() == CellType.BLANK) { ... }
I usually do like this:
from numpy import log as ln
Perhaps this can make you more comfortable.
Parameters passed to the C program executable is nothing but an array of string(or character pointer),so memory would have been already allocated for these input parameter before your program access these parameters,so no need to allocate buffer,and that way you can avoid error handling code in your program as well(Reduce chances of segfault :)).
If you need to remove just trailing whitespace, you could use str.rstrip()
, which should be slightly more efficient than str.strip()
:
>>> lst = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> [x.rstrip() for x in lst]
['this', 'is', 'a', 'list', 'of', 'words']
>>> list(map(str.rstrip, lst))
['this', 'is', 'a', 'list', 'of', 'words']
As per user667073 suggested, except reordering the backslash replacement first, and fixing the quote replacement
escape = function (str) {
return str
.replace(/[\\]/g, '\\\\')
.replace(/[\"]/g, '\\\"')
.replace(/[\/]/g, '\\/')
.replace(/[\b]/g, '\\b')
.replace(/[\f]/g, '\\f')
.replace(/[\n]/g, '\\n')
.replace(/[\r]/g, '\\r')
.replace(/[\t]/g, '\\t');
};
You can mock out aw.Clear
, either manually or using a testing framework like pymox. Manually, you'd do it using something like this:
class MyTest(TestCase):
def testClear():
old_clear = aw.Clear
clear_calls = 0
aw.Clear = lambda: clear_calls += 1
aps.Request('nv2', aw)
assert clear_calls == 1
aw.Clear = old_clear
Using pymox, you'd do it like this:
class MyTest(mox.MoxTestBase):
def testClear():
aw = self.m.CreateMock(aps.Request)
aw.Clear()
self.mox.ReplayAll()
aps.Request('nv2', aw)
\n
is a line break. /n
is not.
use of \n
with
Now if you are trying to echo string to the page:
echo "kings \n garden";
output will be:
kings garden
you won't get garden
in new line because PHP is a server-side language, and you are sending output as HTML, you need to create line breaks in HTML. HTML doesn't understand \n
. You need to use the nl2br()
function for that.
What it does is:
Returns string with
<br />
or<br>
inserted before all newlines (\r\n, \n\r, \n and \r).
echo nl2br ("kings \n garden");
kings
garden
Note Make sure you're echoing/printing
\n
in double quotes, else it will be rendered literally as \n. because php interpreter parse string in single quote with concept of as is
so "\n" not '\n'
Now if you echo to text file you can use just \n
and it will echo to a new line, like:
$myfile = fopen("test.txt", "w+") ;
$txt = "kings \n garden";
fwrite($myfile, $txt);
fclose($myfile);
output will be:
kings
garden
The general methodology would be to iterate through the ArrayList
, and insert the values into the HashMap
. An example is as follows:
HashMap<String, Product> productMap = new HashMap<String, Product>();
for (Product product : productList) {
productMap.put(product.getProductCode(), product);
}
If it gets into the selinux arena you've got a much more complicated issue. It's not a good idea to remove the selinux protection but to embrace it and use the tools that were designed to manage it.
If you are serving content out of /var/www/abc
, you can verify the selinux permissions with a Z
appended to the normal ls -l
command. i.e. ls -laZ
will give the selinux context.
To add a directory to be served by selinux you can use the semanage
command like this. This will change the label on /var/www/abc
to httpd_sys_content_t
semanage fcontext -a -t httpd_sys_content_t /var/www/abc
this will update the label for /var/www/abc
restorecon /var/www/abc
This answer was taken from unixmen and modified to fit this question. I had been searching for this answer for a while and finally found it so felt like I needed to share somewhere. Hope it helps someone.
XmlDocument doc = new XmlDocument();
doc.Load("MonFichierXML.xml");
XmlNode node = doc.SelectSingleNode("Magasin");
XmlNodeList prop = node.SelectNodes("Items");
foreach (XmlNode item in prop)
{
items Temp = new items();
Temp.AssignInfo(item);
lstitems.Add(Temp);
}
You can use "dd/MM/yyyy"
format for using it in DateTime.ParseExact
.
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Here is a DEMO
.
For more informations, check out Custom Date and Time Format Strings
If you are using Sql Server Management Studio 2008 there are certain data fields you can view in the object explorer details window. Simply browse to and select the tables folder. In the details view you are able to right-click the column titles and add fields to the "report". Your mileage may vary if you are on SSMS 2008 express.
No need to add new plugin in pom.xml. Just run this command
mvn org.codehaus.mojo:exec-maven-plugin:1.5.0:java -Dexec.mainClass="com.example.Main" | grep -Ev '(^\[|Download\w+:)'
See the maven exec plugin for more usage.
In this case, ' is not a comment character. It's used to delimit string literals. The comic artist is banking on the idea that the school in question has dynamic sql somewhere that looks something like this:
$sql = "INSERT INTO `Students` (FirstName, LastName) VALUES ('" . $fname . "', '" . $lname . "')";
So now the ' character ends the string literal before the programmer was expecting it. Combined with the ; character to end the statement, an attacker can now add whatever sql they want. The -- comment at the end is to make sure any remaining sql in the original statement does not prevent the query from compiling on the server.
FWIW, I also think the comic in question has an important detail wrong: if you're thinking about sanitizing your database inputs, as the comic suggests, you're still doing it wrong. Instead, you should think in terms of quarantining your database inputs, and the correct way to do this is via parameterized queries.
This is the quick and easy way to do it
<div>
<span>Span 1</span>
<span>Span 2</span>
<span>Span 3</span>
</div>
css
div{
width:100%;
}
span{
display:inline-block;
width:33%;
text-align:center;
}
Then adjust the width
of the span
s for the number you have.
Use TextView
inside a ScrollView
to display messages with any no.of lines. User can't edit the text in this view as in EditText
.
I think this is good for your requirement. Try it once.
You can change the default color and text size in XML file only if you want to fix them as below:
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="100px"
android:textColor="#f00"
android:textSize="25px"
android:typeface="serif"
android:textStyle="italic"/>
or if you want to change dynamically whenever you want use as below:
TextView textarea = (TextView)findViewById(R.id.tv); // tv is id in XML file for TextView
textarea.setTextSize(20);
textarea.setTextColor(Color.rgb(0xff, 0, 0));
textarea.setTypeface(Typeface.SERIF, Typeface.ITALIC);
Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.
A proper way to search for a substring is to use position
function instead of like
expression, which requires escaping %
, _
and an escape character (\
by default):
SELECT id FROM TAG_TABLE WHERE position(tag_name in 'aaaaaaaaaaa')>0;
You can use SelectionChanged event since you are using FullRowSelect selection mode. Than inside the handler you can access SelectedRows property and get data from it. Example:
private void dataGridView_SelectionChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView.SelectedRows)
{
string value1 = row.Cells[0].Value.ToString();
string value2 = row.Cells[1].Value.ToString();
//...
}
}
You can also walk through the column collection instead of typing indexes...
dis
is your friend if the source code is not available:
>>> import dis
>>> def foo(arg1,arg2):
... #do something with args
... a = arg1 + arg2
... return a
...
>>> dis.dis(foo)
3 0 LOAD_FAST 0 (arg1)
3 LOAD_FAST 1 (arg2)
6 BINARY_ADD
7 STORE_FAST 2 (a)
4 10 LOAD_FAST 2 (a)
13 RETURN_VALUE
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
It is a way to simplify error checking and avoid deep nested if's. For example:
do {
// do something
if (error) {
break;
}
// do something else
if (error) {
break;
}
// etc..
} while (0);
I have created a custom regex to deal with names:
I have tried these types of names and found working perfect
My RegEx looks like this:
^([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?)
MVC4 Model:
[RegularExpression("^([a-zA-Z]{2,}\\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\\s?([a-zA-Z]{1,})?)", ErrorMessage = "Valid Charactors include (A-Z) (a-z) (' space -)") ]
Please note the double \\
for escape characters
For those of you that are new to RegEx I thought I'd include a explanation.
^ // start of line
[a-zA-Z]{2,} // will except a name with at least two characters
\s // will look for white space between name and surname
[a-zA-Z]{1,} // needs at least 1 Character
\'?-? // possibility of **'** or **-** for double barreled and hyphenated surnames
[a-zA-Z]{2,} // will except a name with at least two characters
\s? // possibility of another whitespace
([a-zA-Z]{1,})? // possibility of a second surname
Here is how you could do it with Java 11's java.net.http package:
var fileA = new File("a.pdf");
var fileB = new File("b.pdf");
var mimeMultipartData = MimeMultipartData.newBuilder()
.withCharset(StandardCharsets.UTF_8)
.addFile("file1", fileA.toPath(), Files.probeContentType(fileA.toPath()))
.addFile("file2", fileB.toPath(), Files.probeContentType(fileB.toPath()))
.build();
var request = HttpRequest.newBuilder()
.header("Content-Type", mimeMultipartData.getContentType())
.POST(mimeMultipartData.getBodyPublisher())
.uri(URI.create("http://somehost/upload"))
.build();
var httpClient = HttpClient.newBuilder().build();
var response = httpClient.send(request, BodyHandlers.ofString());
With the following MimeMultipartData:
public class MimeMultipartData {
public static class Builder {
private String boundary;
private Charset charset = StandardCharsets.UTF_8;
private List<MimedFile> files = new ArrayList<MimedFile>();
private Map<String, String> texts = new LinkedHashMap<>();
private Builder() {
this.boundary = new BigInteger(128, new Random()).toString();
}
public Builder withCharset(Charset charset) {
this.charset = charset;
return this;
}
public Builder withBoundary(String boundary) {
this.boundary = boundary;
return this;
}
public Builder addFile(String name, Path path, String mimeType) {
this.files.add(new MimedFile(name, path, mimeType));
return this;
}
public Builder addText(String name, String text) {
texts.put(name, text);
return this;
}
public MimeMultipartData build() throws IOException {
MimeMultipartData mimeMultipartData = new MimeMultipartData();
mimeMultipartData.boundary = boundary;
var newline = "\r\n".getBytes(charset);
var byteArrayOutputStream = new ByteArrayOutputStream();
for (var f : files) {
byteArrayOutputStream.write(("--" + boundary).getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(("Content-Disposition: form-data; name=\"" + f.name + "\"; filename=\"" + f.path.getFileName() + "\"").getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(("Content-Type: " + f.mimeType).getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(Files.readAllBytes(f.path));
byteArrayOutputStream.write(newline);
}
for (var entry: texts.entrySet()) {
byteArrayOutputStream.write(("--" + boundary).getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"").getBytes(charset));
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(newline);
byteArrayOutputStream.write(entry.getValue().getBytes(charset));
byteArrayOutputStream.write(newline);
}
byteArrayOutputStream.write(("--" + boundary + "--").getBytes(charset));
mimeMultipartData.bodyPublisher = BodyPublishers.ofByteArray(byteArrayOutputStream.toByteArray());
return mimeMultipartData;
}
public class MimedFile {
public final String name;
public final Path path;
public final String mimeType;
public MimedFile(String name, Path path, String mimeType) {
this.name = name;
this.path = path;
this.mimeType = mimeType;
}
}
}
private String boundary;
private BodyPublisher bodyPublisher;
private MimeMultipartData() {
}
public static Builder newBuilder() {
return new Builder();
}
public BodyPublisher getBodyPublisher() throws IOException {
return bodyPublisher;
}
public String getContentType() {
return "multipart/form-data; boundary=" + boundary;
}
}
This is what I use, but it is slow on large text files.
get-content $pathToFile | % { $_ -replace $stringToReplace, $replaceWith } | set-content $pathToFile
If you are going to be replacing strings in large text files and speed is a concern, look into using System.IO.StreamReader and System.IO.StreamWriter.
try
{
$reader = [System.IO.StreamReader] $pathToFile
$data = $reader.ReadToEnd()
$reader.close()
}
finally
{
if ($reader -ne $null)
{
$reader.dispose()
}
}
$data = $data -replace $stringToReplace, $replaceWith
try
{
$writer = [System.IO.StreamWriter] $pathToFile
$writer.write($data)
$writer.close()
}
finally
{
if ($writer -ne $null)
{
$writer.dispose()
}
}
(The code above has not been tested.)
There is probably a more elegant way to use StreamReader and StreamWriter for replacing text in a document, but that should give you a good starting point.
You could override your object's ToString() method:
public override string ToString ()
{
return string.Format ("{0},{1},{2}", this.number, this.id, this.whatever);
}
As Alex says, it works very well. The only tricky part is to remember to make any changes in the cmake files, rather than from within Visual Studio. So on all platforms, the workflow is similar to if you'd used plain old makefiles.
But it's fairly easy to work with, and I've had no issues with cmake generating invalid files or anything like that, so I wouldn't worry too much.
If your regex includes a variable, make sure to escape it.
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
This can be used like this
new RegExp(escapeRegExp(searchString), 'i')
Or in a mongoDb query like this
{ '$regex': escapeRegExp(searchString) }
Posted same comment here
Follow these steps
npm install --save cors
var cors = require('cors');
app.use(cors());
Just add the attribute disabled
to the element (or use jQuery to do it for you). Disabled prevents the input from being focused or selected at all.
Easiest solution is to create the column using the correct data type: DATE
For example:
Create table:
create table test_date (mydate date);
Insert row:
insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));
To get the month and year, do as follows:
select to_char(mydate, 'MM-YYYY') from test_date;
Your result will be as follows: 01-2011
Another cool function to use is "EXTRACT"
select extract(year from mydate) from test_date;
This will return: 2011
I had loads of trouble with this too. I have data and labels in separate arrays then I reinitialise the chart data. I added the line.destroy(); as suggested above which has done the trick
var ctx = document.getElementById("canvas").getContext("2d");_x000D_
if(window.myLine){_x000D_
window.myLine.destroy();_x000D_
}_x000D_
window.myLine = new Chart(ctx).Line(lineChartData, {_x000D_
etc_x000D_
etc
_x000D_
Other answers already show that you can use split() to get the values into a list. If you were asking about Python's arrays, here is one solution:
import array
s = '42 0'
a = array.array('i')
for n in s.split():
a.append(int(n))
Edit: A more concise solution:
import array
s = '42 0'
a = array.array('i', (int(t) for t in s.split()))
npm install --save-dev "cross-env"
module.cross-env NODE_ENV=development node foo.js
.
Then you can run the like npm run build
.Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar
, you can use
gradle run --args='foo --bar'
Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);
function applyDataMask(field) {
var mask = field.dataset.mask.split('');
// For now, this just strips everything that's not a number
function stripMask(maskedData) {
function isDigit(char) {
return /\d/.test(char);
}
return maskedData.split('').filter(isDigit);
}
// Replace `_` characters with characters from `data`
function applyMask(data) {
return mask.map(function(char) {
if (char != '_') return char;
if (data.length == 0) return char;
return data.shift();
}).join('')
}
function reapplyMask(data) {
return applyMask(stripMask(data));
}
function changed() {
var oldStart = field.selectionStart;
var oldEnd = field.selectionEnd;
field.value = reapplyMask(field.value);
field.selectionStart = oldStart;
field.selectionEnd = oldEnd;
}
field.addEventListener('click', changed)
field.addEventListener('keyup', changed)
}
Date: <input type="text" value="__-__-____" data-mask="__-__-____"/><br/>
Telephone: <input type="text" value="(___) ___-____" data-mask="(___) ___-____"/><br/>
In Chrome when you load a website from some HTTP server both absolute paths (e.g. /images/sth.png
) and relative paths to some upper level directory (e.g. ../images/sth.png
) work.
But!
When you load (in Chrome!) a HTML document from local filesystem you cannot access directories above current directory. I.e. you cannot access ../something/something.sth
and changing relative path to absolute or anything else won't help.
var seconds = 2000 ; // or "2000"
seconds = parseInt(seconds) //because moment js dont know to handle number in string format
var format = Math.floor(moment.duration(seconds,'seconds').asHours()) + ':' + moment.duration(seconds,'seconds').minutes() + ':' + moment.duration(seconds,'seconds').seconds();
Two things:
First, JRE is not the same as the JDK. If you do have the JDK, you need to configure eclipse to point to that in your settings.
Second, in your screenshot above, your compiler compliance level is set to 1.7. This will treat all your code as if it's using Java 1.7. Change this to 1.8 to fix your error.
You will need to have Eclipse Luna in order to get support for Java 8, but you can add it to Kepler SR2 if you want. I'd try with Luna and the above suggestions before you go any further. See this reference.
Once you get Luna, your JAVA_HOME variable should be enough to get Eclipse to recognize JDK 8. If you want to specify an additional JDK, you can add a new Java System Library by going to:
Project -> Properties -> Java Build Path -> Libraries -> Add Library -> Java System Library
and navigating to a valid location for the JDK 8.
You can download your platform's JDK 8 here
list1.equals(list2);
If your list contains a custom Class MyClass, this class must override the equals
function.
class MyClass
{
int field=0;
@0verride
public boolean equals(Object other)
{
if(this==other) return true;
if(other==null || !(other instanceof MyClass)) return false;
return this.field== MyClass.class.cast(other).field;
}
}
Note :if you want to test equals on a java.util.Set rather than a java.util.List
, then your object must override the hashCode
function.
A list comprehension is likely the cleanest way:
>>> L = [0, 23, 234, 89, None, 0, 35, 9
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]
There is also a functional programming approach but it is more involved:
>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(partial(is_not, None), L))
[0, 23, 234, 89, 0, 35, 9]
See these Date methods ...
It calculates ex for each x in your list where e is Euler's number (approximately 2.718). In other words, np.exp(range(5))
is similar to [math.e**x for x in range(5)]
.
Bootstrap now has the following style for table cells:
.table tbody > tr > td{
vertical-align: top;
}
The way to go is to add your own class, adding more specificity to the previous selector:
.table tbody > tr > td.vert-aligned {
vertical-align: middle;
}
And then add the class to your td
s:
<tr>
<td class="vert-aligned"></td>
...
</tr>
There is no way to do this with Bootstrap.
When used in table cells, vertical-align does what most people expect it to, which is to mimic the (old, deprecated) valign attribute. In a modern, standards-compliant browser, the following three code snippets do the same thing:
<td valign="middle"> <!-- but you shouldn't ever use valign --> </td>
<td style="vertical-align:middle"> ... </td>
<div style="display:table-cell; vertical-align:middle"> ... </div>
Check your fiddle updated
Also, you can't refer to the td
class using .vert
because Bootstrap already has this class:
.table td {
padding: 8px;
line-height: 20px;
text-align: left;
vertical-align: top; // The problem!
border-top: 1px solid #dddddd;
}
And is overloading the vertical-align: middle
in '.vert' class, so you have to define this class as td.vert
.
Here is another illustrative example:
>>> print(", ".join(["ha" if i else "Ha" for i in range(3)]) + "!")
Ha, ha, ha!
It exploits the fact that if i
evaluates to False
for 0
and to True
for all other values generated by the function range()
. Therefore the list comprehension evaluates as follows:
>>> ["ha" if i else "Ha" for i in range(3)]
['Ha', 'ha', 'ha']
Internally, Javascript strings are all Unicode (actually UCS-2, a subset of UTF-16).
If you're retrieving the JSON files separately via AJAX, then you only need to make sure that the JSON files are served with the correct Content-Type and charset: Content-Type: application/json; charset="utf-8"
). If you do that, jQuery should already have interpreted them properly by the time you access the deserialized objects.
Could you post an example of the code you’re using to retrieve the JSON objects?
On Windows Server 2016 Standard, which is what I develop on, I just had to open the Credential Manager Control Panel and clear out the cached proxy settings for Visual Studio which were no longer valid and then restart Visual Studio. The next time I opened the Nuget Package Manager I was prompted for proxy credentials, which got me working again.
See: https://support.microsoft.com/en-us/help/4026814/windows-accessing-credential-manager
Use COUNTBLANK(B1)>0
instead of ISBLANK(B1)
inside your IF
statement.
Unlike ISBLANK()
, COUNTBLANK()
considers ""
as empty and returns 1.
An update to @malcubierre for Cordova 4 (and later)-
Create a file called release-signing.properties
and put in APPFOLDER\platforms\android
folder
Contents of the file: edit after = for all except 2nd line
storeFile=C:/yourlocation/app.keystore
storeType=jks
keyAlias=aliasname
keyPassword=aliaspass
storePassword=password
Then this command should build a release version:
cordova build android --release
UPDATE - This was not working for me Cordova 10 with android 9
- The build was replacing the release-signing.properties file. I had to make a build.json
file and drop it in the appfolder, same as root. And this is the contents - replace as above:
{
"android": {
"release": {
"keystore": "C:/yourlocation/app.keystore",
"storePassword": "password",
"alias": "aliasname",
"password" : "aliaspass",
"keystoreType": ""
}
}
}
Run it and it will generate one of those release-signing.properties
in the android folder
You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange
can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed.
If you are looking for the more advanced solution, I would suggest checking Resilio Connect.
It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.
Let's say you'd like to have an array of instances of Parent class, and a set of child classes Child1, Child2, Child3 extending Parent. There're situations when you're only interested with the parent class implementation, which is more general, and do not care about more specific stuff introduced by child classes.
Responding to the Forum Thread for the sake of completeness. Amazon has stopped using the the ECU - Elastic Compute Units and moved on to a vCPU based measure. So ignoring the ECU you pretty much can start comparing the EC2 Instances' sizes as CPU (Clock Speed), number of CPUs, RAM, storage etc.
Every instance families' instance configurations are published as number of vCPU and what is the physical processor. Detailed info and screenshot obstained from here http://aws.amazon.com/ec2/instance-types/#instance-type-matrix
This is universal solution for conditions wiht more same results.
<?php
$your_name1_finded="somethnig searched"; //$your_name1_finded must be finded in previous select
$result = db_query("SELECT your_name1 FROM your_table WHERE your_name=your_condition ORDER BY your_name1, your_name2"); //Get all our ids
$i=0;
while($row = db_fetch_assoc($result)) { //Loop through our rows
$i++;
$current_row[$i]=$row['your_name1'];// field with results
if($row['your_name1'] == $your_name1_finded) {//If we haven't hit our current row yet
$yid=$i;
}
}
//buttons
if ($current_row[$yid-1]) $out_button.= "<a class='button' href='/$your_url/".$current_row[$yid-1]."'>BUTTON_PREVIOUS</a>";
if ($current_row[$yid+1]) $out_button.= "<a class='button' href='/$your_url/".$current_row[$yid+1]."'>BUTTON_NEXT</a>";
echo $out_button;//display buttons
?>
Jackson appears to support some amount of JSON parsing straight from an InputStream
. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.
Modify the code as fieldName = fieldName.replace("," , " ");
E:>move "blogger code.txt" d:/"blogger code.txt"
1 file(s) moved.
"blogger code.txt" is a file name
The file move from E: drive to D: drive
Another option may be to have your fragment implement View.OnClickListener and override onClick(View v) within your fragment. If you need to have your fragment talk to the activity simply add an interface with desired method(s) and have the activity implement the interface and override its method(s).
public class FragName extends Fragment implements View.OnClickListener {
public FragmentCommunicator fComm;
public ImageButton res1, res2;
int c;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
fComm = (FragmentCommunicator) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement FragmentCommunicator");
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
res1 = (ImageButton) getActivity().findViewById(R.id.responseButton1);
res1.setOnClickListener(this);
res2 = (ImageButton) getActivity().findViewById(R.id.responseButton2);
res2.setOnClickListener(this);
}
public void onClick(final View v) { //check for what button is pressed
switch (v.getId()) {
case R.id.responseButton1:
c *= fComm.fragmentContactActivity(2);
break;
case R.id.responseButton2:
c *= fComm.fragmentContactActivity(4);
break;
default:
c *= fComm.fragmentContactActivity(100);
break;
}
public interface FragmentCommunicator{
public int fragmentContactActivity(int b);
}
public class MainActivity extends FragmentActivity implements FragName.FragmentCommunicator{
int a = 10;
//variable a is update by fragment. ex. use to change textview or whatever else you'd like.
public int fragmentContactActivity(int b) {
//update info on activity here
a += b;
return a;
}
}
http://developer.android.com/training/basics/firstapp/starting-activity.html http://developer.android.com/training/basics/fragments/communicating.html
ripgrep
If you care about the performance, use ripgrep
which has similar syntax to grep
, e.g.
rg -C5 "pattern" .
-C
,--context NUM
- Show NUM lines before and after each match.
There are also parameters such as -A
/--after-context
and -B
/--before-context
.
The tool is built on top of Rust's regex engine which makes it very efficient on the large data.
Easiest way I can think of:
def which(program):
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
Edit: Updated code sample to include logic for handling case where provided argument is already a full path to the executable, i.e. "which /bin/ls". This mimics the behavior of the UNIX 'which' command.
Edit: Updated to use os.path.isfile() instead of os.path.exists() per comments.
Edit: path.strip('"')
seems like the wrong thing to do here. Neither Windows nor POSIX appear to encourage quoted PATH items.
You can try this.
Timestamp=2008-11-11 13:23:44.657;
SELECT DATE_SUB(OrderDate,INTERVAL 1 DAY) AS SubtractDate FROM Orders
output :2008-11-10 13:23:44.657
I hope, it will help to solve your problem.
make
in, and off itself, handles directory targets just the same as file targets. So, it's easy to write rules like this:
outDir/someTarget: Makefile outDir
touch outDir/someTarget
outDir:
mkdir -p outDir
The only problem with that is, that the directories timestamp depends on what is done to the files inside. For the rules above, this leads to the following result:
$ make
mkdir -p outDir
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget
$ make
touch outDir/someTarget
This is most definitely not what you want. Whenever you touch the file, you also touch the directory. And since the file depends on the directory, the file consequently appears to be out of date, forcing it to be rebuilt.
However, you can easily break this loop by telling make to ignore the timestamp of the directory. This is done by declaring the directory as an order-only prerequsite:
# The pipe symbol tells make that the following prerequisites are order-only
# |
# v
outDir/someTarget: Makefile | outDir
touch outDir/someTarget
outDir:
mkdir -p outDir
This correctly yields:
$ make
mkdir -p outDir
touch outDir/someTarget
$ make
make: 'outDir/someTarget' is up to date.
TL;DR:
Write a rule to create the directory:
$(OUT_DIR):
mkdir -p $(OUT_DIR)
And have the targets for the stuff inside depend on the directory order-only:
$(OUT_DIR)/someTarget: ... | $(OUT_DIR)
getTime()
retrieves the milliseconds since Jan 1, 1970 GMT passed to the constructor. It should not be too hard to get the Unix time (same, but in seconds) from that.
You can't do it in a (This isn't quite true, as Sean points out in the comments. See note at the end.)switch
unless you're doing full string matching; that's doing substring matching.
If you're happy that your regex at the top is stripping away everything that you don't want to compare in your match, you don't need a substring match, and could do:
switch (base_url_string) {
case "xxx.local":
// Blah
break;
case "xxx.dev.yyy.com":
// Blah
break;
}
...but again, that only works if that's the complete string you're matching. It would fail if base_url_string
were, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.
Update: Okay, so technically you can use a switch
for substring matching, but I wouldn't recommend it in most situations. Here's how (live example):
function test(str) {
switch (true) {
case /xyz/.test(str):
display("• Matched 'xyz' test");
break;
case /test/.test(str):
display("• Matched 'test' test");
break;
case /ing/.test(str):
display("• Matched 'ing' test");
break;
default:
display("• Didn't match any test");
break;
}
}
That works because of the way JavaScript switch
statements work, in particular two key aspects: First, that the cases are considered in source text order, and second that the selector expressions (the bits after the keyword case
) are expressions that are evaluated as that case is evaluated (not constants as in some other languages). So since our test expression is true
, the first case
expression that results in true
will be the one that gets used.
To load your data in WebView. Call loadData() method of WebView
wv.loadData(yourData, "text/html", "UTF-8");
You can check this example
http://developer.android.com/reference/android/webkit/WebView.html
[Edit 1]
You should add -- \ -- before -- " -- for example --> name=\"spanish press\"
below string worked for me
String webData = "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
"content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+
"<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+
"<script src=\"http://www.myscript.com/a\"></script>slkassldkassdksasdkasskdsk</body></html>";
I felt like this needed an answer in case somebody wanted to change just a single edittext. I do it like this:
editText.getBackground().mutate().setColorFilter(ContextCompat.getColor(context, R.color.your_color), PorterDuff.Mode.SRC_ATOP);
If you want to get
localhost:2806
from
http://localhost:2806/Pages/
then use:
HttpContext.Current.Request.Url.Authority
in Powershell: $env:logonserver
The data.table
package has its IDate
class and functionalities similar to lubridate
or the zoo
package. You could do:
dt = data.table(
Name = c('Joe', 'Amy', 'John'),
JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
AmtPaid = c(1000, 100, 200)
)
require(data.table)
dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]
Use:
set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );
Or possibly:
SET TIMING ON;
-- do stuff
SET TIMING OFF;
...to get the hundredths of seconds that elapsed.
In either case, time elapsed can be impacted by server load/etc.
Reference:
meteor add thelohoadmin:bootstrap@=3.3.7
solves the issue. You get the latest bootstrap and no warning messages.
You could use:
Dim MyForm As New Form1
MyForm.Show()
or rather:
MyForm.ShowDialog()
to open the form as a dialog box to ensure that user interacts with the new form or closes it.
You need to set the "linker search paths" of the project (for both Debug and Release builds). If this library was in, say, a sibling directory to the project then you can set it like this:
$(PROJECT_DIR)/../GoogleAnalytics/lib
(you want to avoid using an absolute path, instead keep the library directory relative to the project).
Try this...
<div class="row">
<div class="col-xs-3">
Menu
</div>
<div class="col-xs-9">
<div class="row">
<div class="col-sm-4 col-sm-push-8">
Right content
</div>
<div class="col-sm-8 col-sm-pull-4">
Content
</div>
</div>
</div>
</div>
To get you started, here is a list of PHP Editors (Wikipedia).
There are multiple issues with the MMC however as on almost every PC in my business the ask scheduler API will not open and has somehow been corrupted. So you cannot edit, delete or otherwise modify tasks that were developed before the API decided not to run anymore. The only way we have found to fix that issue is to totally wipe away a persons profile under the C:\Users\ area and force the system to recreate the log in once the person logs back in. This seems to fix the API issue and it works again, however the tasks are often not visible anymore to that user since the tasks developed are specific to the user and not the machine in Windows 7. The other odd thing is that sometimes, although not with any frequency that can be analyzed, the tasks still run even though the API is corrupted and will not open. The cause of this issue is apparently not known but there are many "fixes" described on various websites, but the user profile deletion and adding anew seems to work every time for at least a little while. The tasks are saved as XML now in WIN 7, so if you do find them in the system32/tasks folder you can delete them, or copy them to a new drive and then import them back into task scheduler. We went with the system scheduler software from Splinterware though since we had the same corruption issue multiple times even with the fix that does not seem to be permanent.
You can use this configuration:
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M
Try http://www.icescrum.org . It is free to use. And it has lot of cool features. Perfect for scrum teams.
Like timber said - "Java 8 Collection has a nice method called removeIf that makes things easier and safer"
Here is the code that solve your problem:
set.removeIf((Integer element) -> {
return (element % 2 == 0);
});
Now your set contains only odd values.
if (android.os.Build.VERSION.SDK_INT >= 21) {
storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position], context.getTheme()));
} else {
storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position]));
}
For future reference, you can get help for any command by using the /?
switch, which should explain what switches do what.
According to the set /?
screen, the format for set /p
is SET /P variable=[promptString]
which would indicate that the p in /p
is "prompt." It just prints in your example because <nul
passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.
/L
in for /L
generates a List of numbers.
From ping /?
:
Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
[-r count] [-s count] [[-j host-list] | [-k host-list]]
[-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name
Options:
-t Ping the specified host until stopped.
To see statistics and continue - type Control-Break;
To stop - type Control-C.
-a Resolve addresses to hostnames.
-n count Number of echo requests to send.
-l size Send buffer size.
-f Set Don't Fragment flag in packet (IPv4-only).
-i TTL Time To Live.
-v TOS Type Of Service (IPv4-only. This setting has been deprecated
and has no effect on the type of service field in the IP Header).
-r count Record route for count hops (IPv4-only).
-s count Timestamp for count hops (IPv4-only).
-j host-list Loose source route along host-list (IPv4-only).
-k host-list Strict source route along host-list (IPv4-only).
-w timeout Timeout in milliseconds to wait for each reply.
-R Use routing header to test reverse route also (IPv6-only).
-S srcaddr Source address to use.
-4 Force using IPv4.
-6 Force using IPv6.
I found a useful generic template that can help implement the correct disposal pattern for COM objects, that need Marshal.ReleaseComObject called when they go out of scope:
Usage:
using (AutoReleaseComObject<Application> excelApplicationWrapper = new AutoReleaseComObject<Application>(new Application()))
{
try
{
using (AutoReleaseComObject<Workbook> workbookWrapper = new AutoReleaseComObject<Workbook>(excelApplicationWrapper.ComObject.Workbooks.Open(namedRangeBase.FullName, false, false, missing, missing, missing, true, missing, missing, true, missing, missing, missing, missing, missing)))
{
// do something with your workbook....
}
}
finally
{
excelApplicationWrapper.ComObject.Quit();
}
}
Template:
public class AutoReleaseComObject<T> : IDisposable
{
private T m_comObject;
private bool m_armed = true;
private bool m_disposed = false;
public AutoReleaseComObject(T comObject)
{
Debug.Assert(comObject != null);
m_comObject = comObject;
}
#if DEBUG
~AutoReleaseComObject()
{
// We should have been disposed using Dispose().
Debug.WriteLine("Finalize being called, should have been disposed");
if (this.ComObject != null)
{
Debug.WriteLine(string.Format("ComObject was not null:{0}, name:{1}.", this.ComObject, this.ComObjectName));
}
//Debug.Assert(false);
}
#endif
public T ComObject
{
get
{
Debug.Assert(!m_disposed);
return m_comObject;
}
}
private string ComObjectName
{
get
{
if(this.ComObject is Microsoft.Office.Interop.Excel.Workbook)
{
return ((Microsoft.Office.Interop.Excel.Workbook)this.ComObject).Name;
}
return null;
}
}
public void Disarm()
{
Debug.Assert(!m_disposed);
m_armed = false;
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
#if DEBUG
GC.SuppressFinalize(this);
#endif
}
#endregion
protected virtual void Dispose(bool disposing)
{
if (!m_disposed)
{
if (m_armed)
{
int refcnt = 0;
do
{
refcnt = System.Runtime.InteropServices.Marshal.ReleaseComObject(m_comObject);
} while (refcnt > 0);
m_comObject = default(T);
}
m_disposed = true;
}
}
}
Reference:
http://www.deez.info/sengelha/2005/02/11/useful-idisposable-class-3-autoreleasecomobject/
Assuming this problem still has not be resolved, a lot of individual files don't end their code with a semicolon. Most jQuery scripts end with (jQuery)
and you need to have (jQuery);
.
As separate files the script will load just fine but as one individual file you need the semicolons.
You can you with your source folder so whenever you build, those files are automatically copied to the classes directory.
Instead of using properties file, use XML file.
If the data is too small, you can even use web.xml for accessing the properties.
Please note that any of these approach will require app server restart for changes to be reflected.
It's a lambda expression.
It means that, from the listOfCars, arg0 is one of the items of that list. With that item he is going to do, hence the ->, whatever is inside of the brackets.
In this example, he's going to return a list of cars that fit the condition
Car.SEDAN == ((Car)arg0).getStyle();
\p{L}
matches a single code point in the category "letter".
\p{N}
matches any kind of numeric character in any script.
Source: regular-expressions.info
If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.
<asp:TextBox runat="server" ID="txtPassword" placeholder="Password">
This will work you might some time feel that it is not working due to Intellisence not showing placeholder
remember that the use of "live" is for "jQuery 1.3" or higher
in version "jQuery 1.4.3" or higher is used "delegate"
and version "jQuery 1.7 +" or higher is used "on"
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+
As of jQuery 1.7, the .live() method is deprecated.
check http://api.jquery.com/live/
Regards, Fernando
.id
is not a valid jquery function. You need to use the .attr()
function to access attributes an element possesses. You can use .attr()
to both change an attribute value by specifying two parameters, or get the value by specifying one.
This method is working for me:
public sCdateToJsDate(cSDate: any): Date {
// cSDate is '2017-01-24T14:14:55.807'
var datestr = cSDate.toString();
var dateAr = datestr.split('-');
var year = parseInt(dateAr[0]);
var month = parseInt(dateAr[1])-1;
var day = parseInt(dateAr[2].substring(0, dateAr[2].indexOf("T")));
var timestring = dateAr[2].substring(dateAr[2].indexOf("T") + 1);
var timeAr = timestring.split(":");
var hour = parseInt(timeAr[0]);
var min = parseInt(timeAr[1]);
var sek = parseInt(timeAr[2]);
var date = new Date(year, month, day, hour, min, sek, 0);
return date;
}
Not mentioned above but using max-width
or max-height
on the canvas element is also a possibility.
I am not sure if previous versions of pandas
prevented this but now the following snippet works perfectly for me and produces exactly what you want without having to use apply
>>> import pandas as pd
>>> from sklearn.preprocessing import MinMaxScaler
>>> scaler = MinMaxScaler()
>>> dfTest = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],
'B':[103.02,107.26,110.35,114.23,114.68],
'C':['big','small','big','small','small']})
>>> dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A', 'B']])
>>> dfTest
A B C
0 0.000000 0.000000 big
1 0.926219 0.363636 small
2 0.935335 0.628645 big
3 1.000000 0.961407 small
4 0.938495 1.000000 small
In VSCODE ctrl+z (undo) worked for me
I did git checkout .
instead of git add .
and all my file changes were lost.
But Now using command + z
in my mac , recovered the changes and saved a tone of work for me.
In case any one wants it in Kotlin :
val dialogBuilder = AlertDialog.Builder(this)
// ...Irrelevant code for customizing the buttons and title
val dialogView = layoutInflater.inflate(R.layout.alert_label_editor, null)
dialogBuilder.setView(dialogView)
val editText = dialogView.findViewById(R.id.label_field)
editText.setText("test label")
val alertDialog = dialogBuilder.create()
alertDialog.show()
Reposted @user370305's answer.
To those on macOS Catalina using the zsh
shell who have also installed the postgres app:
Open your ~/.zshrc
file, and add the following line:
export PATH="/Applications/Postgres.app/Contents/Versions/latest/bin:$PATH"
Then close all your terminals, reopen them, and you'll have resolved your problem.
If you don't want to close your terminals, simply enter source ~/.zshrc
in whatever terminal you'd like to keep working on.
Q: The programming model is event driven, especially the way it handles I/O.
Correct. It uses call-backs, so any request to access the file system would cause a request to be sent to the file system and then Node.js would start processing its next request. It would only worry about the I/O request once it gets a response back from the file system, at which time it will run the callback code. However, it is possible to make synchronous I/O requests (that is, blocking requests). It is up to the developer to choose between asynchronous (callbacks) or synchronous (waiting).
Q: It uses JavaScript and the parser is V8.
Yes
Q: It can be easily used to create concurrent server applications.
Yes, although you'd need to hand-code quite a lot of JavaScript. It might be better to look at a framework, such as http://www.easynodejs.com/ - which comes with full online documentation and a sample application.
The below worked for me..
in Dog.java
public Class Dog{
private String a,b;
public Dog(){} //no args constructor
public Dog(Dog d){ // copy constructor
this.a=d.a;
this.b=d.b;
}
}
-------------------------
private List<Dog> createCopy(List<Dog> dogs) {
List<Dog> newDogsList= new ArrayList<>();
if (CollectionUtils.isNotEmpty(dogs)) {
dogs.stream().forEach(dog-> newDogsList.add((Dog) SerializationUtils.clone(dog)));
}
return newDogsList;
}
Here the new list which got created from createCopy method is created through SerializationUtils.clone(). So any change made to new list will not affect original list
You don't need a wrapper, just use the body as the wrapper.
CSS:
body {
margin:0 auto;
width:200px;
}
HTML:
<body>
<p>some content</p>
<body>
You can load data from a csv or text file. If you have a text file with records from a table, you can load those records within the table. For example if you have a text file, where each row is a record with the values for each column, you can load the records this way.
id //field 1
name //field2
1,peter
2,daniel
...
--example on windows
LOAD DATA LOCAL INFILE 'C:\\directory_example\\table.txt'
INTO TABLE Table
CHARACTER SET UTF8
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n';
Use urllib2. For more specifics, check out this example from doc.python.org:
Here's a snippet from the tutorial that may help
import urllib2
req = urllib2.Request('ftp://example.com')
response = urllib2.urlopen(req)
the_page = response.read()
Today date:
$( ".selector" ).datepicker( "setDate", new Date());
// Or on the init
$( ".selector" ).datepicker({ defaultDate: new Date() });
15 days from today:
$( ".selector" ).datepicker( "setDate", 15);
// Or on the init
$( ".selector" ).datepicker({ defaultDate: 15 });
You might also consider trying one of these approaches, since larger tables aren't exactly friendly on mobile even if it works:
http://elvery.net/demo/responsive-tables/
I'm partial to 'No More Tables' but that obviously depends on your application.
You can use the sys.dm_tran_locks
view, which returns information about the currently active lock manager resources.
Try this
SELECT
SessionID = s.Session_id,
resource_type,
DatabaseName = DB_NAME(resource_database_id),
request_mode,
request_type,
login_time,
host_name,
program_name,
client_interface_name,
login_name,
nt_domain,
nt_user_name,
s.status,
last_request_start_time,
last_request_end_time,
s.logical_reads,
s.reads,
request_status,
request_owner_type,
objectid,
dbid,
a.number,
a.encrypted ,
a.blocking_session_id,
a.text
FROM
sys.dm_tran_locks l
JOIN sys.dm_exec_sessions s ON l.request_session_id = s.session_id
LEFT JOIN
(
SELECT *
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle)
) a ON s.session_id = a.session_id
WHERE
s.session_id > 50
Here example on plain JS:
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
outline: none;_x000D_
}
_x000D_
<div _x000D_
id="myDiv"_x000D_
tabindex="0"_x000D_
>_x000D_
Press me and start typing_x000D_
</div>
_x000D_
Create a file with this name:
touch .git/rebase-merge/head-name
and than use git rebase
I have Written a small script to download the live youtube video, you may use as single command as well. script it can be invoked simply as,
~/ytdl_lv.sh <URL> <output file name>
e.g.
~/ytdl_lv.sh https://www.youtube.com/watch?v=BLIGxsYLyjc myfile.mp4
script is as simple as below,
#!/bin/bash
# ytdl_lv.sh
# Author Prashant
#
URL=$1
OUTNAME=$2
streamlink --hls-live-restart -o ${OUTNAME} ${URL} best
here the best is the stream quality, it also can be 144p (worst), 240p, 360p, 480p, 720p (best)
More about string can be found in String Class and String Tutorials
require 'rubygems'
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :ie
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")
More file types and options are available and you can see them in file takes_screenshot.rb.
multiprocessing is not like threading. Each child process will get a copy of the main process's memory. Generally state is shared via communication (pipes/sockets), signals, or shared memory.
Multiprocessing makes some abstractions available for your use case - shared state that's treated as local by use of proxies or shared memory: http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes
Relevant sections:
The simplest solution is :
listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
listView.setStackFromBottom(true);
First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.
If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
'do something
End If
End If
reg
and wire
specify how the object will be assigned and are therefore only meaningful for outputs.
If you plan to assign your output in sequential code,such as within an always
block, declare it as a reg
(which really is a misnomer for "variable" in Verilog). Otherwise, it should be a wire
, which is also the default.
You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.
In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.
I added
config.EnableCors(new EnableCorsAttribute(Properties.Settings.Default.Cors, "", ""))
as well as
app.UseCors(CorsOptions.AllowAll);
on the server. This results in two header entries. Just use the latter one and it works.
Update: More useful information What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?
Maybe this url can help you: Activating Browser Modes with Doctype
Edit: Today we were able to override the compatibility view with:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
There's an important thing that people always seem to overlook:
You can pass a plain array to something which accepts an IList<T>
parameter, and then you can call IList.Add()
and will receive a runtime exception:
Unhandled Exception: System.NotSupportedException: Collection was of a fixed size.
For example, consider the following code:
private void test(IList<int> list)
{
list.Add(1);
}
If you call that as follows, you will get a runtime exception:
int[] array = new int[0];
test(array);
This happens because using plain arrays with IList<T>
violates the Liskov substitution principle.
For this reason, if you are calling IList<T>.Add()
you may want to consider requiring a List<T>
instead of an IList<T>
.
Here is the code that Reto Meier used in the Google I/O presentation this year to get a unique id for the user:
private static String uniqueID = null;
private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
public synchronized static String id(Context context) {
if (uniqueID == null) {
SharedPreferences sharedPrefs = context.getSharedPreferences(
PREF_UNIQUE_ID, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
if (uniqueID == null) {
uniqueID = UUID.randomUUID().toString();
Editor editor = sharedPrefs.edit();
editor.putString(PREF_UNIQUE_ID, uniqueID);
editor.commit();
}
}
return uniqueID;
}
If you couple this with a backup strategy to send preferences to the cloud (also described in Reto's talk, you should have an id that ties to a user and sticks around after the device has been wiped, or even replaced. I plan to use this in analytics going forward (in other words, I have not done that bit yet :).
An expression like this:
[a-zA-Z]*[0-9\+\*][a-zA-Z0-9\+\*]*
should work just fine (obviously insert any additional special characters you want to allow or use ^ operator to match anything except letters/numbers); no need to use complicated lookarounds. This approach makes sense if you only want to allow a certain subset of special characters that you know are "safe", and disallow all others.
If you want to include all special characters except certain ones which you know are "unsafe", then it makes sense to use something like:
\w[^\\]*[^a-zA-Z\\][^\\]*
In this case, you are explicitly disallowing backslashes in your password and allowing any combination with at least one non-alphabetic character otherwise.
The expression above will match any string containing letters and at least one number or +,*. As for the "length of 8" requirement, theres really no reason to check that using regex.
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
print(myInt.runtimeType);
var myDouble = double.parse('123.45');
assert(myInt is double);
print(myDouble); // 123.45
print(myDouble.runtimeType);
I don't yet see a viable answer for 2.7 which doesn't require installing additional dependencies and also starts from the file's directory. It's not nice as a single-line solution, but there's nothing wrong with using the standard utilities.
import os
grandparent_dir = os.path.abspath( # Convert into absolute path string
os.path.join( # Current file's grandparent directory
os.path.join( # Current file's parent directory
os.path.dirname( # Current file's directory
os.path.abspath(__file__) # Current file path
),
os.pardir
),
os.pardir
)
)
print grandparent_dir
And to prove it works, here I start out in ~/Documents/notes
just so that I show the current directory doesn't influence outcome. I put the file grandpa.py
with that script in a folder called "scripts". It crawls up to the Documents dir and then to the user dir on a Mac.
(testing)AlanSE-OSX:notes AlanSE$ echo ~/Documents/scripts/grandpa.py
/Users/alancoding/Documents/scripts/grandpa.py
(testing)AlanSE-OSX:notes AlanSE$ python2.7 ~/Documents/scripts/grandpa.py
/Users/alancoding
This is the obvious extrapolation of the answer for the parent dir. Better to use a general solution than a less-good solution in fewer lines.
The following should work fine:
git diff -z --name-only commit1 commit2 | xargs -0 -IREPLACE rsync -aR REPLACE /home/changes/protected/
To explain further:
The -z
to with git diff --name-only
means to output the list of files separated with NUL bytes instead of newlines, just in case your filenames have unusual characters in them.
The -0
to xargs
says to interpret standard input as a NUL-separated list of parameters.
The -IREPLACE
is needed since by default xargs
would append the parameters to the end of the rsync
command. Instead, that says to put them where the later REPLACE
is. (That's a nice tip from this Server Fault answer.)
The -a
parameter to rsync
means to preserve permissions, ownership, etc. if possible. The -R
means to use the full relative path when creating the files in the destination.
Update: if you have an old version of xargs
, you'll need to use the -i
option instead of -I
. (The former is deprecated in later versions of findutils
.)
There are 3 problems.
1) Incorrect decimal separator
Different cultures use different decimal separators (namely ,
and .
).
If you replace .
with ,
it should work as expected:
Console.WriteLine(Convert.ToDouble("52,8725945"));
You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture
(What is the invariant culture) e.g. using double.Parse
:
double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);
You should also take a look at double.TryParse
, you can use it with many options and it is especially useful to check wheter or not your string is a valid double
.
2) You have an incorrect double
One of your values is incorrect, because it contains two dots:
15.5859949000000662452.23862099999999
3) Your array has an empty value at the end, which is an incorrect double
You can use overloaded Split
which removes empty values:
string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
List comprehension can shorten things...
win_percentages = [m**2.0 / (m**2.0 + n**2.0) * 100 for m, n in [a[i] for i in NL_East]]
The Following command displays extra informations
curl -X POST http://httpbin.org/post -v > /dev/null
You can ask server to send just HEAD, instead of full response
curl -X HEAD -I http://httpbin.org/
Note:
In some cases, server may send different headers for POST and HEAD. But in almost all cases headers are same.
I have made my own solution using NSTimer and Alamofire:
import Alamofire
public class ConnectionHelper: NSObject {
var request: Alamofire.Request?
func isInternetConnected(completionHandler: Bool -> Void) {
NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "requestTimeout", userInfo: nil, repeats: false)
request = Alamofire
.request(
Method.HEAD,
"http://www.testurl.com"
)
.response { response in
if response.3?.code == -999 {
completionHandler(
false
)
} else {
completionHandler(
true
)
}
}
}
func requestTimeout() {
request!.cancel()
}
}
The NSTimer is used as a timeout, and was used due to unreliable results using the Alamofire timeout. The request should be made to a URL you trust to be reliable, such as your own server or the server that is hosting the services you depend on.
When the timer expires, the request is cancelled and the results are returned using a completion handler.
Usage:
ConnectionHelper().isInternetConnected() { internetConnected in
if internetConnected {
// Connected
} else {
// Not connected
}
}
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:buttonStyle">@style/Button</item>
</style>
<style name="Button" parent="Widget.AppCompat.Button">
<item name="android:textAllCaps">false</item>
</style>
As you are probably aware, int
s are stored internally in binary. Typically an int
contains 32 bits, but in some environments might contain 16 or 64 bits (or even a different number, usually but not necessarily a power of two).
But for this example, let's look at 4-bit integers. Tiny, but useful for illustration purposes.
Since there are four bits in such an integer, it can assume one of 16 values; 16 is two to the fourth power, or 2 times 2 times 2 times 2. What are those values? The answer depends on whether this integer is a signed int
or an unsigned int
. With an unsigned int
, the value is never negative; there is no sign associated with the value. Here are the 16 possible values of a four-bit unsigned int
:
bits value
0000 0
0001 1
0010 2
0011 3
0100 4
0101 5
0110 6
0111 7
1000 8
1001 9
1010 10
1011 11
1100 12
1101 13
1110 14
1111 15
... and Here are the 16 possible values of a four-bit signed int
:
bits value
0000 0
0001 1
0010 2
0011 3
0100 4
0101 5
0110 6
0111 7
1000 -8
1001 -7
1010 -6
1011 -5
1100 -4
1101 -3
1110 -2
1111 -1
As you can see, for signed int
s the most significant bit is 1
if and only if the number is negative. That is why, for signed int
s, this bit is known as the "sign bit".
Only thing i found is the BetterSource extension for Safari this will show you the manipulated source of the document only downside is nothing remotely like it for Firefox
if using homebrew you can update sim links using
brew link --overwrite git
The simple answer to the basic question is no. The only cross-browser option is to create a hack that accomplishes what you want. This approach does carry with it certain potential issues when it comes to styling pre-existing content, but it provides for more customization of the outline (offset, width, line style) than many of the other solutions.
On a basic level, consider the following static example (run the snippent for demo):
.outline {_x000D_
border: 2px dotted transparent;_x000D_
border-radius: 5px;_x000D_
display: inline-block;_x000D_
padding: 2px;_x000D_
margin: -4px;_x000D_
}_x000D_
_x000D_
/* :focus-within does not work in Edge or IE */_x000D_
.outline:focus-within, .outline.edge {_x000D_
border-color: blue;_x000D_
}_x000D_
_x000D_
br {_x000D_
margin-bottom: 0.75rem;_x000D_
}
_x000D_
<h3>Javascript-Free Demo</h3>_x000D_
<div class="outline edge"><input type="text" placeholder="I always have an outline"/></div><br><div class="outline"><input type="text" placeholder="I have an outline when focused"/></div> *<i>Doesn't work in Edge or IE</i><br><input type="text" placeholder="I have never have an outline" />_x000D_
<p>Note that the outline does not increase the spacing between the outlined input and other elements around it. The margin (-4px) compensates for the space that the outlines padding (-2px) and width (2px) take up, a total of 4px.</p>
_x000D_
Now, on a more advanced level, it would be possible to use JavaScript to bootstrap elements of a given type or class so that they are wrapped inside a div that simulates an outline on page load. Furthermore, event bindings could be established to show or hide the outline on user interactions like this (run the snippet below or open in JSFiddle):
h3 {_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
div {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.clickable {_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.box {_x000D_
background: red;_x000D_
border: 1px solid black;_x000D_
border-radius: 10px;_x000D_
height: 5rem;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
text-align: center;_x000D_
color: white;_x000D_
font-weight: bold;_x000D_
padding: 0.5rem;_x000D_
margin: 1rem;_x000D_
}
_x000D_
<h3>Javascript-Enabled Demo</h3>_x000D_
<div class="flex">_x000D_
<div class="box outline-me">I'm outlined because I contain<br>the "outline-me" class</div>_x000D_
<div class="box clickable">Click me to toggle outline</div>_x000D_
</div>_x000D_
<hr>_x000D_
<input type="text" placeholder="I'm outlined when focused" />_x000D_
_x000D_
<script>_x000D_
// Called on an element to wrap with an outline and passed a styleObject_x000D_
// the styleObject can contain the following outline properties:_x000D_
// style, width, color, offset, radius, bottomLeftRadius,_x000D_
// bottomRightRadius, topLeftRadius, topRightRadius_x000D_
// It then creates a new div with the properties specified and _x000D_
// moves the calling element into the div_x000D_
// The newly created wrapper div receives the class "simulated-outline"_x000D_
Element.prototype.addOutline = function (styleObject, hideOutline = true) {_x000D_
var element = this;_x000D_
_x000D_
// create a div for simulating an outline_x000D_
var outline = document.createElement('div');_x000D_
_x000D_
// initialize css formatting_x000D_
var css = 'display:inline-block;';_x000D_
_x000D_
// transfer any element margin to the outline div_x000D_
var margins = ['marginTop', 'marginBottom', 'marginLeft', 'marginRight'];_x000D_
var marginPropertyNames = { _x000D_
marginTop: 'margin-top',_x000D_
marginBottom: 'margin-bottom',_x000D_
marginLeft: 'margin-left',_x000D_
marginRight: 'margin-right'_x000D_
}_x000D_
var outlineWidth = Number.parseInt(styleObject.width);_x000D_
var outlineOffset = Number.parseInt(styleObject.offset);_x000D_
for (var i = 0; i < margins.length; ++i) {_x000D_
var computedMargin = Number.parseInt(getComputedStyle(element)[margins[i]]);_x000D_
var margin = computedMargin - outlineWidth - outlineOffset;_x000D_
css += marginPropertyNames[margins[i]] + ":" + margin + "px;";_x000D_
}_x000D_
element.style.cssText += 'margin:0px !important;';_x000D_
_x000D_
// compute css border style for the outline div_x000D_
var keys = Object.keys(styleObject);_x000D_
for (var i = 0; i < keys.length; ++i) {_x000D_
var key = keys[i];_x000D_
var value = styleObject[key];_x000D_
switch (key) {_x000D_
case 'style':_x000D_
var property = 'border-style';_x000D_
break;_x000D_
case 'width':_x000D_
var property = 'border-width';_x000D_
break;_x000D_
case 'color':_x000D_
var property = 'border-color';_x000D_
break;_x000D_
case 'offset':_x000D_
var property = 'padding';_x000D_
break;_x000D_
case 'radius':_x000D_
var property = 'border-radius';_x000D_
break;_x000D_
case 'bottomLeftRadius':_x000D_
var property = 'border-bottom-left-radius';_x000D_
break;_x000D_
case 'bottomRightRadius':_x000D_
var property = 'border-bottom-right-radius';_x000D_
break;_x000D_
case 'topLeftRadius':_x000D_
var property = 'border-top-left-radius-style';_x000D_
break;_x000D_
case 'topRightRadius':_x000D_
var property = 'border-top-right-radius';_x000D_
break;_x000D_
}_x000D_
css += property + ":" + value + ';';_x000D_
}_x000D_
_x000D_
// apply the computed css to the outline div_x000D_
outline.style.cssText = css;_x000D_
_x000D_
// add a class in case we want to do something with elements_x000D_
// receiving a simulated outline_x000D_
outline.classList.add('simulated-outline');_x000D_
_x000D_
// place the element inside the outline div_x000D_
var parent = element.parentElement;_x000D_
parent.insertBefore(outline, element);_x000D_
outline.appendChild(element);_x000D_
_x000D_
// determine whether outline should be hidden by default or not_x000D_
if (hideOutline) element.hideOutline();_x000D_
}_x000D_
_x000D_
Element.prototype.showOutline = function () {_x000D_
var element = this;_x000D_
// get a reference to the outline element that wraps this element_x000D_
var outline = element.getOutline();_x000D_
// show the outline if one exists_x000D_
if (outline) outline.classList.remove('hide-outline');_x000D_
}_x000D_
_x000D_
_x000D_
Element.prototype.hideOutline = function () {_x000D_
var element = this;_x000D_
// get a reference to the outline element that wraps this element_x000D_
var outline = element.getOutline();_x000D_
// hide the outline if one exists_x000D_
if (outline) outline.classList.add('hide-outline');_x000D_
}_x000D_
_x000D_
// Determines if this element has an outline. If it does, it returns the outline_x000D_
// element. If it doesn't have one, return null._x000D_
Element.prototype.getOutline = function() {_x000D_
var element = this;_x000D_
var parent = element.parentElement;_x000D_
return (parent.classList.contains('simulated-outline')) ? parent : null;_x000D_
}_x000D_
_x000D_
// Determines the visiblity status of the outline, returning true if the outline is_x000D_
// visible and false if it is not. If the element has no outline, null is returned._x000D_
Element.prototype.outlineStatus = function() {_x000D_
var element = this;_x000D_
var outline = element.getOutline();_x000D_
if (outline === null) {_x000D_
return null;_x000D_
} else {_x000D_
return !outline.classList.contains('hide-outline');_x000D_
}_x000D_
}_x000D_
_x000D_
// this embeds a style element in the document head for handling outline visibility_x000D_
var embeddedStyle = document.querySelector('#outline-styles');_x000D_
if (!embeddedStyle) {_x000D_
var style = document.createElement('style');_x000D_
style.innerText = `_x000D_
.simulated-outline.hide-outline {_x000D_
border-color: transparent !important;_x000D_
}_x000D_
`;_x000D_
document.head.append(style);_x000D_
}_x000D_
_x000D_
_x000D_
/*########################## example usage ##########################*/_x000D_
_x000D_
// add outline to all elements with "outline-me" class_x000D_
var outlineMeStyle = {_x000D_
style: 'dashed',_x000D_
width: '3px',_x000D_
color: 'blue',_x000D_
offset: '2px',_x000D_
radius: '5px'_x000D_
};_x000D_
document.querySelectorAll('.outline-me').forEach((element)=>{_x000D_
element.addOutline(outlineMeStyle, false);_x000D_
});_x000D_
_x000D_
_x000D_
// make clickable divs get outlines_x000D_
var outlineStyle = {_x000D_
style: 'double',_x000D_
width: '4px',_x000D_
offset: '3px',_x000D_
color: 'red',_x000D_
radius: '10px'_x000D_
};_x000D_
document.querySelectorAll('.clickable').forEach((element)=>{_x000D_
element.addOutline(outlineStyle);_x000D_
element.addEventListener('click', (evt)=>{_x000D_
var element = evt.target;_x000D_
(element.outlineStatus()) ? element.hideOutline() : element.showOutline();_x000D_
});_x000D_
});_x000D_
_x000D_
_x000D_
// configure inputs to only have outline on focus_x000D_
document.querySelectorAll('input').forEach((input)=>{_x000D_
var outlineStyle = {_x000D_
width: '2px',_x000D_
offset: '2px',_x000D_
color: 'black',_x000D_
style: 'dotted',_x000D_
radius: '10px'_x000D_
}_x000D_
input.addOutline(outlineStyle);_x000D_
input.addEventListener('focus', (evt)=>{_x000D_
var input = evt.target;_x000D_
input.showOutline();_x000D_
});_x000D_
input.addEventListener('blur', (evt)=>{_x000D_
var input = evt.target;_x000D_
input.hideOutline();_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
In closing, let me reiterate, that implementing this approach may require more styling than what I have included in my demos, especially if you have already styled the element you want outlined.
Use [^\p{L}\p{Nd}]+
- this matches all (Unicode) characters that are neither letters nor (decimal) digits.
In Java:
String resultString = subjectString.replaceAll("[^\\p{L}\\p{Nd}]+", "");
Edit:
I changed \p{N}
to \p{Nd}
because the former also matches some number symbols like ¼
; the latter doesn't. See it on regex101.com.
I just did something like this. My solution for this was to replace the interior for loop with a list comprehension.
for ii in range(200):
done = any([op(ii, jj) for jj in range(200, 400)])
...block0...
if done:
continue
...block1...
where op is some boolean operator acting on a combination of ii and jj. In my case, if any of the operations returned true, I was done.
This is really not that different from breaking the code out into a function, but I thought that using the "any" operator to do a logical OR on a list of booleans and doing the logic all in one line was interesting. It also avoids the function call.
You can avoid refactoring your code by including the following JavaScript code
jQuery.fn.extend({
live: function (event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
return this;
}
});
where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS')
should work.
If you are wanting a client side validation also so you get less of a need to throw exceptions you could try to implement client side file size validation.
Note: This only works in browsers that support HTML5. http://www.html5rocks.com/en/tutorials/file/dndfiles/
<form id="FormID" action="post" name="FormID">
<input id="target" name="target" class="target" type="file" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$('.target').change(function () {
if (typeof FileReader !== "undefined") {
var size = document.getElementById('target').files[0].size;
// check file size
if (size > 100000) {
$(this).val("");
}
}
});
</script>
Here's a neat little workaround:
You can use a Greek Lower Numeral Sign instead (U+0375)
It looks like this ?
Using this method saves you a lot of resources too...
If I understand well, you want to Join ScheduleRequest
with User
and apply the in
clause to the userName
property of the entity User
.
I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join
part (because it handles the Join
logic outside the Criteria Query).
List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);
In order to write more type-safe code you could also use Metamodel by replacing this line:
Expression<String> exp = scheduleRequest.get("createdBy");
with this:
Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);
If it works, then you may try to add the Join
logic into the Criteria Query
. But right now I can't test it, so I prefer to see if somebody else wants to try.
Not a perfect answer though may be code snippets might help.
public <T> List<T> findListWhereInCondition(Class<T> clazz,
String conditionColumnName, Serializable... conditionColumnValues) {
QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
addWhereInClause(queryBuilder, conditionColumnName,
conditionColumnValues);
queryBuilder.select();
return queryBuilder.getResultList();
}
private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
String conditionColumnName, Serializable... conditionColumnValues) {
Path<Object> path = queryBuilder.root.get(conditionColumnName);
In<Object> in = queryBuilder.criteriaBuilder.in(path);
for (Serializable conditionColumnValue : conditionColumnValues) {
in.value(conditionColumnValue);
}
queryBuilder.criteriaQuery.where(in);
}
None of the above helped for me.
I was able to install Mojave using this link here: http://dosdude1.com/mojave/ This patch worked beautifully and without a hitch
Proof: here's Mojave running on my (unsupported) 2011 Mac-mini
If it's just running (not a daemon) then just use Ctrl-C
.
If it's daemonized then you could try:
$ ps aux | grep node
you PID 1.5 0.2 44172 8260 pts/2 S 15:25 0:00 node app.js
$ kill -2 PID
Where PID
is replaced by the number in the output of ps
.
I recompiled the package specification, even though the change was only in the package body. This resolved my issue
You could set your property in the model's constructor
public YourModel()
{
As = true;
}
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
IF EXISTS
(SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'functionName')
AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION functionName
GO
I had the same problem and i tried solutions from Metadata file '.dll' could not be found
but none of these worked.
So after trial and error i fixed it by unloading and reloading the project doing this reset the configuration file and fixed the issue.
try to clear workspace.
rm -rf ' ~/Library/Application\ Support/"your programm name" '
Your csv is malformed. The output is not three loopings but just one output. To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.
This is what your code sees
0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M
Try this
0,Filipe,19,M
1,Maria,20,F
2,Walter,60,M
while(file.good())
{
getline(file, ID, ',');
cout << "ID: " << ID << " " ;
getline(file, nome, ',') ;
cout << "User: " << nome << " " ;
getline(file, idade, ',') ;
cout << "Idade: " << idade << " " ;
getline(file, genero) ; \\ diff
cout << "Sexo: " << genero;\\diff
}
window.onload = function() {
var userImage = document.getElementById('imageOtherUser');
var hangoutButton = document.getElementById("hangoutButtonId");
userImage.onclick = function() {
hangoutButton.click(); // this will trigger the click event
};
};
this will do the trick
Swift 3+ one liner to sum properties of objects
var totalSum = scaleData.map({$0.points}).reduce(0, +)
Where points is the property in my custom object scaleData that I am trying to reduce
Use .closest()
with a selector:
var $div = $('#divid').closest('div[class^="div-a"]');
Here is a simpler code for the same:
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, $fp);
where $fp is a file handle to output errors. For example:
$fp = fopen(dirname(__FILE__).'/errorlog.txt', 'w');
( Read on http://curl.haxx.se/mail/curlphp-2008-03/0064.html )
Even after installing the sqlserver jar, my maven was trying to fetch the dependecy from maven repository. I then, provided my pom the repository of my local machine and it works fine after that...might be of help for someone.
<repository>
<id>local</id>
<name>local</name>
<url>file://C:/Users/mywindows/.m2/repository</url>
</repository>
From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.
The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.
If this issue is causing serious problems, here are a few things I would suggest:
Revert back to JDK 1.7.0_25 until a fix is added to the JDK.
Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.
Try the JDK early releases as they come out. One of them might fix your problem.
Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.
A possibility is to create a trigger on insert to add in the correct sequence number.
TL;DR:
git checkout HEAD path/to/file
git stash apply
Long version:
You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD
. You can undo changes to a specific file with git checkout HEAD path/to/file
. After removing the cause of the conflict, you can apply as usual.
Javascript Keycodes
Except this detail Colin & Tod's answer is working.
Generally, make an "inverse" commit, using:
git revert 364705c
then send it to the remote as usual:
git push
This won't delete the commit: it makes an additional commit that undoes whatever the first commit did. Anything else, not really safe, especially when the changes have already been propagated.
NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
NSString* firstBit = [foo objectAtIndex: 0];
Update 7/3/2018:
Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:
let substrings = "10/04/2011".split(separator: "/")
let firstBit = substrings[0]
Although note that it gives you an array of Substring
. If you need to convert these back to ordinary strings, use map
let strings = "10/04/2011".split(separator: "/").map{ String($0) }
let firstBit = strings[0]
or
let firstBit = String(substrings[0])
There is an easy way to get Jobs' Owners info from multiple instances by PowerShell:
Run the script in your PowerShell ISE:
Loads SQL Powerhell SMO and commands:
Import-Module SQLPS -disablenamechecking
BUild list of Servers manually (this builds an array list):
$SQLServers = "SERVERNAME\INSTANCE01","SERVERNAME\INSTANCE02","SERVERNAME\INSTANCE03";
$SysAdmins = $null;
foreach($SQLSvr in $SQLServers)
{
## - Add Code block:
$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLSvr;
DIR SQLSERVER:\SQL\$SQLSvr\JobServer\Jobs| FT $SQLSvr, NAME, OWNERLOGINNAME -Auto
## - End of Code block
}
Inline:
$('#link_other').find('a').attr('target','_blank');
I solved this problem temporary by disabling the dfs permission.By adding below property code to conf/hdfs-site.xml
<property>
<name>dfs.permissions</name>
<value>false</value>
</property>
Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:
I did a quick experiment after looking at a number of potential solutions all over the place. This is what I ended up with:
Don't forget to add payment methods on Google AdMod. It was my issue with "Error code 3". Anyway, when your account Google AdMod will be ready to show ads (for tested device or real users) they send you email that your account verified and ready to work! After this letter everything should work fine.
The error is telling you it cannot find the class because it is not available in your application.
If you are using Maven, make sure you have the dependency for jstl
artifact:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
If you are not using it, just make sure you include the JAR in your classpath. See this answer for download links.
$(document).on('change', '.custom-file-input', function (event) {
$(this).next('.custom-file-label').html(event.target.files[0].name);
})
Best of all worlds. Works on dynamically created inputs, and uses actual file name.
Give this link a try --> https://pypi.python.org/pypi/setuptools
I'm assuming you're on Windows (could be wrong) but if you click the green Downloads button, it should take you to a table where you can choose to download a .exe version of setuptools appropriate for your version of Python. All that eggsetup stuff should be taken care of in the executable file.
Let me know if you need more help.
Select
Count(Distinct user_id) As countUsers
, Count(site_id) As countVisits
, site_id As site
From cp_visits
Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Group By site_id
for non nulls
select count(a)
from us
for nulls
select count(*)
from us
minus
select count(a)
from us
Hence
SELECT COUNT(A) NOT_NULLS
FROM US
UNION
SELECT COUNT(*) - COUNT(A) NULLS
FROM US
ought to do the job
Better in that the column titles come out correct.
SELECT COUNT(A) NOT_NULL, COUNT(*) - COUNT(A) NULLS
FROM US
In some testing on my system, it costs a full table scan.
In order to get local time in pure Javascript use this built in function
// return new Date().toLocaleTimeString();
See below example
function getLocaltime(){
return new Date().toLocaleTimeString();
}
console.log(getLocaltime());
You must swap the order of your test:
From:
if (Attachment.Length > 0 && Attachment != null)
To:
if (Attachment != null && Attachment.Length > 0 )
The first version attempts to dereference Attachment
first and therefore throws if it's null. The second version will check for nullness first and only go on to check the length if it's not null (due to "boolean short-circuiting").
[EDIT] I come from the future to tell you that with later versions of C# you can use a "null conditional operator" to simplify the code above to:
if (Attachment?.Length > 0)