Similar symptoms (Facebook et al not correctly fetching og:image and other assets over https) can occur when the site's https certificate is not fully compliant.
Your site's https cert may seem valid (green key in the browser and all), but it will not scrape correctly if it's missing an intermediate or chain certificate. This can lead to many wasted hours checking and rechecking all the various caches and meta tags.
Might not have been your problem, but could be other's with similar symptoms (like mine). There's many ways to check your cert - the one I happened to use: https://www.sslshopper.com/ssl-checker.html
curb
looks like a great solution, but in case it doesn't meet your needs, you can do it with Net::HTTP
. A multipart form post is just a carefully-formatted string with some extra headers. It seems like every Ruby programmer who needs to do multipart posts ends up writing their own little library for it, which makes me wonder why this functionality isn't built-in. Maybe it is... Anyway, for your reading pleasure, I'll go ahead and give my solution here. This code is based off of examples I found on a couple of blogs, but I regret that I can't find the links anymore. So I guess I just have to take all the credit for myself...
The module I wrote for this contains one public class, for generating the form data and headers out of a hash of String
and File
objects. So for example, if you wanted to post a form with a string parameter named "title" and a file parameter named "document", you would do the following:
#prepare the query
data, headers = Multipart::Post.prepare_query("title" => my_string, "document" => my_file)
Then you just do a normal POST
with Net::HTTP
:
http = Net::HTTP.new(upload_uri.host, upload_uri.port)
res = http.start {|con| con.post(upload_uri.path, data, headers) }
Or however else you want to do the POST
. The point is that Multipart
returns the data and headers that you need to send. And that's it! Simple, right? Here's the code for the Multipart module (you need the mime-types
gem):
# Takes a hash of string and file parameters and returns a string of text
# formatted to be sent as a multipart form post.
#
# Author:: Cody Brimhall <mailto:[email protected]>
# Created:: 22 Feb 2008
# License:: Distributed under the terms of the WTFPL (http://www.wtfpl.net/txt/copying/)
require 'rubygems'
require 'mime/types'
require 'cgi'
module Multipart
VERSION = "1.0.0"
# Formats a given hash as a multipart form post
# If a hash value responds to :string or :read messages, then it is
# interpreted as a file and processed accordingly; otherwise, it is assumed
# to be a string
class Post
# We have to pretend we're a web browser...
USERAGENT = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/523.10.6 (KHTML, like Gecko) Version/3.0.4 Safari/523.10.6"
BOUNDARY = "0123456789ABLEWASIEREISAWELBA9876543210"
CONTENT_TYPE = "multipart/form-data; boundary=#{ BOUNDARY }"
HEADER = { "Content-Type" => CONTENT_TYPE, "User-Agent" => USERAGENT }
def self.prepare_query(params)
fp = []
params.each do |k, v|
# Are we trying to make a file parameter?
if v.respond_to?(:path) and v.respond_to?(:read) then
fp.push(FileParam.new(k, v.path, v.read))
# We must be trying to make a regular parameter
else
fp.push(StringParam.new(k, v))
end
end
# Assemble the request body using the special multipart format
query = fp.collect {|p| "--" + BOUNDARY + "\r\n" + p.to_multipart }.join("") + "--" + BOUNDARY + "--"
return query, HEADER
end
end
private
# Formats a basic string key/value pair for inclusion with a multipart post
class StringParam
attr_accessor :k, :v
def initialize(k, v)
@k = k
@v = v
end
def to_multipart
return "Content-Disposition: form-data; name=\"#{CGI::escape(k)}\"\r\n\r\n#{v}\r\n"
end
end
# Formats the contents of a file or string for inclusion with a multipart
# form post
class FileParam
attr_accessor :k, :filename, :content
def initialize(k, filename, content)
@k = k
@filename = filename
@content = content
end
def to_multipart
# If we can tell the possible mime-type from the filename, use the
# first in the list; otherwise, use "application/octet-stream"
mime_type = MIME::Types.type_for(filename)[0] || MIME::Types["application/octet-stream"][0]
return "Content-Disposition: form-data; name=\"#{CGI::escape(k)}\"; filename=\"#{ filename }\"\r\n" +
"Content-Type: #{ mime_type.simplified }\r\n\r\n#{ content }\r\n"
end
end
end
You can use it like this:
In Mvc:
@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});
In Html:
<input type="text" name="Id" data_val_number="10"/>
This information is outdated as of now, but cannot be deleted.
You can create File
instances just by specifying a path when your code is chrome-privileged:
new File("/path/to/file");
File
is a sub-class of Blob
, so all File
instances are also valid Blob
s.
Please note that this requires a platform path, and not a file URL.
Yes, FileReader
is available to addons.
File
and FileReader
are available in all window
s. If you want to use them in a non-window scope (like bootstrap.js
or a code module), you may use nsIDOMFile
/nsIDOMFileReader
.
In modern browsers, you can accomplish this with string.matchAll().
The benefit to this approach vs RegExp.exec()
is that it does not rely on the regex being stateful, as in @Gumbo's answer.
let regexp = /bar/g;
let str = 'foobarfoobar';
let matches = [...str.matchAll(regexp)];
matches.forEach((match) => {
console.log("match found at " + match.index);
});
_x000D_
public static <E> E[] arrayListToTypedArray(List<E> list) {
if (list == null) {
return null;
}
int noItems = list.size();
if (noItems == 0) {
return null;
}
E[] listAsTypedArray;
E typeHelper = list.get(0);
try {
Object o = Array.newInstance(typeHelper.getClass(), noItems);
listAsTypedArray = (E[]) o;
for (int i = 0; i < noItems; i++) {
Array.set(listAsTypedArray, i, list.get(i));
}
} catch (Exception e) {
return null;
}
return listAsTypedArray;
}
If you think the performance of the query will be better using the index, how could you force the query to use the index?
First you would of course verify that the index gave a better result for returning the complete data set, right?
The index hint is the key here, but the more up to date way of specifying it is with the column naming method rather than the index naming method. In your case you would use:
select /*+ index(table_name (column_having_index)) */ *
from table_name
where column_having_index="some value";
In more complex cases you might ...
select /*+ index(t (t.column_having_index)) */ *
from my_owner.table_name t,
...
where t.column_having_index="some value";
With regard to composite indexes, I'm not sure that you need to specify all columns, but it seems like a good idea. See the docs here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#autoId18 on multiple index_specs and use of index_combine for multiple indexes, and here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#BABGFHCH for the specification of multiple columns in the index_spec.
Paste this code to your pom.xml file. It works for me.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>
I found it easier to edit the project file directly e.g. YourApp.csproj.
You can do this by modifying ApplicationIcon
property element:
<ApplicationIcon>..\Path\To\Application.ico</ApplicationIcon>
Also, if you create an MSI installer for your application e.g. using WiX, you can use the same icon again for display in Add/Remove Programs. See tip 5 here.
I would say you have an indentation problem, at least as you wrote it here:
while not os.path.exists(file + "_" + str(i) + extension):
i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)
should be:
while os.path.exists(file + "_" + str(i) + extension):
i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)
Check this out, please!
In my case the following solved the problem:
oracle.dataaccess.dll
to the bin
file by browsing the file location or just from the refence list in .NET
tab.Unix will only run commands if they are available on the system path, as you can view by the $PATH variable
echo $PATH
Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such
./my-exec
Where my-exec
is the name of your program.
Use the replace
function in js:
var emailAdd = $(this).text().replace(/ /g,'');
That will remove all the spaces
If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :
var emailAdd = $.trim($(this).text());
I can give an example commonly seen in project.
Here, option --no-ff
(i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff
(i.e. fast-forward merge) is by default.
$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature' // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk // => see details with graph
$ git checkout -b anotherFeature // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk // => see details with graph
(*) Note that here if the newFeature
branch is re-used, instead of creating a new branch, git will have to do a --no-ff
merge anyway. This means fast forward merge is not always eligible.
Since everything was working fine for weeks then stopped, I doubt this has anything to do with your code. Perhaps the error is occurring when the service is activated within IIS/ASP.NET, not when your code is called. The runtime could just be checking the configuration of the web site and throwing a generic error message which has nothing to do with the service.
My suspicion is that a certificate has expired or that the bindings are set up incorrectly. If the web site is mis-configured for HTTPS, whether your code uses them or not, you may be getting this error.
Use this:
var arr = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
Try to check the length of the selector, if it returns you something then the element must exists else not.
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
I was able to use Find & Replace with the "Find what:" input field set to:
" * "
(space asterisk space with no double-quotes)
and "Replace with:" set to:
""
(nothing)
You could use a ternary operator like this one, to make it a one liner.
echo ($profitloss < 0) ? 'false' : 'true';
Most of these linker errors occur because of missing libraries.
I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.
That solved it for me on Xcode 6.3.2 for iOS 8.3
Cheers!
It seems that you should use the multiprocessing.Pool class instead and use the methods .apply() .apply_async(), map()
http://docs.python.org/library/multiprocessing.html?highlight=pool#multiprocessing.pool.AsyncResult
Here is the solution I found:
How to fix the missing MSVCR711.dll problem
You can find MSVCR71.dll
file in following location of your installed SQL Developer 2.1 directory:
sqldeveloper-2.1.0.63.10\sqldeveloper\jdk\jre\bin\MSVCR71.dll
You can use \
to indicate that any line of Ruby continues on the next line. This works with strings too:
string = "this is a \
string that spans lines"
puts string.inspect
will output "this is a string that spans lines"
table
in a div
(e.g. if the HTML is generated from Markdown) but still want to have scrollbars:table {_x000D_
display: block;_x000D_
max-width: -moz-fit-content;_x000D_
max-width: fit-content;_x000D_
margin: 0 auto;_x000D_
overflow-x: auto;_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>Especially on mobile, a table can easily become wider than the viewport.</td>_x000D_
<td>Using the right CSS, you can get scrollbars on the table without wrapping it.</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>A centered table.</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Explanation: display: block;
makes it possible to have scrollbars. By default (and unlike tables), blocks span the full width of the parent element. This can be prevented with max-width: fit-content;
, which allows you to still horizontally center tables with less content using margin: 0 auto;
. white-space: nowrap;
is optional (but useful for this demonstration).
// copy /tmp/abc.txt to /tmp/abc.txt (target path)
// username and password of 10.1.1.2 is "username" and "password"
sshpass -p "password" scp /tmp/abc.txt [email protected]:/tmp/abc.txt
// install sshpass (ubuntu)
sudo apt-get install sshpass
This worked for me in newer browsers:
autocomplete="new-password"
try this one :
public void itemClicked(View v) {
//code to check if this checkbox is checked!
CheckBox checkBox = (CheckBox)v;
if(checkBox.isChecked()){
}
}
For SublimeText 3 on Mac:
# .jshintrc
{
"esversion": 6
}
// SublimeLinter Settings - User
{
"linters": {
"jshint": {
"args": ["--config", "/Users/[your_username]/.jshintrc"]
}
}
}
Most likely, as mentioned by others, it is a class carrying the css values:
.clear{clear: both;}
in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.
In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.
What I did to make this go away:
Open C:\Users\gr_mext1\Documents\IISExpress\config\applicationhost.config
and remove all <site>
entries in <sites>
do not remove <siteDefaults>
!
In your project, go to Properties, Web and click "Create Virtual Directory".
Close and re-open visual studio, load your project and run
Fixed!
delete from t
where id in (1, 4, 6, 7)
The following commands will return only Java ProcessIDs. These commands are very useful especially whenever you want to feed another process by these return values (java PIDs).
sudo netstat -nlpt | awk '/java/ {print $7}' | tr '/java' ' '
sudo netstat -nlpt | awk '/java/ {print $7}' | sed 's/\/java/ /g'
But if you remove the latest pipe, you will be noticed these are java process
sudo netstat -nlpt | awk '/java/ {print $7}'
sudo netstat -nlpt | awk '/java/ {print $7}'
There a small difference when u use rgba(255,255,255,a),background color becomes more and more lighter as the value of 'a' increase from 0.0 to 1.0. Where as when use rgba(0,0,0,a), the background color becomes more and more darker as the value of 'a' increases from 0.0 to 1.0. Having said that, its clear that both (255,255,255,0) and (0,0,0,0) make background transparent. (255,255,255,1) would make the background completely white where as (0,0,0,1) would make background completely black.
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):
Android and iOS devices respect the following
<meta>
tag:<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this
<meta>
tag be included within the page's<head>
element.
From the docs:
Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.
http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing
Try:
alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]
Try mvn clean install eclipse:eclipse -Dwtpversion=2.0 command on DOS command prompt. Suggesting you because , It worked for me!!
Typically, your help output should include:
[options]
to indicate where the options goarg_name
for a required, singular arg[arg_name]
for an optional, singular argarg_name...
for a required arg of which there can be many (this is rare)[arg_name...]
for an arg for which any number can be suppliedarg_name
should be a descriptive, short name, in lower, snake case-l
) or a long form (e.g. --list
), include them together on the same line, as their descriptions will be the sameGREP_OPTS
Note further that it's good form to accept both -h
and --help
to trigger this message and that you should show this message if the user messes up the command-line syntax, e.g. omits a required argument.
Some notes to complement the ALTER DATABASE process:
1) You can obtain a full list of databases with logical names and full paths of MDF and LDF files:
USE master SELECT name, physical_name FROM sys.master_files
2) You can move manually the files with CMD move command:
Move "Source" "Destination"
Example:
md "D:\MSSQLData"
Move "C:\test\SYSADMIT-DB.mdf" "D:\MSSQLData\SYSADMIT-DB_Data.mdf"
Move "C:\test\SYSADMIT-DB_log.ldf" "D:\MSSQLData\SYSADMIT-DB_log.ldf"
3) You should change the default database path for new databases creation. The default path is obtained from the Windows registry.
You can also change with T-SQL, for example, to set default destination to: D:\MSSQLData
USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', REG_SZ, N'D:\MSSQLData'
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', REG_SZ, N'D:\MSSQLData'
GO
Extracted from: http://www.sysadmit.com/2016/08/mover-base-de-datos-sql-server-a-otro-disco.html
This tip shows how to use Logger in any java application. Logger needs to configure Formatter and Handler. There are many types of handlers and formatters present. In this example FileHandler is used to store all the log messages in a log file. And Simple formatter is used to format the log messages in human readable form.
package MyProject;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class MyLogger {
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("c:\\MyLogFile.log", true);
logger.addHandler(fh);
logger.setLevel(Level.ALL);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.log(Level.WARNING,"My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
some more examples you can find here https://docs.oracle.com/javase/7/docs/api/java/util/logging/Logger.html
It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.
If you're using jQuery 2.1.4 or above, try this:
$("#" + this.d);
Or, you can define var before using it. It makes your code simpler.
var d = this.d
$("#" + d);
Another option is instanceof:
Object o =...
if (o instanceof Number) {
double d = ((Number)o).doubleValue(); //this cast is safe
}
Here is a snippet from my perl script to do this:
print OUTPUT "set arrow from $x1,$y1 to $x1,$y2 nohead lc rgb \'red\'\n";
As you might guess from above, it's actually drawn as a "headless" arrow.
Restarting the Management Studio worked for me.
Try BeanComparator from Apache Commons.
import org.apache.commons.beanutils.BeanComparator;
BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);
Thanking Daniel Jimenez for his perfect solution to fetch column names alone from my csv, I extend his solution to use DictReader so we can iterate over the rows using column names as indexes. Thanks Jimenez.
with open('myfile.csv') as csvfile:
rest = []
with open("myfile.csv", "rb") as f:
reader = csv.reader(f)
i = reader.next()
i=i[1:]
re=csv.DictReader(csvfile)
for row in re:
for x in i:
print row[x]
Just cast the enum, e.g.
int something = (int) Question.Role;
The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int
.
However, as cecilphillip points out, enums can have different underlying types.
If an enum is declared as a uint
, long
, or ulong
, it should be cast to the type of the enum; e.g. for
enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};
you should use
long something = (long)StarsInMilkyWay.Wolf424B;
For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:
Suppose if the list is a collection of objects like given below:
obj = [
{
"subjectId" : "577a54c09c57916109142248",
"evaluableMaterialCount" : 0,
"subjectName" : "ASP.net"
},
{
"subjectId" : "56645cd63c43a07b61c2c650",
"subjectName" : ".NET",
},
{
"subjectId" : "5656a2ec3c43a07b61c2bd83",
"subjectName" : "Python",
},
{
"subjectId" : "5662add93c43a07b61c2c58c",
"subjectName" : "HTML"
}
]
You can use the following method to find the index. Suppose the subjectId is 5662add93c43a07b61c2c58c then to get the index of the object in the list,
subjectId = "5662add93c43a07b61c2c58c"
for i, subjobj in enumerate(obj):
if(subjectId == subjobj['subjectId']):
print(i)
If your file is really big try to use following formula: =A1 / 86400 + 25569
A1 should be replaced to what your need. Should work faster than =(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970,1,1) cause of less number of calculations needed.
Just put the below code in your .htaccess
file:
AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf
Or you can also do trick by JavaScript
element.setAttribute( 'download', whatever_string_you_want);
For Asp.Net core you better use
<partial name="_MyPartialView" model="MyModel" />
So for example
@foreach (var item in Model)
{
<partial name="_MyItemView" model="item" />
}
This button is a built-in overlay that is provided by the UITextField
class, but as of the iOS 2.2 SDK, there isn't any way to set it via Interface Builder. You have to enable it programmatically.
Add this line of code somewhere (viewDidLoad
, for example):
Objective-C
myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;
Swift 5.0
myUITextField.clearButtonMode = .whileEditing
Here's a really helpful overview of when to base64 encode and when not to by David Calhoun.
Basic answer = gzipped base64 encoded files will be roughly comparable in file size to standard binary (jpg/png). Gzip'd binary files will have a smaller file size.
Takeaway = There's some advantage to encoding and gzipping your UI icons, etc, but unwise to do this for larger images.
just run DBCC useroptions
and you'll get something like this:
Set Option Value
--------------------------- --------------
textsize 2147483647
language us_english
dateformat mdy
datefirst 7
lock_timeout -1
quoted_identifier SET
arithabort SET
ansi_null_dflt_on SET
ansi_warnings SET
ansi_padding SET
ansi_nulls SET
concat_null_yields_null SET
isolation level read committed
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?
It worked fine with me,
$this->db->where("your_id !=",$your_id);
Or try this one,
$this->db->where("your_id <>",$your_id);
Or try this one,
$this->db->where("your_id IS NOT NULL");
all will work.
The accepted answer doesn't provide a viable fix, and most of the other ones suggest the "triple-slashes" workaround which is not viable anymore, since the browser.d.ts
has been removed by the Angular2 latest RC's and thus is not available anymore.
I strongly suggest to install the typings
module as suggested by a couple solutions here, yet it's not necessary to do it manually or globally - there's an effective way to do that for your project only and within VS2015 interface. Here's what you need to do:
typings
in the project's package.json file.script
block in the package.json
file to execute/update typings
after each NPM action.typings.json
file in the project's root folder containing a reference to core-js
(overall better than es6-shim
atm).That's it.
You can also take a look to this other SO thread and/or read this post on my blog for additional details.
Add onload listener in componentDidMount
class Comp1 extends React.Component {
constructor(props) {
super(props);
this.handleLoad = this.handleLoad.bind(this);
}
componentDidMount() {
window.addEventListener('load', this.handleLoad);
}
componentWillUnmount() {
window.removeEventListener('load', this.handleLoad)
}
handleLoad() {
$("myclass") // $ is available here
}
}
var nameCheckBoxList = "myCheckListName";
var selectedValues = $("[name=" + nameCheckBoxList + "]:checked").map(function(){return this.value;});
Well, if yo don't know where is my.cnf (such Mac OS X installed with homebrew), or You are looking found others choices:
ps aux|grep mysql
abkrim 1160 0.0 0.2 2913068 26224 ?? R Tue04PM 0:14.63 /usr/local/opt/mariadb/bin/mysqld --basedir=/usr/local/opt/mariadb --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/opt/mariadb/lib/plugin --bind-address=127.0.0.1 --log-error=/usr/local/var/mysql/iMac-2.local.err --pid-file=iMac-2.local.pid
You get datadir=/usr/local/var/mysql
in the java src you can add a new tool like this:
public static String remplaceVirguleParpoint(String chaine) {
return chaine.replaceAll(",", "\\.");
}
Use String.format (or java.util.Formatter):
Timestamp timestamp = ...
String.format("%1$TD %1$TT", timestamp)
EDIT:
please see the documentation of Formatter to know what TD and TT means: click on java.util.Formatter
The first 'T' stands for:
't', 'T' date/time Prefix for date and time conversion characters.
and the character following that 'T':
'T' Time formatted for the 24-hour clock as "%tH:%tM:%tS".
'D' Date formatted as "%tm/%td/%ty".
You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout
to kick off a function after a delay:
setTimeout(function(){alert("hi")}, 1000);
Depending on your needs, setInterval
might be useful, too.
You can archive it with a Service and Alarm Manager, but be careful with this, because if you setup a high priority you gonna drain the battery of the phone, in other hand, you really need notify the location every minute? This is because the only way to see a considerably change of the user location, it's traveling in a car or train. I only ask, because that gonna depend of you app and the requirement of the tracking.
Get COLUMN INDEX on click:
$(this).closest("td").index();
Get ROW INDEX on click:
$(this).closest("tr").index();
When you remove RegExp from the equation you leave a less "friendly" code, but it still can be done with the (much) less elegant way of split().
function removeClass(classString, toRemove) {
classes = classString.split(' ');
var out = Array();
for (var i=0; i<classes.length; i++) {
if (classes[i].length == 0) // double spaces can create empty elements
continue;
if (classes[i] == toRemove) // don't include this one
continue;
out.push(classes[i])
}
return out.join(' ');
}
This method is a lot bigger than a simple replace() but at least it can be used on older browsers. And in case the browser doesn't even support the split() command it's relatively easy to add it using prototype.
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'USD' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml
// format inital value
onBlur({target:currencyInput})
// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)
function localStringToNumber( s ){
return Number(String(s).replace(/[^0-9.-]+/g,""))
}
function onFocus(e){
var value = e.target.value;
e.target.value = value ? localStringToNumber(value) : ''
}
function onBlur(e){
var value = e.target.value
var options = {
maximumFractionDigits : 2,
currency : currency,
style : "currency",
currencyDisplay : "symbol"
}
e.target.value = value
? localStringToNumber(value).toLocaleString(undefined, options)
: ''
}
_x000D_
input{
padding: 10px;
font: 20px Arial;
width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
You did not do anything wrong here, it will any other thing that is overriding the image size.
You can check this working fiddle.
And in this fiddle I have alter the image size using %
, and it is working.
Also try using this code:
<img src="image.jpg" style="width: 50%; height: 50%"/>?
Here is the example fiddle.
In this thread rejection sampling was already discussed, but I wanted to suggest one optimization based on the fact that rand() % 2^something
does not introduce any bias as already mentioned above.
The algorithm is really simple:
Here's my sample code:
int randInInterval(int min, int max) {
int intervalLen = max - min + 1;
//now calculate the smallest power of 2 that is >= than `intervalLen`
int ceilingPowerOf2 = pow(2, ceil(log2(intervalLen)));
int randomNumber = rand() % ceilingPowerOf2; //this is "as uniform as rand()"
if (randomNumber < intervalLen)
return min + randomNumber; //ok!
return randInInterval(min, max); //reject sample and try again
}
This works well especially for small intervals, because the power of 2 will be "nearer" to the real interval length, and so the number of misses will be smaller.
PS
Obviously avoiding the recursion would be more efficient (no need to calculate over and over the log ceiling..) but I thought it was more readable for this example.
You create buttons dynamically because of that you need to call them with .live()
method if you use jquery 1.7
but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:
$(document).on('click', 'selector', function(){
// Your Code
});
For Example
If your html is something like this
<div id="btn-list">
<div class="btn12">MyButton</div>
</div>
You can write your jquery like this
$(document).on('click', '#btn-list .btn12', function(){
// Your Code
});
You just add following lines of code in style.xml file
<style name="AppTheme.NoTitleBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
change apptheme in AndroidManifest.xml file
android:theme="@style/AppTheme.NoTitleBar"
in regard of answer from @Perception, its true to be very memory-consuming when working with byte arrays, but you could also simply write back into the outputstream
@Path("/picture")
public class ProfilePicture {
@GET
@Path("/thumbnail")
@Produces("image/png")
public StreamingOutput getThumbNail() {
return new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException, WebApplicationException {
//... read your stream and write into os
}
};
}
}
You can try the same with replacewith()
$('.click').click(function() {
// get the contents of the link that was clicked
var linkText = $(this).text();
// replace the contents of the div with the link text
$('#content-container').replaceWith(linkText);
// cancel the default action of the link by returning false
return false;
});
The .replaceWith()
method removes content from the DOM and inserts new content in its place with a single call.
Use LayoutBuilder
and Get the output you want
Wrap the SingleChildScrollView
with LayoutBuilder
and implement the Builder function.
we can use a LayoutBuilder
to get the box contains
or the amount of space available.
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints){
return SingleChildScrollView(
child: Stack(
children: <Widget>[
Container(
height: constraints.maxHeight,
),
topTitle(context),
middleView(context),
bottomView(context),
],
),
);
}
)
Also consider using Array()
. From the Ruby Community Style Guide:
Use Array() instead of explicit Array check or [*var], when dealing with a variable you want to treat as an Array, but you're not certain it's an array.
# bad
paths = [paths] unless paths.is_a? Array
paths.each { |path| do_something(path) }
# bad (always creates a new Array instance)
[*paths].each { |path| do_something(path) }
# good (and a bit more readable)
Array(paths).each { |path| do_something(path) }
Verry Easy, change order of element:
Origin
<div style="">
My Text
<button type="button" style="float: right; margin:5px;">
My Button
</button>
</div>
Change to:
<div style="">
<button type="button" style="float: right; margin:5px;">
My Button
</button>
My Text
</div>
This solution is for Windows users.
You can open the node.js installer and give the installer some time to compute space requirements and then click next and click remove. This will remove node.js from your computer and again reopen the installer and install it in this path - C:\Windows\System32
or
Cleaning Cache
and Node_module
will work.
Follow this steps:
npm cache clean --force
node_modules
folderpackage-lock.json
filenpm install
This suffices and stores the first line of filename
in the variable $line
:
read -r line < filename
I also like awk
for this:
awk 'NR==1 {print; exit}' file
To store the line itself, use the var=$(command)
syntax. In this case, line=$(awk 'NR==1 {print; exit}' file)
.
Or even sed
:
sed -n '1p' file
With the equivalent line=$(sed -n '1p' file)
.
See a sample when we feed the read
with seq 10
, that is, a sequence of numbers from 1 to 10:
$ read -r line < <(seq 10)
$ echo "$line"
1
$ line=$(awk 'NR==1 {print; exit}' <(seq 10))
$ echo "$line"
1
This link explains everything in depth, including why those multiplier constants exist before the R, G and B values.
Edit: It has an explanation to one of the answers here too (0.299*R + 0.587*G + 0.114*B)
try something like
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}
Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>pip</executable>
<arguments><argument>install</argument></arguments>
<workingDirectory>${project.build.directory}/Demo</workingDirectory>
</configuration>
Since you have dynamic values, you need to use an IF or CASE for the columns to be updated. It gets kinda ugly, but it should work.
Using your example, you could do it like:
UPDATE table SET Col1 = CASE id WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 4 THEN 10 ELSE Col1 END, Col2 = CASE id WHEN 3 THEN 3 WHEN 4 THEN 12 ELSE Col2 END WHERE id IN (1, 2, 3, 4);
Remove folowing dependancy on your pom file will work for me
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Create the Intent like this:
Uri uriSms = Uri.parse("smsto:1234567899");
Intent intentSMS = new Intent(Intent.ACTION_SENDTO, uriSms);
intentSMS.putExtra("sms_body", "The SMS text");
startActivity(intentSMS);
Code to detect the operating system of an user
let os = navigator.userAgent.slice(13).split(';')
os = os[0]
console.log(os)
Windows NT 10.0
In MomentJs We can declare it like :
const start = moment().format('YYYY-MM-DD 00:00:01');
const end = moment().format('YYYY-MM-DD 23:59:59');
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
bad:
<a id="myLink" href="javascript:MyFunction();">link text</a>
good:
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
better:
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
even better 1:
<a id="myLink" title="Click to do something"
href="#" onclick="MyFunction();return false;">link text</a>
even better 2:
<a id="myLink" title="Click to do something"
href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>
Why better? because return false
will prevent browser from following the link
best:
Use jQuery or other similar framework to attach onclick handler by element's ID.
$('#myLink').click(function(){ MyFunction(); return false; });
On Windows, a good 3-way diff/merge tool remains kdiff3 (WinMerge, for now, is still 2-way based, pending WinMerge3)
See "How do you merge in GIT on Windows?" and this config.
Update 7 years later (Aug. 2018): Artur Kedzior mentions in the comments:
If you guys happen to use Visual Studio (Community Edition is free), try the tool that is shipped with it: vsDiffMerge.exe
. It's really awesome and easy to use.
here is an utility which is up to transform json2object or Object2json, whatever your pojo (entity T)
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
*
* @author TIAGO.MEDICI
*
*/
public class JsonUtils {
public static boolean isJSONValid(String jsonInString) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
}
public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
StringWriter sw = new StringWriter();
objMapper.writeValue(sw, object);
return sw.toString();
}
public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
if (indent == true) {
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
StringWriter stringWriter = new StringWriter();
objMapper.writeValue(stringWriter, object);
return stringWriter.toString();
}
public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper objMapper = new ObjectMapper();
obj = objMapper.readValue(content, clazz);
return obj;
}
@SuppressWarnings("rawtypes")
public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
obj = mapper.readValue(content, new TypeReference<List>() {
});
return obj;
}
public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
return obj;
}
Create WScript.Shell object and invoke Run() method on it.
http://msdn.microsoft.com/en-us/library/d5fk67ky(v=vs.85).aspx
I also faced it and encorrected it like below successfully.
File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution
Set the home path as : C:/Program Files/Android/Android Studio/gradle/gradle-version
You may need to upgrade your gradle version.
I use function for returning index for the matching element (Python 2.6):
def index(l, f):
return next((i for i in xrange(len(l)) if f(l[i])), None)
Then use it via lambda function for retrieving needed element by any required equation e.g. by using element name.
element = mylist[index(mylist, lambda item: item["name"] == "my name")]
If i need to use it in several places in my code i just define specific find function e.g. for finding element by name:
def find_name(l, name):
return l[index(l, lambda item: item["name"] == name)]
And then it is quite easy and readable:
element = find_name(mylist,"my name")
Goto Package properties->Configurations->Enable Package Configurations->Add->xml configuration file->Specify dtsconfig file->click next->In OLEDB Properties tick the connection string->connection string value will be displayed->click next and finish package is hence configured.
You can add Environment variable also in this process
This is happend to me once I forgot to add files. So I got the same error. All you need to do is add your files.
git add .
or the name of the files you want to add. you supposed to init first your repo with git init
.git commit -m 'Initial Commit'
.git push -u origin master
If you try it on CellContentClick
Event
Use:
dataGridView1.EndEdit(); //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
But there is switch-case :)
switch (true) {
case true:
console.log("Yes, its ture :) Break from the switch-case");
break;
case false:
console.log("Nope, but if the condition was set to false this would be used and then break");
break;
default:
console.log("If all else fails");
break;
}
Although in the particular example of the OP's question, switch
is not appropriate, there is an example where switch is still appropriate/beneficial, but other evaluation expressions are also required. This can be achieved by using the default clause for the expressions:
switch (foo) {
case 'bar':
// do something
break;
case 'foo':
// do something
break;
... // other plain comparison cases
default:
if (foo.length > 16) {
// something specific
} else if (foo.length < 2) {
// maybe error
} else {
// default action for everything else
}
}
This is a very simple solution using the tree
command in the directory you want to search for. -f
shows the full file path and |
is used to pipe the output of tree to grep
to find the file containing the string filename
in the name.
tree -f | grep filename
check this out: http://hayageek.com/docs/jquery-upload-file.php I've found it accidentally on the net.
type.convert()
Convert a data object to logical, integer, numeric, complex, character or factor as appropriate.
Add the as.is argument type.convert(df,as.is = T)
to prevent character vectors from becoming factors when there is a non-numeric in the data set.
To answer the question "how can I find out if a given index in that dict has already been set to a non-None value", I would prefer this:
try:
nonNone = my_dict[key] is not None
except KeyError:
nonNone = False
This conforms to the already invoked concept of EAFP (easier to ask forgiveness then permission). It also avoids the duplicate key lookup in the dictionary as it would in key in my_dict and my_dict[key] is not None
what is interesting if lookup is expensive.
For the actual problem that you have posed, i.e. incrementing an int if it exists, or setting it to a default value otherwise, I also recommend the
my_dict[key] = my_dict.get(key, default) + 1
as in the answer of Andrew Wilkinson.
There is a third solution if you are storing modifyable objects in your dictionary. A common example for this is a multimap, where you store a list of elements for your keys. In that case, you can use:
my_dict.setdefault(key, []).append(item)
If a value for key does not exist in the dictionary, the setdefault method will set it to the second parameter of setdefault. It behaves just like a standard my_dict[key], returning the value for the key (which may be the newly set value).
var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'
We can create a tag for some past commit:
git tag [tag_name] [reference_of_commit]
eg:
git tag v1.0 5fcdb03
Your product
class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.
As a side note: You should use Pascal casing for your class names. That is Product
, and not product
.
Update (December 1, 2009):
I'd like to amend this answer and concede that the original answer was flawed.
The original analysis does apply to objects that require finalization – and the point that practices shouldn’t be accepted on the surface without an accurate, in-depth understanding still stands.
However, it turns out that DataSets, DataViews, DataTables suppress finalization in their constructors – this is why calling Dispose() on them explicitly does nothing.
Presumably, this happens because they don’t have unmanaged resources; so despite the fact that MarshalByValueComponent makes allowances for unmanaged resources, these particular implementations don’t have the need and can therefore forgo finalization.
(That .NET authors would take care to suppress finalization on the very types that normally occupy the most memory speaks to the importance of this practice in general for finalizable types.)
Notwithstanding, that these details are still under-documented since the inception of the .NET Framework (almost 8 years ago) is pretty surprising (that you’re essentially left to your own devices to sift though conflicting, ambiguous material to put the pieces together is frustrating at times but does provide a more complete understanding of the framework we rely on everyday).
After lots of reading, here’s my understanding:
If an object requires finalization, it could occupy memory longer than it needs to – here’s why: a) Any type that defines a destructor (or inherits from a type that defines a destructor) is considered finalizable; b) On allocation (before the constructor runs), a pointer is placed on the Finalization queue; c) A finalizable object normally requires 2 collections to be reclaimed (instead of the standard 1); d) Suppressing finalization doesn’t remove an object from the finalization queue (as reported by !FinalizeQueue in SOS)
This command is misleading; Knowing what objects are on the finalization queue (in and of itself) isn’t helpful; Knowing what objects are on the finalization queue and still require finalization would be helpful (is there a command for this?)
Suppressing finalization turns a bit off in the object's header indicating to the runtime that it doesn’t need to have its Finalizer invoked (doesn’t need to move the FReachable queue); It remains on the Finalization queue (and continues to be reported by !FinalizeQueue in SOS)
The DataTable, DataSet, DataView classes are all rooted at MarshalByValueComponent, a finalizable object that can (potentially) handle unmanaged resources
4 (new references):
Original Answer:
There are a lot of misleading and generally very poor answers on this - anyone who's landed here should ignore the noise and read the references below carefully.
Without a doubt, Dispose should be called on any Finalizable objects.
DataTables are Finalizable.
Calling Dispose significantly speeds up the reclaiming of memory.
MarshalByValueComponent calls GC.SuppressFinalize(this) in its Dispose() - skipping this means having to wait for dozens if not hundreds of Gen0 collections before memory is reclaimed:
With this basic understanding of finalization we can already deduce some very important things:
First, objects that need finalization live longer than objects that do not. In fact, they can live a lot longer. For instance, suppose an object that is in gen2 needs to be finalized. Finalization will be scheduled but the object is still in gen2, so it will not be re-collected until the next gen2 collection happens. That could be a very long time indeed, and, in fact, if things are going well it will be a long time, because gen2 collections are costly and thus we want them to happen very infrequently. Older objects needing finalization might have to wait for dozens if not hundreds of gen0 collections before their space is reclaimed.
Second, objects that need finalization cause collateral damage. Since the internal object pointers must remain valid, not only will the objects directly needing finalization linger in memory but everything the object refers to, directly and indirectly, will also remain in memory. If a huge tree of objects was anchored by a single object that required finalization, then the entire tree would linger, potentially for a long time as we just discussed. It is therefore important to use finalizers sparingly and place them on objects that have as few internal object pointers as possible. In the tree example I just gave, you can easily avoid the problem by moving the resources in need of finalization to a separate object and keeping a reference to that object in the root of the tree. With that modest change only the one object (hopefully a nice small object) would linger and the finalization cost is minimized.
Finally, objects needing finalization create work for the finalizer thread. If your finalization process is a complex one, the one and only finalizer thread will be spending a lot of time performing those steps, which can cause a backlog of work and therefore cause more objects to linger waiting for finalization. Therefore, it is vitally important that finalizers do as little work as possible. Remember also that although all object pointers remain valid during finalization, it might be the case that those pointers lead to objects that have already been finalized and might therefore be less than useful. It is generally safest to avoid following object pointers in finalization code even though the pointers are valid. A safe, short finalization code path is the best.
Take it from someone who's seen 100s of MBs of non-referenced DataTables in Gen2: this is hugely important and completely missed by the answers on this thread.
References:
1 - http://msdn.microsoft.com/en-us/library/ms973837.aspx
2 - http://vineetgupta.spaces.live.com/blog/cns!8DE4BDC896BEE1AD!1104.entry http://www.dotnetfunda.com/articles/article524-net-best-practice-no-2-improve-garbage-collector-performance-using-finalizedispose-pattern.aspx
3 - http://codeidol.com/csharp/net-framework/Inside-the-CLR/Automatic-Memory-Management/
Swift 5.1
You can get class, struct, enum, protocol and NSObject names though Self.self
.
print("\(Self.self)")
The Runnable
interface is another way in which you can implement multi-threading other than extending the Thread
class due to the fact that Java allows you to extend only one class.
You can however, use the new Thread(Runnable runnable) constructor, something like this:
private Thread thread = new Thread(new Runnable() {
public void run() {
final long start = mStartTime;
long millis = SystemClock.uptimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10) {
mTimeLabel.setText("" + minutes + ":0" + seconds);
} else {
mTimeLabel.setText("" + minutes + ":" + seconds);
}
mHandler.postAtTime(this,
start + (((minutes * 60) + seconds + 1) * 1000));
}
});
thread.start();
I have done the INotifyPropertyChanged
implementation similar to the method below. Here the properties are stored in a dictionary in the base class shown below. It is of course not always desirable to use inheritance, but for view models I think it is acceptable and gives very clean property references in the view model classes.
public class PhotoDetailsViewModel
: PropertyChangedNotifierBase<PhotoDetailsViewModel>
{
public bool IsLoading
{
get { return GetValue(x => x.IsLoading); }
set { SetPropertyValue(x => x.IsLoading, value); }
}
public string PendingOperation
{
get { return GetValue(x => x.PendingOperation); }
set { SetPropertyValue(x => x.PendingOperation, value); }
}
public PhotoViewModel Photo
{
get { return GetValue(x => x.Photo); }
set { SetPropertyValue(x => x.Photo, value); }
}
}
The somewhat more complex base class is shown below. It handles the translation from lambda expression to property name. Note that the properties are really pseudo properties since only the names are used. But it will appear transparent to the view model and references to the properties on the view model.
public class PropertyChangedNotifierBase<T> : INotifyPropertyChanged
{
readonly Dictionary<string, object> _properties = new Dictionary<string, object>();
protected U GetValue<U>(Expression<Func<T, U>> property)
{
var propertyName = GetPropertyName(property);
return GetValue<U>(propertyName);
}
private U GetValue<U>(string propertyName)
{
object value;
if (!_properties.TryGetValue(propertyName, out value))
{
return default(U);
}
return (U)value;
}
protected void SetPropertyValue<U>(Expression<Func<T, U>> property, U value)
{
var propertyName = GetPropertyName(property);
var oldValue = GetValue<U>(propertyName);
if (Object.ReferenceEquals(oldValue, value))
{
return;
}
_properties[propertyName] = value;
RaisePropertyChangedEvent(propertyName);
}
protected void RaisePropertyChangedEvent<U>(Expression<Func<T, U>> property)
{
var name = GetPropertyName(property);
RaisePropertyChangedEvent(name);
}
protected void RaisePropertyChangedEvent(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private static string GetPropertyName<U>(Expression<Func<T, U>> property)
{
if (property == null)
{
throw new NullReferenceException("property");
}
var lambda = property as LambdaExpression;
var memberAssignment = (MemberExpression) lambda.Body;
return memberAssignment.Member.Name;
}
public event PropertyChangedEventHandler PropertyChanged;
}
For your question as asked
Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))
If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA
I think this is similar to what the last podcast discussed. The "Be liberal in what you accept" means that extra work had to be put into the Javascript parser to fix cases where semicolons were left out. Now we have a boatload of pages out there floating around with bad syntax, that might break one day in the future when some browser decides to be a little more stringent on what it accepts. This type of rule should also apply to HTML and CSS. You can write broken HTML and CSS, but don't be surprise when you get weird and hard to debug behaviors when some browser doesn't properly interpret your incorrect code.
This because the input that the user inserts into the JOptionPane
is a String
and it is stored and returned as a String
.
Java cannot convert between strings and number by itself, you have to use specific functions, just use:
int ans = Integer.parseInt(JOptionPane.showInputDialog(...))
Use NSURLComponents to build your NSURL like this
var urlComponents = NSURLComponents(string: "https://www.google.de/maps/")!
urlComponents.queryItems = [
NSURLQueryItem(name: "q", value: String(51.500833)+","+String(-0.141944)),
NSURLQueryItem(name: "z", value: String(6))
]
urlComponents.URL // returns https://www.google.de/maps/?q=51.500833,-0.141944&z=6
font: https://www.ralfebert.de/snippets/ios/encoding-nsurl-get-parameters/
If you don't want to SELECT SLEEP(1);
, you can also DO SLEEP(1);
It's useful for those situations in procedures where you don't want to see output.
e.g.
SELECT ...
DO SLEEP(5);
SELECT ...
Can you change the if condition to this:
if (!is.na(comments[l])) print(comments[l]);
You can only check for NA values with is.na().
There is now another way to install the gcc toolchain on OS X through the osx-gcc-installer this includes:
The download is 282MB vs 3GB for Xcode.
As the question is already dated (6 years), the answers are missing a solution with newer packages tidyr and purrr. So for people working with these packages, I want to add a solution to the previous answers - all quite interesting, especially .
The biggest advantage of purrr and tidyr are better readability IMHO. purrr replaces lapply with the more flexible map() family, tidyr offers the super-intuitive method add_row - just does what it says :)
map_df(1:1000, function(x) { df %>% add_row(x = x, y = toString(x)) })
This solution is short and intuitive to read, and it's relatively fast:
system.time(
map_df(1:1000, function(x) { df %>% add_row(x = x, y = toString(x)) })
)
user system elapsed
0.756 0.006 0.766
It scales almost linearly, so for 1e5 rows, the performance is:
system.time(
map_df(1:100000, function(x) { df %>% add_row(x = x, y = toString(x)) })
)
user system elapsed
76.035 0.259 76.489
which would make it rank second right after data.table (if your ignore the placebo) in the benchmark by @Adam Ryczkowski:
nr function time
4 data.frame 228.251
3 sqlite 133.716
2 data.table 3.059
1 rbindlist 169.998
0 placebo 0.202
jQuery takes care of this for you. The first argument to your .each()
callback function is the index of the current iteration of the loop. The second being the current matched DOM element So:
$('#list option').each(function(index, element){
alert("Iteration: " + index)
});
In Bootstrap 3.3.x make sure you use the scrollspy JavaScript capability to track active elements. It's easy to include it in your HTML. Just do the following:
<body data-spy="scroll" data-target="Id or class of the element you want to track">
In most cases I usually track active elements on my navbar, so I do the following:
<body data-spy="scroll" data-target=".navbar-fixed-top" >
Now in your CSS you can target .navbar-fixed-top .active a
:
.navbar-fixed-top .active a {
// Put in some styling
}
This should work if you are tracking active li elements in your top fixed navigation bar.
The problem is that, even in 2014, devices handle screen resize events, as well as scroll events, inconsistently while the soft keyboard is open.
I've found that, even if you're using a bluetooth keyboard, iOS in particular triggers some strange layout bugs; so instead of detecting a soft keyboard, I've just had to target devices that are very narrow and have touchscreens.
I use media queries (or window.matchMedia) for width detection and Modernizr for touch event detection.
override
is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:
class Foo
{
public:
virtual void func1();
}
class Bar : public Foo
{
public:
void func1() override;
}
If B::func1()
signature doesn't equal A::func1()
signature a compilation error will be generated because B::func1()
does not override A::func1()
, it will define a new method called func1()
instead.
I have heard this argument too - from people who forgot to put an index on their foreign keys and then complained that certain operations were slow (because constraint checking could take advantage of any index). So to sum up: There is no good reason not to use foreign keys. All modern databases support cascaded deletes, so...
If you want to remove the outline when focused as well try:
input[type="text"],
input[type="text"]:focus
{
background: transparent;
border: none;
outline-width: 0;
}
If you're doing this in the context of a asp.Net Core API action, the conversion to Json is done implicitly.
[HttpGet]
public ActionResult Get()
{
return Ok(TheList);
}
I would like to emphasize @icza answer and simplify it a bit since it is a crucial concept. I assume that reader is familiar with slices.
c := append(a, b...)
This is a valid answer to the question. BUT if you need to use slices 'a' and 'c' later in code in different context, this is not the safe way to concatenate slices.
To explain, lets read the expression not in terms of slices, but in terms of underlying arrays:
"Take (underlying) array of 'a' and append elements from array 'b' to it. If array 'a' has enough capacity to include all elements from 'b' - underlying array of 'c' will not be a new array, it will actually be array 'a'. Basically, slice 'a' will show len(a) elements of underlying array 'a', and slice 'c' will show len(c) of array 'a'."
append() does not necessarily create a new array! This can lead to unexpected results. See Go Playground example.
Always use make() function if you want to make sure that new array is allocated for the slice. For example here are few ugly but efficient enough options for the task.
la := len(a)
c := make([]int, la, la + len(b))
_ = copy(c, a)
c = append(c, b...)
la := len(a)
c := make([]int, la + len(b))
_ = copy(c, a)
_ = copy(c[la:], b)
1) For me that's the most simple way passing parameters to async task is like this
// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);
Declare and use the async task like here
private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {
@Override
protected Void doInBackground(Boolean...pParams)
{
Boolean param1, param2, param3;
//
param1=pParams[0];
param2=pParams[1];
param3=pParams[2];
....
}
2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.
/* Generic Async Task */
interface MyGenericMethod {
int execute(String param);
}
protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
public String mParam; // member variable to parameterize the function
@Override
protected Void doInBackground(MyGenericMethod... params) {
// do something here
params[0].execute("Myparameter");
return null;
}
}
// to start the asynctask do something like that
public void startAsyncTask()
{
//
AsyncTask<MyGenericMethod, Void, Void> mytest = new testtask().execute(new MyGenericMethod() {
public int execute(String param) {
//body
return 1;
}
});
}
It can also be used as below:
from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)
I can't believe, except for one guy no one has used the code to explain this, let me give it a shot too!
// Design Class
class HumanClass {
var name:String
init(name:String) {
self.name = name
}
}
var humanClassObject1 = HumanClass(name: "Rehan")
Now the left side i.e: "humanClassObject1" is the object and the right side i.e: HumanClass(name: "Rehan") is the instance of this object.
var humanClassObject2 = HumanClass(name: "Ahmad") // again object on left and it's instance on the right.
So basically, instance contains the specific values for that object and objects contains the memory location (at run-time).
Remember the famous statement "object reference not set to an instance of an object", this means that non-initialised objects don't have any instance. In some programming languages like swift the compiler will not allow you to even design a class that don't have any way to initialise all it's members (variable eg: name, age e.t.c), but in some language you are allowed to do this:
// Design Class
class HumanClass {
var name:String // See we don't have any way to initialise name property.
}
And the error will only be shown at run time when you try to do something like this:
var myClass = HumanClass()
print(myClass.name) // will give, object reference not set to an instance of the object.
This error indicates that, the specific values (for variables\property) is the "INSTANCE" as i tried to explain this above! And the object i.e: "myClass" contains the memory location (at run-time).
Although this does not directly address your question, you can actually sort your data by cell colour in Excel (which then makes it pretty easy to label all records with a particular colour in the same way and, hence, condition upon this label).
In Excel 2010, you can do this by going to Data -> Sort -> Sort On "Cell Colour".
Here is a link that has a performance test you can run. find()
is actually about 2 times faster than children()
.
I think it is faster than regex .
public final boolean containsDigit(String s) {
boolean containsDigit = false;
if (s != null && !s.isEmpty()) {
for (char c : s.toCharArray()) {
if (containsDigit = Character.isDigit(c)) {
break;
}
}
}
return containsDigit;
}
cmp
Compare
'a' cmp 'b' # -1
'b' cmp 'a' # 1
'a' cmp 'a' # 0
eq
Equal to
'a' eq 'b' # 0
'b' eq 'a' # 0
'a' eq 'a' # 1
ne
Not-Equal to
'a' ne 'b' # 1
'b' ne 'a' # 1
'a' ne 'a' # 0
lt
Less than
'a' lt 'b' # 1
'b' lt 'a' # 0
'a' lt 'a' # 0
le
Less than or equal to
'a' le 'b' # 1
'b' le 'a' # 0
'a' le 'a' # 1
gt
Greater than
'a' gt 'b' # 0
'b' gt 'a' # 1
'a' gt 'a' # 0
ge
Greater than or equal to
'a' ge 'b' # 0
'b' ge 'a' # 1
'a' ge 'a' # 1
See perldoc perlop
for more information.
( I'm simplifying this a little bit as all but cmp
return a value that is both an empty string, and a numerically zero value instead of 0
, and a value that is both the string '1'
and the numeric value 1
. These are the same values you will always get from boolean operators in Perl. You should really only be using the return values for boolean or numeric operations, in which case the difference doesn't really matter. )
I had the same issue when I tried to use git.
It is possible to install git without it. And I doubt that gcc on mac is truly dependent on XCode. And I don't want to use root to accept something unless I'm sure I need it.
I uninstalled XCode by navigating to the applications folder and dragging XCode to the trash.
Now my git commands work as usual. I'll re-install XCode if/when I truly need it.
I consider this simpler than any prior correct answer. I'll also throw in javadoc. :-)
/**
* Converts the given string to title case, where the first
* letter is capitalized and the rest of the string is in
* lower case.
*
* @param s a string with unknown capitalization
* @return a title-case version of the string
*/
public static String toTitleCase(String s)
{
if (s.isEmpty())
{
return s;
}
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
Strings of length 1 do not needed to be treated as a special case because s.substring(1)
returns the empty string when s
has length 1.
Solution using only javascript
function saveFile(fileName,urlFile){
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
a.href = urlFile;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
let textData = `El contenido del archivo
que sera descargado`;
let blobData = new Blob([textData], {type: "text/plain"});
let url = window.URL.createObjectURL(blobData);
//let url = "pathExample/localFile.png"; // LocalFileDownload
saveFile('archivo.txt',url);
<table style="border: 5px solid black">
This only adds a border around the table.
If you want same border through CSS then add this rule:
table tr td { border: 5px solid black; }
and one thing for HTML table to avoid spaces
<table cellspacing="0" cellpadding="0">
Update for Swift 3.0 and higher
//
// Step 1:- Create a method in AppDelegate.swift
//
func someMethodInAppDelegate() {
print("someMethodInAppDelegate called")
}
calling above method from your controller by followings
//
// Step 2:- Getting a reference to the AppDelegate & calling the require method...
//
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.someMethodInAppDelegate()
}
Output:
I'm not sure why you'd want to validate an optional email address, but I'd suggest you use
^$|^[^@\s]+@[^@\s]+$
meaning
^$ empty string
| or
^ beginning of string
[^@\s]+ any character but @ or whitespace
@
[^@\s]+
$ end of string
You won't stop fake emails anyway, and this way you won't stop valid addresses.
You really should fix whatever's causing the warning, but you can control visibility of errors with error_reporting()
. To skip warning messages, you could use something like:
error_reporting(E_ERROR | E_PARSE);
This can happen if you don't attach your dataset.
This function can split the entire text of Huckleberry Finn into sentences in about 0.1 seconds and handles many of the more painful edge cases that make sentence parsing non-trivial e.g. "Mr. John Johnson Jr. was born in the U.S.A but earned his Ph.D. in Israel before joining Nike Inc. as an engineer. He also worked at craigslist.org as a business analyst."
# -*- coding: utf-8 -*-
import re
alphabets= "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov)"
def split_into_sentences(text):
text = " " + text + " "
text = text.replace("\n"," ")
text = re.sub(prefixes,"\\1<prd>",text)
text = re.sub(websites,"<prd>\\1",text)
if "Ph.D" in text: text = text.replace("Ph.D.","Ph<prd>D<prd>")
text = re.sub("\s" + alphabets + "[.] "," \\1<prd> ",text)
text = re.sub(acronyms+" "+starters,"\\1<stop> \\2",text)
text = re.sub(alphabets + "[.]" + alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>\\3<prd>",text)
text = re.sub(alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>",text)
text = re.sub(" "+suffixes+"[.] "+starters," \\1<stop> \\2",text)
text = re.sub(" "+suffixes+"[.]"," \\1<prd>",text)
text = re.sub(" " + alphabets + "[.]"," \\1<prd>",text)
if "”" in text: text = text.replace(".”","”.")
if "\"" in text: text = text.replace(".\"","\".")
if "!" in text: text = text.replace("!\"","\"!")
if "?" in text: text = text.replace("?\"","\"?")
text = text.replace(".",".<stop>")
text = text.replace("?","?<stop>")
text = text.replace("!","!<stop>")
text = text.replace("<prd>",".")
sentences = text.split("<stop>")
sentences = sentences[:-1]
sentences = [s.strip() for s in sentences]
return sentences
Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.
I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.
Note in the below code NeedsToRunAsAdmin
is a method that detects if under current conditions admin privileges are required. If this returns false
the code will not elevate itself. This is a major advantage of this approach over the others.
Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.
private static void Main(string[] args)
{
if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
foreach (string arg in args)
{
proc.Arguments += String.Format("\"{0}\" ", arg);
}
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
}
}
else
{
//Normal program logic...
}
}
private static bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
# Open the file
f = open('morseCode.txt', 'r')
# Read the morse code data into "letters" [(lowercased letter, morse code), ...]
letters = []
for Line in f:
if not Line.strip(): break
letter, code = Line.strip().split() # Assuming the format is <letter><whitespace><morse code><newline>
letters.append((letter.lower(), code))
f.close()
# Get the input from the user
# (Don't use input() - it calls eval(raw_input())!)
i = raw_input("Enter a string to be converted to morse code or press <enter> to quit ")
# Convert the codes to morse code
out = []
for c in i:
found = False
for letter, code in letters:
if letter == c.lower():
found = True
out.append(code)
break
if not found:
raise Exception('invalid character: %s' % c)
# Print the output
print ' '.join(out)
It is ES-6 feature. It means you extract all the properties of props in
div.{... }
operator is used to extract properties of an object.
U can use eclipse. but u need to download pydev addon for that.
Solution provided by @Divergent does work, but in my experience it is better to have 2 queries:
Solution with pushing $$ROOT and using $slice runs into document memory limitation of 16MB for large collections. Also, for large collections two queries together seem to run faster than the one with $$ROOT pushing. You can run them in parallel as well, so you are limited only by the slower of the two queries (probably the one which sorts).
I have settled with this solution using 2 queries and aggregation framework (note - I use node.js in this example, but idea is the same):
var aggregation = [
{
// If you can match fields at the begining, match as many as early as possible.
$match: {...}
},
{
// Projection.
$project: {...}
},
{
// Some things you can match only after projection or grouping, so do it now.
$match: {...}
}
];
// Copy filtering elements from the pipeline - this is the same for both counting number of fileter elements and for pagination queries.
var aggregationPaginated = aggregation.slice(0);
// Count filtered elements.
aggregation.push(
{
$group: {
_id: null,
count: { $sum: 1 }
}
}
);
// Sort in pagination query.
aggregationPaginated.push(
{
$sort: sorting
}
);
// Paginate.
aggregationPaginated.push(
{
$limit: skip + length
},
{
$skip: skip
}
);
// I use mongoose.
// Get total count.
model.count(function(errCount, totalCount) {
// Count filtered.
model.aggregate(aggregation)
.allowDiskUse(true)
.exec(
function(errFind, documents) {
if (errFind) {
// Errors.
res.status(503);
return res.json({
'success': false,
'response': 'err_counting'
});
}
else {
// Number of filtered elements.
var numFiltered = documents[0].count;
// Filter, sort and pagiante.
model.request.aggregate(aggregationPaginated)
.allowDiskUse(true)
.exec(
function(errFindP, documentsP) {
if (errFindP) {
// Errors.
res.status(503);
return res.json({
'success': false,
'response': 'err_pagination'
});
}
else {
return res.json({
'success': true,
'recordsTotal': totalCount,
'recordsFiltered': numFiltered,
'response': documentsP
});
}
});
}
});
});
The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.
Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).
The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.
In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.
If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.
Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.
In XML there can be only one root element - you have two - heading
and song
.
If you restructure to something like:
<?xml version="1.0" encoding="UTF-8"?>
<song>
<heading>
The Twelve Days of Christmas
</heading>
....
</song>
The error about well-formed XML on the root level should disappear (though there may be other issues).
I had the same issue. Untick this checkbox. Since you are setting the content size in code.
While it's not been too long that I made the switch to Rubymine, I found it challenging ignoring .idea files of Rubymine from been committed to git.
Here's how I fixed it
If you've not done any staging/commit at all, or you just spinned up a new project in Ruby mine, then simply do this
Option 1
Add the line below to the .gitignore file which is usually placed at the root of your repository.
# Ignore .idea files
.idea/
This will ensure that all .idea files are ignored from been tracked by git, although they will still remain in your project folder locally.
Option 2
If you've however done some staging/commit, or you just opened up an existing project in Ruby mine, then simply do this
Run the code in your terminal/command line
git rm -r --cached .idea
This deletes already tracked .idea files in git
Next, include .idea/ to the .gitignore file which is usually placed at the root of your repository.
# Ignore .idea files
.idea/
This will ensure that all .idea files are ignored from been tracked by git, although they will still remain in your project folder locally.
Option 3
If you've however done some staging/commit, or you just opened up an existing project in Ruby mine, and want to totally delete .idea files locally and in git, then simply do this
Run the code in your terminal/command line
git rm -r --cached .idea
This deletes already tracked .idea files in git
Run the code in your terminal/command line
rm -r .idea
This deletes all .idea files including the folder locally
Next, include .idea/ to the .gitignore file which is usually placed at the root of your repository.
# Ignore .idea files
.idea/
This will ensure that all .idea files are ignored from been tracked by git, and also deleted from your project folder locally.
That's all
I hope this helps
I will explain you this with a practical example and no theory stuff:
A developer writes the code. No GUI is implemented yet. The testing at this level verifies that the functions work correctly and the data types are correct. This phase of testing is called Unit testing.
When a GUI is developed, and application is assigned to a tester, he verifies business requirements with a client and executes the different scenarios. This is called functional testing. Here we are mapping the client requirements with application flows.
Integration testing: let's say our application has two modules: HR and Finance. HR module was delivered and tested previously. Now Finance is developed and is available to test. The interdependent features are also available now, so in this phase, you will test communication points between the two and will verify they are working as requested in requirements.
Regression testing is another important phase, which is done after any new development or bug fixes. Its aim is to verify previously working functions.
A hacky one-liner for 2.5+ :
>>> a = dict(x=2, y=3)
>>> b = dict(y=4, z=5)
>>> c = 'No Effect' if a.update(b) else a
>>> c
{'x': 2, 'y': 4, 'z': 5}
dict.update
modifies the dict
in-place, hence it evaluates to None
A if C else B
, C
is evaluated first. See hereSo here, a.update(b)
is evaluated first, a
gets updated with b
and operation results in None
, thus the expression will always return the value given in the else
condition, i.e. a
. Since, a
is already modified, it will return the new value of a
, which is the updated dict.
IMPROVEMENT
This can be further improved, and it be made to work for even older versions (probably python 1.0 as well?):
>>> c = a.update(b) or a
Here also, the first part produces None
, hence it always returns the second part, but as the update operation is already done, it always returns the updated dict.
CRITIQUE
a
, so if one wants to keep both the input dictionaries unchanged, this is not a good idea.IMPROVEMENT
If copy of a
is needed, the second one can be slightly modified:
>>> a = dict(x=2, y=3)
>>> b = dict(y=4, z=5)
>>> a, c = a.copy(), a.update(b) or a
>>> c
{'x': 2, 'y': 4, 'z': 5}
>>> d = dict(m=10, n=11)
>>> a, c = a.copy(), a.update(b) or a.update(d) or a
>>> c
{'x': 2, 'y': 4, 'z': 5, 'm': 10, 'n': 11}
>>> a
{'x': 2, 'y': 4}
CAVEATS
Even though these solutions are extremely fast, especially the or
method which is probably faster than the new python 3.9 union operator (not entirely sure, further testing required, if anyone wants to add it afterwards, they are welcome), I would not recommend these methods due to the abovementioned reasons.
Added it for the sake of completeness.
I am also new to MVC and I received the same error and found that it is not passing proper routeValues
in the Index
view or whatever view is present to view the all data.
It was as below
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
I changed it to the as show below and started to work properly.
<td>
@Html.ActionLink("Edit", "Edit", new { EmployeeID=item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
Basically this error can also come because of improper navigation also.
I wanted to create a MarkdownPreviewer in react as part of a project in freecodecamp. So I was desperately searching for newline characters for markdown. After trying many suggestions. I finally used \n and it worked.
Check out DLRadioButton. You can add and customize radio buttons directly from the Interface Builder. Also works with Swift
perfectly.
Update: version 1.3.2
added square buttons, also improved performance.
Update: version 1.4.4
added multiple selection option, can be used as checkbox as well.
Update: version 1.4.7
added RTL language support.
None of the above answers worked for me - PHP was properly rendering everything except pages that relied on mysqli, for which it was sending a blank page with a 200 response code and not throwing any errors. As I'm on OS X, the fix was simply
sudo port install php56-mysql
followed by a restart of PHP-FPM and nginx.
I was migrating from an older Apache/PHP setup to nginx, and failed to notice the version mismatch in the driver for php-mysql
and php-fpm
.
Mutating methods are always useful if the original object is not in scope:
def fun(d):
d.clear()
d["b"] = 2
d={"a": 2}
fun(d)
d # {'b': 2}
Re-assigning the dictionary would create a new object and wouldn't modify the original one.
Here is an overlay using a pseudo-element (eg: no need to add more markup to do it)
.box {_x000D_
background: 0 0 url(http://ianfarb.com/wp-content/uploads/2013/10/nicholas-hodag.jpg);_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
content: "";_x000D_
display: block;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: rgba(0, 0, 0, 0.4);_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
Now i know ,the element is one of node
All node types in here"http://www.w3schools.com/dom/dom_nodetype.asp"
Element is between the start tag and end in the end tag
So text node is a node , but not a element.
You can use find_all
in the following way to find every a
element that has an href
attribute, and print each one:
from BeautifulSoup import BeautifulSoup
html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''
soup = BeautifulSoup(html)
for a in soup.find_all('a', href=True):
print "Found the URL:", a['href']
The output would be:
Found the URL: some_url
Found the URL: another_url
Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll
. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all
instead.
If you want all tags with an href
, you can omit the name
parameter:
href_tags = soup.find_all(href=True)
In case you want to do this on multiple lines that match a specific search:
:g/Your query/ normal ddp
or :g/Your query/ m -1
:g/Your query/ normal ddp
or :g/Your query/ m +1
Try
os.path.getsize(filename)
It should return the size of a file, reported by os.stat().
select column1 || ' ' || column2 as whole_name FROM tablename;
Here ||
is the concat operator used for concatenating them to single column and (''
) inside ||
used for space between two columns.
I just had this issue myself. 3 points that will hopefully help:
app/assets/images
directory, then you should be able to call the image directly with no prefix in the path. ie. image_url('logo.png')
background-image:
property, then your line of code should be background-image: image-url('logo.png')
. This works for both less and sass stylesheets. If you are using it inline in the view, then you will need to use the built in image_tag
helper in rails to output your image. Once again, no prefixing <%= image_tag 'logo.png' %>
rake assets:precompile
to generate your assets, or rake assets:precompile RAILS_ENV=production
for production, otherwise, your production environment will not have the fingerprinted assets when loading the page.Also for those commands in point 3 you will need to prefix them with bundle exec
if you are running bundler.
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
I think you will have to have 2 routes. If you look at line 331 of the connect router the * in a path is replaced with .+ so will match 1 or more characters.
https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js
If you have 2 routes that perform the same action you can do the following to keep it DRY.
var express = require("express"),
app = express.createServer();
function fooRoute(req, res, next) {
res.end("Foo Route\n");
}
app.get("/foo*", fooRoute);
app.get("/foo", fooRoute);
app.listen(3000);
I did something similar with this construct
$('li').each(function(){
if(this.id){
this.id = this.id+"something";
}
});
There could be a perceptible difference.
String.format
is quite complex and uses a regular expression underneath, so don't make it a habit to use it everywhere, but only where you need it.
StringBuilder
would be an order of magnitude faster (as someone here already pointed out).
Was just working with Nativescript's fetchModule and figured out my own solution using string manipulation. Append the query string bit by bit to the url. Here is an example where query is passed as a json object (query = {order_id: 1}):
function performGetHttpRequest(fetchLink='http://myapi.com/orders', query=null) {
if(query) {
fetchLink += '?';
let count = 0;
const queryLength = Object.keys(query).length;
for(let key in query) {
fetchLink += key+'='+query[key];
fetchLink += (count < queryLength) ? '&' : '';
count++;
}
}
// link becomes: 'http://myapi.com/orders?order_id=1'
// Then, use fetch as in MDN and simply pass this fetchLink as the url.
}
I tested this over a multiple number of query parameters and it worked like a charm :) Hope this helps someone.
Since your controller actions execute on the server, and JavaScript (usually) executes on the client (browser), this doesn't make sense. If you need some action to happen by default once the page is loaded into the browser, you can use JavaScript's document.OnLoad event handler.
You need to use __repr__
. This is a standard function like __init__
.
For example:
class Foobar():
"""This will create Foobar type object."""
def __init__(self):
print "Foobar object is created."
def __repr__(self):
return "Type what do you want to see here."
a = Foobar()
print a
In 2010 it is ctrl +k +d for indentation
Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:
$('.collapse').on('show.bs.collapse', function () {
$('.collapse.in').collapse('hide');
});
I modified his example to do this here: http://jsfiddle.net/QLfMU/116/
As I said in a comment to aqingsao's answer, it doesn't quite work when the textarea
has newline characters, at least on Windows.
I've change his answer slightly thus:
$(function() {
$("textarea[maxlength]").bind('input propertychange', function() {
var maxLength = $(this).attr('maxlength');
//I'm guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error.
//Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input.
var newlines = ($(this).val().match(/\n/g) || []).length
if ($(this).val().length + newlines > maxLength) {
$(this).val($(this).val().substring(0, maxLength - newlines));
}
})
});
Now when I try to paste a lot of data in with newlines, I get exactly the right number of characters.
You can also use the latextable function from the R package micsFuncs:
http://cran.r-project.org/web/packages/miscFuncs/index.html
latextable(M) where M is a matrix with mixed alphabetic and numeric entries outputs a basic LaTeX table onto screen, which can be copied and pasted into a LaTeX document. Where there are small numbers, it also replaces these with index notation (eg 1.2x10^{-3}).
Android Studio now comes bundled with OpenJDK 8 . Legacy projects can still use JDK7 or JDK8
Reference: https://developer.android.com/studio/releases/index.html
The number in parentheses in a type declaration is display width, which is unrelated to the range of values that can be stored in a data type. Just because you can declare Int(20)
does not mean you can store values up to 10^20 in it:
[...] This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. ...
The display width does not constrain the range of values that can be stored in the column, nor the number of digits that are displayed for values having a width exceeding that specified for the column. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range allowed by three characters are displayed using more than three characters.
For a list of the maximum and minimum values that can be stored in each MySQL datatype, see here.
My simple way to do it is:
I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):
Just do:
echo substr($string, 0, -3);
You don't need to use a strlen
call, since, as noted in the substr docs:
If length is given and is negative, then that many characters will be omitted from the end of string
In C#/.NET 3.5 you could write a little program to do:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
string controller = context.ConnectedServer;
Console.WriteLine( "Domain Controller:" + controller );
}
This will list all the users in the current domain:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal searchPrincipal = new UserPrincipal(context))
{
using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
{
foreach (UserPrincipal principal in searcher.FindAll())
{
Console.WriteLine( principal.SamAccountName);
}
}
}
}
<div class="content scrollable" ref="msgContainer">
<!-- content -->
</div>
data() {
return {
count: 5
};
},
watch: {
count: function() {
this.$nextTick(function() {
var container = this.$refs.msgContainer;
container.scrollTop = container.scrollHeight + 120;
});
}
}
.scrollable {
overflow: hidden;
overflow-y: scroll;
height: calc(100vh - 20px);
}
There is a single BEXTR (Bit field extract (with register)) x86 instruction on Intel and AMD CPUs and UBFX
on ARM. There are intrinsic functions such as _bextr_u32()
(link requires sign-in) that allow to invoke this instruction explicitly.
They implement (source >> offset) & ((1 << n) - 1)
C code: get n
continuous bits from source
starting at the offset
bit. Here's a complete function definition that handles edge cases:
#include <limits.h>
unsigned getbits(unsigned value, unsigned offset, unsigned n)
{
const unsigned max_n = CHAR_BIT * sizeof(unsigned);
if (offset >= max_n)
return 0; /* value is padded with infinite zeros on the left */
value >>= offset; /* drop offset bits */
if (n >= max_n)
return value; /* all bits requested */
const unsigned mask = (1u << n) - 1; /* n '1's */
return value & mask;
}
For example, to get 3
bits from 2273
(0b100011100001
) starting at 5
-th bit, call getbits(2273, 5, 3)
—it extracts 7 (0b111
).
For example, say I want the first 17 bits of the 32-bit value; what is it that I should do?
unsigned first_bits = value & ((1u << 17) - 1); // & 0x1ffff
Assuming CHAR_BIT * sizeof(unsigned)
is 32 on your system.
I presume I am supposed to use the modulus operator and I tried it and was able to get the last 8 bits and last 16 bits
unsigned last8bitsvalue = value & ((1u << 8) - 1); // & 0xff
unsigned last16bitsvalue = value & ((1u << 16) - 1); // & 0xffff
If the offset is always zero as in all your examples in the question then you don't need the more general getbits()
. There is a special cpu instruction BLSMSK that helps to compute the mask ((1 << n) - 1)
.
If you're using SQL Server, you can set the value of bit fields with 0 and 1
or
'true' and 'false'
(yes, using strings)
...your_bit_field='false'... => equivalent to 0
If you like doing things the hard way:
my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon) == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";
In case anyone having problem with Samsung GT-I9060 I followed this answer on SO:
If you are on windows, many times it will not recognize the device fully and because of driver issues, the device won't show up.
- go to settings
- control panel
- hardware and sound
- device manager
And look for any devices showing an error. Many androids will show as an unknown USB device. Select that device and try to update the drivers for it.
I uninstalled the device, unplug the device and plug it again. This time Windows properly installed the driver. What a bummer.
In modern browsers (IE8+, FF3.6+, Chrome), you can just listen to the hashchange
event on window
.
In some old browsers, you need a timer that continually checks location.hash
. If you're using jQuery, there is a plugin that does exactly that.
Specify the paths explicitly:
git diff HEAD:full/path/to/foo full/path/to/bar
Check out the --find-renames
option in the git-diff
docs.
Credit: twaggs.
My experience in August 2013 with a linux client and a simple AWS Beanstalk installation (single EC2 instance) is as follows (based on Community Wiki above)
awsweb...
security group and the details should show at the base of the pageGood luck
Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:
Using ImageLocation property of the PictureBox like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "../SamuderaJayaMotor.png";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
Using an image from the web like:
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
pb1.SizeMode = PictureBoxSizeMode.AutoSize;
}
And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.
Here is a quick-and-dirty way to replace all the broken images, and there is no need to change the HTML code ;)
$("img").each(function(){
var img = $(this);
var image = new Image();
image.src = $(img).attr("src");
var no_image = "https://dummyimage.com/100x100/7080b5/000000&text=No+image";
if (image.naturalWidth == 0 || image.readyState == 'uninitialized'){
$(img).unbind("error").attr("src", no_image).css({
height: $(img).css("height"),
width: $(img).css("width"),
});
}
});
I had the same problem. After a couple of hours of trouble shooting found that,
I had
<script type="text/javascript" src="Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-2.1.1.min.js"></script>
instead of,
<script type="text/javascript" src="Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="Scripts/bootstrap.min.js"></script>
Hope this helps someone
When I had this problem, I had included the mail-api.jar
in my maven pom file. That's the API specification only. The fix is to replace this:
<!-- DO NOT USE - it's just the API, not an implementation -->
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
with the reference implementation of that api:
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
I know it has sun in the package name, but that's the latest version. I learned this from https://stackoverflow.com/a/28935760/1128668
Same problem happened with me when i try to show popup menu in activity i also got same excpetion but i encounter problem n resolve by providing context
YourActivityName.this
instead of getApplicationContext()
at
Dialog dialog = new Dialog(getApplicationContext());
and yes it worked for me may it will help someone else
Building on @Tim's example to make a self-contained method:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Shell {
/** Returns null if it failed for some reason.
*/
public static ArrayList<String> command(final String cmdline,
final String directory) {
try {
Process process =
new ProcessBuilder(new String[] {"bash", "-c", cmdline})
.redirectErrorStream(true)
.directory(new File(directory))
.start();
ArrayList<String> output = new ArrayList<String>();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while ( (line = br.readLine()) != null )
output.add(line);
//There should really be a timeout here.
if (0 != process.waitFor())
return null;
return output;
} catch (Exception e) {
//Warning: doing this is no good in high quality applications.
//Instead, present appropriate error messages to the user.
//But it's perfectly fine for prototyping.
return null;
}
}
public static void main(String[] args) {
test("which bash");
test("find . -type f -printf '%T@\\\\t%p\\\\n' "
+ "| sort -n | cut -f 2- | "
+ "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt");
}
static void test(String cmdline) {
ArrayList<String> output = command(cmdline, ".");
if (null == output)
System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
else
for (String line : output)
System.out.println(line);
}
}
(The test example is a command that lists all files in a directory and its subdirectories, recursively, in chronological order.)
By the way, if somebody can tell me why I need four and eight backslashes there, instead of two and four, I can learn something. There is one more level of unescaping happening than what I am counting.
Edit: Just tried this same code on Linux, and there it turns out that I need half as many backslashes in the test command! (That is: the expected number of two and four.) Now it's no longer just weird, it's a portability problem.
Using Python to extract a value from the provided Json
Working sample:-
import json
import sys
//load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}
//dumps the json object into an element
json_str = json.dumps(data)
//load the json to a string
resp = json.loads(json_str)
//print the resp
print (resp)
//extract an element in the response
print (resp['test1'])