I had the exact same problem and solved it running the folowing command from the command line as an admin :
1) first stop the service with the following
net stop http /y
2) then disable the startup (optional)
sc config http start= disabled
This might help you
public static string TransformDocument(string doc, string stylesheetPath)
{
Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlContent);
return xmlDocument;
};
try
{
var document = GetXmlDocument(doc);
var style = GetXmlDocument(File.ReadAllText(stylesheetPath));
System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
transform.Load(style); // compiled stylesheet
System.IO.StringWriter writer = new System.IO.StringWriter();
XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
transform.Transform(xmlReadB, null, writer);
return writer.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
The issue you are running into is that you are starting up a second MySqlCommand
while still reading back data with the DataReader
. The MySQL connector only allows one concurrent query. You need to read the data into some structure, then close the reader, then process the data. Unfortunately you can't process the data as it is read if your processing involves further SQL queries.
@[User::path] ="MDS/Material/"+(DT_STR, 4, 1252) DATEPART("yy" , GETDATE())+ "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
I think you simply have a double conversion of the character type there :D
It may be, because you opened an html document within a html document. So you have something that looks like this in the end
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test</title>.......
The use of mb_detect_encoding
therefore may lead you to other issues.
Programs to monitor if a process on a system is running.
Script is stored in crontab
and runs once every minute.
#! /bin/bash
case "$(pidof amadeus.x86 | wc -w)" in
0) echo "Restarting Amadeus: $(date)" >> /var/log/amadeus.txt
/etc/amadeus/amadeus.x86 &
;;
1) # all ok
;;
*) echo "Removed double Amadeus: $(date)" >> /var/log/amadeus.txt
kill $(pidof amadeus.x86 | awk '{print $1}')
;;
esac
0
If process is not found, restart it.
1
If process is found, all ok.
*
If process running 2 or more, kill the last.
It just tests the exit flag $?
from the pidof
program. It will be 0
of process is running and 1
if not.
#!/bin/bash
pidof amadeus.x86 >/dev/null
if [[ $? -ne 0 ]] ; then
echo "Restarting Amadeus: $(date)" >> /var/log/amadeus.txt
/etc/amadeus/amadeus.x86 &
fi
pidof amadeus.x86 >/dev/null ; [[ $? -ne 0 ]] && echo "Restarting Amadeus: $(date)" >> /var/log/amadeus.txt && /etc/amadeus/amadeus.x86 &
cccam oscam
If you want to run all the tests from various test case classes and you're happy to specify them explicitly then you can do it like this:
from unittest import TestLoader, TextTestRunner, TestSuite
from uclid.test.test_symbols import TestSymbols
from uclid.test.test_patterns import TestPatterns
if __name__ == "__main__":
loader = TestLoader()
tests = [
loader.loadTestsFromTestCase(test)
for test in (TestSymbols, TestPatterns)
]
suite = TestSuite(tests)
runner = TextTestRunner(verbosity=2)
runner.run(suite)
where uclid
is my project and TestSymbols
and TestPatterns
are subclasses of TestCase
.
best way:
<xmp>
// your codes ..
</xmp>
old samples:
sample 1:
<pre>
This text has
been formatted using
the HTML pre tag. The brower should
display all white space
as it was entered.
</pre>
sample 2:
<pre>
<code>
My pre-formatted code
here.
</code>
</pre>
sample 3: (If you are actually "quoting" a block of code, then the markup would be)
<blockquote>
<pre>
<code>
My pre-formatted "quoted" code here.
</code>
</pre>
</blockquote>
nice CSS sample:
pre{
font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
margin-bottom: 10px;
overflow: auto;
width: auto;
padding: 5px;
background-color: #eee;
width: 650px!ie7;
padding-bottom: 20px!ie7;
max-height: 600px;
}
Syntax highlighting code (For pro work):
rainbows (very Perfect)
best links for you:
https://github.com/balupton/jquery-syntaxhighlighter
http://bavotasan.com/2009/how-to-wrap-text-within-the-pre-tag-using-css/
http://alexgorbatchev.com/SyntaxHighlighter/
If order does not matter and when it's more performant to run in parallel, Collect to a Map and then get values:
employee.stream().collect(Collectors.toConcurrentMap(Employee::getId, Function.identity(), (p, q) -> p)).values()
Here's one way to do it, but probably not the most efficient.
find -type d -print0 | xargs -0 -n1 bash -c 'echo -n "$1:"; ls -1 "$1" | wc -l' --
Gives output like this, with directory name followed by count of entries in that directory. Note that the output count will also include directory entries which may not be what you want.
./c/fa/l:0
./a:4
./a/c:0
./a/a:1
./a/a/b:0
The simplest answer is to ensure that your pod or replication controller yaml/json files add the pod IP as an environment variable by adding the config block defined below. (the block below additionally makes the name and namespace available to the pod)
env:
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: MY_POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: MY_POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
Recreate the pod/rc and then try
echo $MY_POD_IP
also run env
to see what else kubernetes provides you with.
Cheers
Winand, Quality was also an issue for me so I did this:
For Each ws In ActiveWorkbook.Worksheets
If ws.PageSetup.PrintArea <> "" Then
'Reverse the effects of page zoom on the exported image
zoom_coef = 100 / ws.Parent.Windows(1).Zoom
areas = Split(ws.PageSetup.PrintArea, ",")
areaNo = 0
For Each a In areas
Set area = ws.Range(a)
' Change xlPrinter to xlScreen to see zooming white space
area.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
Set chartobj = ws.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
chartobj.Chart.Paste
'scale the image before export
ws.Shapes(chartobj.Index).ScaleHeight 3, msoFalse, msoScaleFromTopLeft
ws.Shapes(chartobj.Index).ScaleWidth 3, msoFalse, msoScaleFromTopLeft
chartobj.Chart.Export ws.Name & "-" & areaNo & ".png", "png"
chartobj.delete
areaNo = areaNo + 1
Next
End If
Next
See here:https://robp30.wordpress.com/2012/01/11/improving-the-quality-of-excel-image-export/
To whomever searching for default value...
It is written in the source code at version 2.0.5 of spring-boot and 1.1.0 at JpaProperties:
/**
* DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto"
* property. Defaults to "create-drop" when using an embedded database and no
* schema manager was detected. Otherwise, defaults to "none".
*/
private String ddlAuto;
To rename file using refactoring (which also updates all occurrences of name in other scripts):
See "PHP Developer User Guide > Tasks > Using Refactoring > Renaming Files".
If you want maximum throughput, allowing multiple readers to read and only one writer to write, BCL has something called ReaderWriterLockSlim that should help slim down your code...
Shortcut from JavaDoc:
boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e))
Oh so i guess .pretty() is equal to:
db.collection.find().forEach(printjson);
I use it to amend more than just the last commit.
Let's say I made a mistake in commit A and then made commit B. Now I can only amend B.
So I do git reset --soft HEAD^^
, I correct and re-commit A and then re-commit B.
Of course, it's not very convenient for large commits… but you shouldn't do large commits anyway ;-)
XCode 10 with Swift 4.2
import UIKit
class ViewController: UIViewController {
var timer = Timer()
var totalSecond = 10
override func viewDidLoad() {
super.viewDidLoad()
startTimer()
}
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}
@objc func updateTime() {
print(timeFormatted(totalSecond))
if totalSecond != 0 {
totalSecond -= 1
} else {
endTimer()
}
}
func endTimer() {
timer.invalidate()
}
func timeFormatted(_ totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
return String(format: "0:%02d", seconds)
}
}
I'm guessing you're using SQL 2005 or greater. The 2nd line selects the top 2 rows and by using ORDER BY ROW_COUNT DESC
, the 2nd row is arranged as being first, then it is selected using TOP 1
SELECT TOP 1 COLUMN1, COLUMN2
from (
SELECT TOP 2 COLUMN1, COLUMN2
FROM Table
) ORDER BY ROW_NUMBER DESC
Install JavaScript Development Tools (JSDT) and AngularJS Eclipse plug-in in eclipse from Eclipse Marketplace or Update site angularjs-eclipse-0.5.0,
Right Click on your project --> Configure --> Convert to Angularjs Project
(as shown below)
Now you can see the Angularjs tags available as shown below.
.
When I tried to make ObjectMapper primary in spring boot 2.0.6 I got errors So I modified the one that spring boot created for me
Also see https://stackoverflow.com/a/48519868/255139
@Lazy
@Autowired
ObjectMapper mapper;
@PostConstruct
public ObjectMapper configureMapper() {
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true);
mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
SimpleModule module = new SimpleModule();
module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
module.addSerializer(LocalDate.class, new LocalDateSerializer());
mapper.registerModule(module);
return mapper;
}
Using Git Bash on Windows 10 and Python36 for Windows I found the virtualenvwrapper.sh in a slightly different place and running this resolved the issue
source virtualenvwrapper.sh
/c/users/[myUserName]/AppData/Local/Programs/Python36/Scripts
Is there a way to have placeholders, like ? for column names? For example SELECT ? FROM TABLEA GROUP BY ?
Use dynamic query as below:
String queryString = "SELECT "+ colName+ " FROM TABLEA GROUP BY "+ colName;
If I want to simply run the above query and get a List what is the best way?
List<String> data = getJdbcTemplate().query(query, new RowMapper<String>(){
public String mapRow(ResultSet rs, int rowNum)
throws SQLException {
return rs.getString(1);
}
});
EDIT: To Stop SQL Injection, check for non word characters in the colName as :
Pattern pattern = Pattern.compile("\\W");
if(pattern.matcher(str).find()){
//throw exception as invalid column name
}
For those who might need it, a "FILE_LINE" macro to easily print file and line:
#define STRINGIZING(x) #x
#define STR(x) STRINGIZING(x)
#define FILE_LINE __FILE__ ":" STR(__LINE__)
A lot of the answers in this thread get the point of using refs, but I think a complete example would be good. Since you're operating on an actual DOM node by using the event listener and stepping out of the React context, a ref should be considered the standard solution. Here's a complete example:
class someComponent extends Component {
constructor(props) {
super(props)
this.node = null
}
render() {
return (
<div ref={node => { this.node = node }}>Content</div>
)
}
handleEvent(event) {
if (this.node) {
this.setState({...})
}
}
componentDidMount() {
//as soon as render completes, the node will be registered.
const handleEvent = this.handleEvent.bind(this)
this.node.addEventListener('click', handleEvent)
}
componentWillUnmount() {
const handleEvent = this.handleEvent.bind(this)
this.node.removeEventListener('click', handleEvent)
}
}
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
You need to follow the advice from Miles M comment and here is a little code that fixes the range in mysql. Also u need to open up my.ini(Mysql) and change max_execution_time=60 to max_execution_time=6000; for large databases. Dont use "ALTER TABLE tablename AUTO_INCREMENT = 1" it will delete everything in your database.
$con=mysqli_connect($dbhost, $dbuser, $dbpass, $database);
$res=mysqli_query($con, "select * FROM data WHERE id LIKE id ORDER BY id ASC");
$count = 0;
while ($row = mysqli_fetch_array($res)){
$count++;
mysqli_query($con, "UPDATE data SET id='".$count."' WHERE id='".$row['id']."'");
}
echo 'Done reseting id';
mysqli_close($con);
I searched around as well and probably some answers do fit for some situations,
my situation is Mysql 5.7 on a Ubuntu 18.04.2 LTS system:
(get root privileges)
$ sudo bash
(set up password for root db user + implement security in steps)
# mysql_secure_installation
(give access to the root user via password in stead of socket)
(+ edit: apparently you need to set the password again?)
(don't set it to 'mySecretPassword'!!!)
# mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql> set password for 'root'@'localhost' = PASSWORD('mySecretPassword');
mysql> FLUSH PRIVILEGES;
mysql> exit;
# service mysql restart
Many thanks to zetacu (and erich) for this excellent answer (after searching a couple of hours...)
Enjoy :-D
S.
Edit (2020):
This method doesn't work anymore, see this question for future reference...
I think you want the selected item of the spinner when button is clicked..
Try getSelectedItem():
spinner.getSelectedItem()
If you're displaying a user-readable file name, you do not want to use lastPathComponent
. Instead, pass the full path to NSFileManager's displayNameAtPath:
method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.
Try this:
myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))
giving:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
or this:
myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))
giving:
V1 V2 V3 V4 V5
1 1 2 3 5 1
2 2 4 4 1 2
3 1 4 1 1 0
4 4 5 1 3 0
5 5 5 5 4 0
Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.
Above used this input:
myfile <-
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L,
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))
Update 1 Since originally posted dplyr has changed %.%
to %>%
so have modified answer accordingly.
Update 2 dplyr now has case_when
which provides another solution:
myfile %>%
mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1,
V2 == 4 & V3 != 1 ~ 2,
TRUE ~ 0))
You can do like...
If you want to access using ColumnName
Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0]["column4Name"].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0]["column5Name"].ToString());
OR, if you want to access using Index
Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0][4].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0][5].ToString());
Without a RE (which I assume is what you want):
def remafterellipsis(text):
where_ellipsis = text.find('...')
if where_ellipsis == -1:
return text
return text[:where_ellipsis + 3]
or, with a RE:
import re
def remwithre(text, there=re.compile(re.escape('...')+'.*')):
return there.sub('', text)
Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.
Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).
So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...
If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.
insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)
There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:
CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int
AS
If you want to know what the ID of the newly inserted record is add
SELECT @@IDENTITY
to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx
You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.
P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.
Yes, it is. Just create files in the windows explorer and git automatically detects these files as currently untracked. Then add it with the command you already mentioned.
git add
does not create any files. See also http://gitref.org/basic/#add
Github probably creates the file with touch
and adds the file for tracking automatically. You can do this on the bash
as well.
If you need to reference a dynamically generated value you can also append query string paramters after the @URL.Action like so:
var id = $(this).attr('id');
var value = $(this).attr('value');
$('#user_content').load('@Url.Action("UserDetails","User")?Param1=' + id + "&Param2=" + value);
public ActionResult Details( int id, string value )
{
var model = GetFooModel();
if (Request.IsAjaxRequest())
{
return PartialView( "UserDetails", model );
}
return View(model);
}
simple is the best and works in every version.
if a>10:
value="b"
else:
value="c"
You've imported the certificate into the truststore of the JRE provided in the JDK, but you are running the java.exe of the JRE installed directly.
EDIT
For clarity, and to resolve the morass of misunderstanding in the commentary below, you need to import the certificate into the cacerts
file of the JRE you are intending to use, and that will rarely if ever be the one shipping inside the JDK, because clients won't normally have a JDK. Anything in the commentary below that suggests otherwise should be ignored as not expressing my intention here.
A far better solution would be to create your own truststore, starting with a copy of the cacerts
file, and specifically tell Java to use that one via the system property javax.net.ssl.trustStore.
You should make building this part of your build process, so as to keep up to date with changes I the cacerts
file caused by JDK upgrades.
You can use [(ngModel)]
, but you'll need to update your value
to [value]
otherwise the value is evaluating as a string. It would look like this:
<label>This rule is true if:</label>
<label class="form-check-inline">
<input class="form-check-input" type="radio" name="mode" [value]="true" [(ngModel)]="rule.mode">
</label>
<label class="form-check-inline">
<input class="form-check-input" type="radio" name="mode" [value]="false" [(ngModel)]="rule.mode">
</label>
If rule.mode
is true, then that radio is selected. If it's false, then the other.
The difference really comes down to the value
. value="true"
really evaluates to the string 'true', whereas [value]="true"
evaluates to the boolean true.
If you want to call these methods without including module in another class then you need to define them as module methods:
module UsefulThings
def self.get_file; ...
def self.delete_file; ...
def self.format_text(x); ...
end
and then you can call them with
UsefulThings.format_text("xxx")
or
UsefulThings::format_text("xxx")
But anyway I would recommend that you put just related methods in one module or in one class. If you have problem that you want to include just one method from module then it sounds like a bad code smell and it is not good Ruby style to put unrelated methods together.
menubar must no, or 0, for Google Chrome to open in new window instead of tab.
NOTE: This is an old answer, for PHP 5.5 and below. PHP 5.6+ supports default arguments
In PHP 5.5 and below, you can achieve this by using one of these 2 methods:
function method_1()
{
$arg1 = (func_num_args() >= 1)? func_get_arg(0): "default_value_for_arg1";
$arg2 = (func_num_args() >= 2)? func_get_arg(1): "default_value_for_arg2";
}
function method_2($arg1 = null, $arg2 = null)
{
$arg1 = $arg1? $arg1: "default_value_for_arg1";
$arg2 = $arg2? $arg2: "default_value_for_arg2";
}
I prefer the second method because it's clean and easy to understand, but sometimes you may need the first method.
Ended up just using the built-in angular attribute ng-checked="model"
See the swagger-api/swagger-codegen project on GitHub ; the project README shows how to use it to generate static HTML. See Generating static html api documentation.
If you want to view the swagger.json you can install the Swagger UI and run it. You just deploy it on a web server (the dist folder after you clone the repo from GitHub) and view the Swagger UI in your browser. It's a JavaScript app.
Just stumbled on the answer. android:inputType="textPassword"
does work with android:hint
, same as android:password
. The only difference is when I use android:gravity="center"
, the hint will not show if I'm using android:inputType
. Case closed!
I use json_decode($response->getBody())
now instead of $response->json()
.
I suspect this might be a casualty of PSR-7 compliance.
The embedded code of youtube has autoplay off by default. Simply add autoplay=1
at the end of "src" attribute. For example:
<iframe src="http://www.youtube.com/embed/xzvScRnF6MU?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>
Try this, It will help.
I have used this in my project.
SELECT
*
FROM
customer c
OUTER APPLY(SELECT top 1 * FROM purchase pi
WHERE pi.customer_id = c.Id order by pi.Id desc) AS [LastPurchasePrice]
In my case, the installation of nlme
package is in trouble:
mv: cannot move '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/nlme'
to '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/00LOCK-nlme/nlme':
Permission denied
Using Ubuntu 18.04, CTRL+ALT+T to open a terminal window:
sudo R
install.packages('nlme')
q()
add option 'close' like under sample and do what you want inline function
close: function(e){
//do something
}
How would you check if a variable is a dictionary in Python?
This is an excellent question, but it is unfortunate that the most upvoted answer leads with a poor recommendation, type(obj) is dict
.
(Note that you should also not use dict
as a variable name - it's the name of the builtin object.)
If you are writing code that will be imported and used by others, do not presume that they will use the dict builtin directly - making that presumption makes your code more inflexible and in this case, create easily hidden bugs that would not error the program out.
I strongly suggest, for the purposes of correctness, maintainability, and flexibility for future users, never having less flexible, unidiomatic expressions in your code when there are more flexible, idiomatic expressions.
is
is a test for object identity. It does not support inheritance, it does not support any abstraction, and it does not support the interface.
So I will provide several options that do.
This is the first recommendation I would make, because it allows for users to supply their own subclass of dict, or a OrderedDict
, defaultdict
, or Counter
from the collections module:
if isinstance(any_object, dict):
But there are even more flexible options.
from collections.abc import Mapping
if isinstance(any_object, Mapping):
This allows the user of your code to use their own custom implementation of an abstract Mapping, which also includes any subclass of dict
, and still get the correct behavior.
You commonly hear the OOP advice, "program to an interface".
This strategy takes advantage of Python's polymorphism or duck-typing.
So just attempt to access the interface, catching the specific expected errors (AttributeError
in case there is no .items
and TypeError
in case items
is not callable) with a reasonable fallback - and now any class that implements that interface will give you its items (note .iteritems()
is gone in Python 3):
try:
items = any_object.items()
except (AttributeError, TypeError):
non_items_behavior(any_object)
else: # no exception raised
for item in items: ...
Perhaps you might think using duck-typing like this goes too far in allowing for too many false positives, and it may be, depending on your objectives for this code.
Don't use is
to check types for standard control flow. Use isinstance
, consider abstractions like Mapping
or MutableMapping
, and consider avoiding type-checking altogether, using the interface directly.
Like this:
if ($('input[value=""]').length > 0) {
console.log('some fields are empty!')
}
EDIT: URIUtil
is no longer available in more recent versions, better answer at Java - encode URL or by Mr. Sindi in this thread.
URIUtil
of Apache httpclient is really useful, although there are some alternatives
URIUtil.encodeQuery(url);
For example, it encodes space as "+" instead of "%20"
Both are perfectly valid in the right context. Although if you really preferred you could issue a string replace.
I think you want to put a
, in front of a:link
(a
, a:link
) in your CSS file. The only way I could get rid of that awful default blue link color. I'm not sure if this was necessary for earlier version of the browsers we have, because it's supposed to work without a
The C++03 standard relies on the C90 standard for what the standard calls the Standard C Library which is covered in the draft C++03 standard (closest publicly available draft standard to C++03 is N1804) section 1.2
Normative references:
The library described in clause 7 of ISO/IEC 9899:1990 and clause 7 of ISO/IEC 9899/Amd.1:1995 is hereinafter called the Standard C Library.1)
If we go to the C documentation for round, lround, llround on cppreference we can see that round and related functions are part of C99 and thus won't be available in C++03 or prior.
In C++11 this changes since C++11 relies on the C99 draft standard for C standard library and therefore provides std::round and for integral return types std::lround, std::llround :
#include <iostream>
#include <cmath>
int main()
{
std::cout << std::round( 0.4 ) << " " << std::lround( 0.4 ) << " " << std::llround( 0.4 ) << std::endl ;
std::cout << std::round( 0.5 ) << " " << std::lround( 0.5 ) << " " << std::llround( 0.5 ) << std::endl ;
std::cout << std::round( 0.6 ) << " " << std::lround( 0.6 ) << " " << std::llround( 0.6 ) << std::endl ;
}
Another option also from C99 would be std::trunc which:
Computes nearest integer not greater in magnitude than arg.
#include <iostream>
#include <cmath>
int main()
{
std::cout << std::trunc( 0.4 ) << std::endl ;
std::cout << std::trunc( 0.9 ) << std::endl ;
std::cout << std::trunc( 1.1 ) << std::endl ;
}
If you need to support non C++11 applications your best bet would be to use boost round, iround, lround, llround or boost trunc.
Rolling your own version of round is hard
Rolling your own is probably not worth the effort as Harder than it looks: rounding float to nearest integer, part 1, Rounding float to nearest integer, part 2 and Rounding float to nearest integer, part 3 explain:
For example a common roll your implementation using std::floor
and adding 0.5
does not work for all inputs:
double myround(double d)
{
return std::floor(d + 0.5);
}
One input this will fail for is 0.49999999999999994
, (see it live).
Another common implementation involves casting a floating point type to an integral type, which can invoke undefined behavior in the case where the integral part can not be represented in the destination type. We can see this from the draft C++ standard section 4.9
Floating-integral conversions which says (emphasis mine):
A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.[...]
For example:
float myround(float f)
{
return static_cast<float>( static_cast<unsigned int>( f ) ) ;
}
Given std::numeric_limits<unsigned int>::max()
is 4294967295
then the following call:
myround( 4294967296.5f )
will cause overflow, (see it live).
We can see how difficult this really is by looking at this answer to Concise way to implement round() in C? which referencing newlibs version of single precision float round. It is a very long function for something which seems simple. It seems unlikely that anyone without intimate knowledge of floating point implementations could correctly implement this function:
float roundf(x)
{
int signbit;
__uint32_t w;
/* Most significant word, least significant word. */
int exponent_less_127;
GET_FLOAT_WORD(w, x);
/* Extract sign bit. */
signbit = w & 0x80000000;
/* Extract exponent field. */
exponent_less_127 = (int)((w & 0x7f800000) >> 23) - 127;
if (exponent_less_127 < 23)
{
if (exponent_less_127 < 0)
{
w &= 0x80000000;
if (exponent_less_127 == -1)
/* Result is +1.0 or -1.0. */
w |= ((__uint32_t)127 << 23);
}
else
{
unsigned int exponent_mask = 0x007fffff >> exponent_less_127;
if ((w & exponent_mask) == 0)
/* x has an integral value. */
return x;
w += 0x00400000 >> exponent_less_127;
w &= ~exponent_mask;
}
}
else
{
if (exponent_less_127 == 128)
/* x is NaN or infinite. */
return x + x;
else
return x;
}
SET_FLOAT_WORD(x, w);
return x;
}
On the other hand if none of the other solutions are usable newlib could potentially be an option since it is a well tested implementation.
This can be changed in your my.ini
file (on Windows, located in \Program Files\MySQL\MySQL Server) under the server section, for example:
[mysqld]
max_allowed_packet = 10M
I ran into this issue when trying to root the emulator, I found out it was because I was running the Nexus 5x emulator which had Google Play on it. Created a different emulator that didn't have google play and adb root
will root the device for you. Hope this helps someone.
You will need to define the repository outside of buildscript
. The buildscript
configuration block only sets up the repositories and dependencies for the classpath of your build script but not your application.
Display the row as a block.
tr {
display: block;
border-bottom: 1px solid #000;
}
and to display alternate colors simply:
tr.oddrow {
display: block;
border-bottom: 1px solid #F00;
}
Right-click on your project and choose Maven > Update Snapshots
. In addition to that you can set "update Maven projects on startup" in Window > Preferences > Maven
UPDATE: In latest versions of Eclipse:
Maven > Update Project
. Make sure "Force Update of Snapshots/Releases" is checked.
Most of the roles you see were defined as part of ARIA 1.0, and then later incorporated into HTML via supporting specs like HTML-AAM. Some of the new HTML5 elements (dialog, main, etc.) are even based on the original ARIA roles.
http://www.w3.org/TR/wai-aria/
There are a few primary reasons to use roles in addition to your native semantic element.
Reason #1. Overriding the role where no host language element is appropriate or, for various reasons, a less semantically appropriate element was used.
In this example, a link was used, even though the resulting functionality is more button-like than a navigation link.
<a href="#" role="button" aria-label="Delete item 1">Delete</a>
<!-- Note: href="#" is just a shorthand here, not a recommended technique. Use progressive enhancement when possible. -->
Screen readers users will hear this as a button (as opposed to a link), and you can use a CSS attribute selector to avoid class-itis and div-itis.
[role="button"] {
/* style these as buttons w/o relying on a .button class */
}
[Update 7 years later: removed the * selector to make some commenters happy, since the old browser quirk that required universal selector on attribute selectors is unnecessary in 2020.]
Reason #2. Backing up a native element's role, to support browsers that implemented the ARIA role but haven't yet implemented the native element's role.
For example, the "main" role has been supported in browsers for many years, but it's a relatively recent addition to HTML5, so many browsers don't yet support the semantic for <main>
.
<main role="main">…</main>
This is technically redundant, but helps some users and doesn't harm any. In a few years, this technique will likely become unnecessary for main.
Reason #3. Update 7 years later (2020): As at least one commenter pointed out, this is now very useful for custom elements, and some spec work is underway to define the default accessibility role of a web component. Even if/once that API is standardized, there may be need to override the default role of a component.
Note/Reply
You also wrote:
I see some people make up their own. Is that allowed or a correct use of the role attribute?
That's an allowed use of the attribute unless a real role is not included. Browsers will apply the first recognized role in the token list.
<span role="foo link note bar">...</a>
Out of the list, only link
and note
are valid roles, and so the link role will be applied in the platform accessibility API because it comes first. If you use custom roles, make sure they don't conflict with any defined role in ARIA or the host language you're using (HTML, SVG, MathML, etc.)
After installing tomcat, you can choose "configure tomcat" by search in "search programs and files". After clicking on "configure Tomcat", you should give admin permissions and the window opens. Then click on "java" tab. There you can see the JVM and JAVA classpath.
These port assignments are specified by the Internet Assigned Numbers Authority (IANA):
Historically, port 465 was initially planned for the SMTPS encryption and authentication “wrapper” over SMTP, but it was quickly deprecated (within months, and over 15 years ago) in favor of STARTTLS over SMTP (RFC 3207). Despite that fact, there are probably many servers that support the deprecated protocol wrapper, primarily to support older clients that implemented SMTPS. Unless you need to support such older clients, SMTPS and its use on port 465 should remain nothing more than an historical footnote.
The hopelessly confusing and imprecise term, SSL, has often been used to indicate the SMTPS wrapper and TLS to indicate the STARTTLS protocol extension.
The most simple way would be to use the Join() method:
public static void Trail()
{
var list = new List<string> { "lala", "lulu", "lele" };
var data = string.Join(",", list);
}
If you really need the StringBuilder, trim the end comma after the loop:
data.ToString().TrimEnd(',');
This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.
The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...)
and cola<string>::cola(...)
until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T>
also.)
The problem is caused by the fact that main.cpp
and cola.cpp
will be compiled separately first. In main.cpp
, the compiler will implicitly instantiate the template classes cola<float>
and cola<string>
because those particular instantiations are used in main.cpp
. The bad news is that the implementations of those member functions are not in main.cpp
, nor in any header file included in main.cpp
, and therefore the compiler can't include complete versions of those functions in main.o
. When compiling cola.cpp
, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float>
or cola<string>
. Remember, when compiling cola.cpp
, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>
, cola<char>
, cola<ostream>
, cola< cola<int> >
... and so on ...)
The two answers are:
cola.cpp
, which particular template classes will be required, forcing it to compile cola<float>
and cola<string>
.main.cpp
) uses the template class.At the end of cola.cpp
, you should add lines explicitly instantiating all the relevant templates, such as
template class cola<float>;
template class cola<string>;
and you add the following two lines at the end of nodo_colaypila.cpp
:
template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;
This will ensure that, when the compiler is compiling cola.cpp
that it will explicitly compile all the code for the cola<float>
and cola<string>
classes. Similarly, nodo_colaypila.cpp
contains the implementations of the nodo_colaypila<...>
classes.
In this approach, you should ensure that all the of the implementation is placed into one .cpp
file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).
The common answer is to move all the code from the implementation files cola.cpp
and nodo_colaypila.cpp
into cola.h
and nodo_colaypila.h
. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>
) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.
The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float>
and cola<string>
, if you want to use something else, tell me first and will can verify it works before enabling it.").
Finally, there are three other minor typos in the code in your question:
#endif
at the end of nodo_colaypila.hnodo_colaypila<T>* ult, pri;
should be nodo_colaypila<T> *ult, *pri;
- both are pointers.nodo_colaypila.h
, not in this implementation file.Height lines converted into points and pixel (my own formula). Here is an example with a manual entry of 213.67 points in the Row Height field:
213.67 Manual Entry
0.45 Add 0.45
214.12 Subtotal
213.75 Round to a multiple of 0.75
213.00 Subtract 0.75 provides manual entry converted by Excel
284.00 Divide by 0.75 gives the number of pixels of height
Here the manual entry of 213.67 points gives 284 pixels.
Here the manual entry of 213.68 points gives 285 pixels.
(Why 0.45? I do not know but it works.)
I am talking here from a theoretical point of view; I have not tried BitLocker.
BitLocker uses AES encryption with a 128-bit key. On a Core2 machine, clocked at 2.53 GHz, encryption speed should be about 110 MB/s, using one core. The two cores could process about 220 MB/s, assuming perfect data transfer and core synchronization with no overhead, and that nothing requires the CPU in the same time (that one hell of an assumption, actually). The X25-M G2 is announced at 250 MB/s read bandwidth (that's what the specs say), so, in "ideal" conditions, BitLocker necessarily involves a bit of a slowdown.
However read bandwidth is not that important. It matters when you copy huge files, which is not something that you do very often. In everyday work, access time is much more important: as a developer, you create, write, read and delete many files, but they are all small (most of them are much smaller than one megabyte). This is what makes SSD "snappy". Encryption does not impact access time. So my guess is that any performance degradation will be negligible(*).
(*) Here I assume that Microsoft's developers did their job properly.
If your file contains lines with different lengths and you need to read lines often and you need to read it quickly you can make an index of the file by reading it once, saving position of each new line and then when you need to read a line, you just lookup the position of the line in your index, seek there and then you read the line.
If you add new lines to the file you can just add index of new lines and you don't need to reindex it all. Though if your file changes somewhere in a line you have already indexed then you have to reindex.
Eclipse: Right click on the project > Android tools > Rename application package.
As simple as that...
In Android Studio: open the build.gradle file > rename the applicationId under defaultConfig > synchronize
Also worth noting that WinFlexBison has been packaged for the Chocolatey package manager. Install that and then go:
choco install winflexbison
...which at the time of writing contains Bison 2.7 & Flex 2.6.3.
There is also winflexbison3
which (at the time of writing) has Bison 3.0.4 & Flex 2.6.3.
I ran into this issue after updating the Java JDK, but had not yet restarted my command prompt. After restarting the command prompt, everything worked fine. Presumably, because the PATH variable need to be reset after the JDK update.
"Java 8 support for Eclipse Kepler SR2", and the new "JavaSE-1.8" execution environment showed up automatically.
Download this one:- Eclipse kepler SR2
and then follow this link:- Eclipse_Java_8_Support_For_Kepler
I came up with an generic, interesting solution to this problem:
class SafeInvocator(object):
def __init__(self, module):
self._module = module
def _safe(self, func):
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
return None
return inner
def __getattr__(self, item):
obj = getattr(self.module, item)
return self._safe(obj) if hasattr(obj, '__call__') else obj
and you can use it like so:
safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
# do something
I faced the same error, in my case I miss-spelled ng-model directive something like "ng-moel"
Wrong one: ng-moel="user.name" Right one: ng-model="user.name"
You use
#main_text .title {
/* Properties */
}
If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text
with the class name title
. If you use >
instead of a space, it will only select the direct child of the element, and not children of children, e.g.:
#main_text > .title {
/* Properties */
}
Either will work in this case, but the first is more typically used.
You can call this function in beforeMount section of a Vue component: like following:
....
methods:{
getUnits: function() {...}
},
beforeMount(){
this.getUnits()
},
......
Working fiddle: https://jsfiddle.net/q83bnLrx/1/
There are different lifecycle hooks Vue provide:
I have listed few are :
vm.$el
.You can have a look at complete list here.
You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.
Use count(*)
declare
cnt integer;
begin
SELECT count(*) INTO cnt
FROM people
WHERE person_id = my_person_id;
IF cnt > 0 THEN
-- Do something
END IF;
Edit (for the downvoter who didn't read the statement and others who might be doing something similar)
The solution is only effective because there is a where clause on a column (and the name of the column suggests that its the primary key - so the where clause is highly effective)
Because of that where
clause there is no need to use a LIMIT or something else to test the presence of a row that is identified by its primary key. It is an effective way to test this.
This can help:
mysqldump --compatible=mysql40 -u user -p DB > dumpfile.sql
PHPMyAdmin has the same MySQL compatibility mode in the 'expert' export options. Although that has on occasions done nothing.
If you don't have access via the command line or via PHPMyAdmin then editing the
/*!50003 SET character_set_client = utf8mb4 */ ;
bit to read 'utf8'
only, is the way to go.
If you are using OSX and have yet to set your locale module setting this first answer will not work you will receive the following error:
Traceback (most recent call last):File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 221, in currency
raise ValueError("Currency formatting is not possible using "ValueError: Currency formatting is not possible using the 'C' locale.
To remedy this you will have to do use the following:
locale.setlocale(locale.LC_ALL, 'en_US')
Try using file to view the encoding details (reference):
cd directory/of/interest
file *
It produces useful output like this:
$ file *
CR6Series_stats resaved.dat: ASCII text, with very long lines, with CRLF line terminators
CR6Series_stats utf8.dat: UTF-8 Unicode (with BOM) text, with very long lines, with CRLF line terminators
CR6Series_stats.dat: ASCII text, with very long lines, with CRLF line terminators
readme.md: ASCII text, with CRLF line terminators
You could instantiate the values from a dictionary if you wanted different values for each column & you don't mind making a dictionary on the line before.
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
>>> df
col_1 col_2
0 0 4
1 1 5
2 2 6
3 3 7
>>> cols = {
'column_new_1':np.nan,
'column_new_2':'dogs',
'column_new_3': 3
}
>>> df[list(cols)] = pd.DataFrame(data={k:[v]*len(df) for k,v in cols.items()})
>>> df
col_1 col_2 column_new_1 column_new_2 column_new_3
0 0 4 NaN dogs 3
1 1 5 NaN dogs 3
2 2 6 NaN dogs 3
3 3 7 NaN dogs 3
Not necessarily better than the accepted answer, but it's another approach not yet listed.
It may be a problem with the Google Play Services dependencies rather than an actual app version issue.
Sometimes, it is NOT the case that:
a) there is an existing version of the app installed, newer or not b) there is an existing version of the app installed on another user account on the device
So the error message is just bogus.
In my case, I had:
implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.gms:play-services-gcm:16.0.0'
But when I tried
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.google.android.gms:play-services-gcm:17.0.0'
I got androidX related errors, as I had not yet upgraded to androidX and was not ready to do so. I found that using the latest 16.x.y versions work and I don't get the error message any more. Furthermore, I could wait till later when I am ready, to upgrade to androidX.
implementation 'com.google.android.gms:play-services-maps:16.+'
implementation 'com.google.android.gms:play-services-location:16.+'
implementation 'com.google.android.gms:play-services-gcm:16.+'
this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in this case:
you specify
transaction_status varchar(10)
but you actually trying to store
_transaction_status
which contain 19 characters.
that's why you faced this type of error in this code..
If the servers are clustered and there is a clustered DTC you have to disable security on the clustered DTC not the local DTC.
git reset
and git clean
can be overkill in some situations (and be a huge waste of time).
If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch>
is the best option.
If you're like me, your other option was to clean and perform a --hard reset
then recompile your project.
You can use MySQL variables to do it. Something like this should work (though, it consists of two queries).
SELECT 0 INTO @x;
SELECT itemID,
COUNT(*) AS ordercount,
(@x:=@x+1) AS rownumber
FROM orders
GROUP BY itemID
ORDER BY ordercount DESC;
Example solution for adding the library to your PYTHONPATH.
Add the following line into your ~/.bashrc or just run it directly:
export PYTHONPATH="$PYTHONPATH:$HOME/.python"
Then link your required library into your ~/.python folder, e.g.
ln -s /home/user/work/project/foo ~/.python/
Yes, you can enforce the constraint only when the value is not NULL. This can be easily tested with the following example:
CREATE DATABASE t;
USE t;
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT NULL,
parent_id INT NULL,
FOREIGN KEY (parent_id) REFERENCES parent(id)
) ENGINE=INNODB;
INSERT INTO child (id, parent_id) VALUES (1, NULL);
-- Query OK, 1 row affected (0.01 sec)
INSERT INTO child (id, parent_id) VALUES (2, 1);
-- ERROR 1452 (23000): Cannot add or update a child row: a foreign key
-- constraint fails (`t/child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY
-- (`parent_id`) REFERENCES `parent` (`id`))
The first insert will pass because we insert a NULL in the parent_id
. The second insert fails because of the foreign key constraint, since we tried to insert a value that does not exist in the parent
table.
silly way:
onclick="javascript:CapacityChart();"
You should read about discrete javascript, and use a frameworks bind method to bind callbacks to dom events.
You cannot delete a variable if you declared it (with var x;
) at the time of first use.
However, if your variable x
first appeared in the script without a declaration, then you can use the delete
operator (delete x;
) and your variable will be deleted, very similar to deleting an element of an array or deleting a property of an object.
Yes, if it is .NET RegEx-engine. .Net engine supports finite state machine supplied with an external stack. see details
You can use glob for referring the directory and the list :
import glob
import os
#to get the current working directory name
cwd = os.getcwd()
#Load the images from images folder.
for f in glob.glob('images\*.jpg'):
dir_name = get_dir_name(f)
image_file_name = dir_name + '.jpg'
#To print the file name with path (path will be in string)
print (image_file_name)
To get the list of all directory in array you can use os :
os.listdir(directory)
Swift 3/ Swift 4/ Swift 5
Just one line code to omit Array duplicates without effecting order:
let filteredArr = Array(NSOrderedSet(array: yourArray))
I have same problem!
Found following in oracle site link text
As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.
If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.
Best way in giving write access to a directory..
$dst = "path/to/directory";
mkdir($dst);
chown($dst, "ownername");
chgrp($dst, "groupname");
exec ("find ".$dst." -type d -exec chmod 0777 {} +");
The simplest way to do this is as follows:
save_results_to = '/Users/S/Desktop/Results/'
plt.savefig(save_results_to + 'image.png', dpi = 300)
The image is going to be saved in the save_results_to
directory with name image.png
I realize this question is a bit dated and since it shows up on Google search for similar issue I thought I will expand a little bit more on top of @CowWarrior's answer. I was looking for somewhat similar solution, and after scouring through countless SO question/answers and Bootstrap documentations the solution was pretty simple. Again, this would be using inbuilt Bootstrap collapse
class to show/hide divs and Bootstrap's "Collapse Event".
What I realized is that it is easy to do it using a Bootstrap Accordion, but most of the time even though the functionality required is "somewhat" similar to an Accordion, it's different in a way that one would want to show hide <div>
based on, lets say, menu buttons on a navbar
. Below is a simple solution to this. The anchor tags (<a>
) could be navbar items and based on a collapse event the corresponding div will replace the existing div. It looks slightly sloppy in CodeSnippet, but it is pretty close to achieving the functionality-
All that the JavaScript does is makes all the other <div>
hide using
$(".main-container.collapse").not($(this)).collapse('hide');
when the loaded <div>
is displayed by checking the Collapse event shown.bs.collapse
. Here's the Bootstrap documentation on Collapse Event.
Note: main-container
is just a custom class.
Here it goes-
$(".main-container.collapse").on('shown.bs.collapse', function () { _x000D_
//when a collapsed div is shown hide all other collapsible divs that are visible_x000D_
$(".main-container.collapse").not($(this)).collapse('hide');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<a href="#Foo" class="btn btn-default" data-toggle="collapse">Toggle Foo</a>_x000D_
<a href="#Bar" class="btn btn-default" data-toggle="collapse">Toggle Bar</a>_x000D_
_x000D_
<div id="Bar" class="main-container collapse in">_x000D_
This div (#Bar) is shown by default and can toggle_x000D_
</div>_x000D_
<div id="Foo" class="main-container collapse">_x000D_
This div (#Foo) is hidden by default_x000D_
</div>
_x000D_
Provide the full path of the file openfile.exe
and remember not to put forward slash /
in the path such as
c:/users/username/etc....
instead of that use
c:\\Users\\username\etc
(for windows)
May be this will help you.
In the detached window (Tool Options), the name of the view (Paintbrush) is a grab-bar.
Put your cursor over the grab-bar, click and drag it to the dock area in the main window in order to reattach it to the main window.
This is a place in which C++ has a strange rule. Before being able to compile a call to a function the compiler must know the function name, return value and all parameters.
This can be done by adding a "prototype". In your case this simply means adding before main
the following line:
int writeFile();
this tells the compiler that there exist a function named writeFile
that will be defined somewhere, that returns an int
and that accepts no parameters.
Alternatively you can define first the function writeFile
and then main
because in this case when the compiler gets to main
already knows your function.
Note that this requirement of knowing in advance the functions being called is not always applied. For example for class members defined inline it's not required...
struct Foo {
void bar() {
if (baz() != 99) {
std::cout << "Hey!";
}
}
int baz() {
return 42;
}
};
In this case the compiler has no problem analyzing the definition of bar
even if it depends on a function baz
that is declared later in the source code.
Try this method. It should work when field when you want to store image is of type byte
.
First it creates byte[]
for image. Then it saves it to the DB using IDataParameter
of type binary
.
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
public static void PerisitImage(string path, IDbConnection connection)
{
using (var command = connection.CreateCommand ())
{
Image img = Image.FromFile (path);
MemoryStream tmpStream = new MemoryStream();
img.Save (tmpStream, ImageFormat.Png); // change to other format
tmpStream.Seek (0, SeekOrigin.Begin);
byte[] imgBytes = new byte[MAX_IMG_SIZE];
tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE);
command.CommandText = "INSERT INTO images(payload) VALUES (:payload)";
IDataParameter par = command.CreateParameter();
par.ParameterName = "payload";
par.DbType = DbType.Binary;
par.Value = imgBytes;
command.Parameters.Add(par);
command.ExecuteNonQuery ();
}
}
I guess some of the files in the target build directory is open in another tool you use. Just a file handle open in the folder which has to be cleaned. The build task 'clean' wants to delete all the files in the build directory(normally 'target') and when it fails, the build fails.
I had a similar issue from the console after building a Jar in Intellij. Using the Java configuration to update to a newer version (Windows -> Configure Java -> Update -> Update Now) didn't work and stuck at version 1.8 (Java 8).
To switch to a more recent version locally I had to install the Java 15 JDK from https://www.oracle.com/uk/java/technologies/javase-jdk15-downloads.html and add that to my Java runtime environment settings.
I'm having the same problem with Wampserver. It’s worked for me:
You must change this file: "C:\wamp\bin\mysql[mysql_version]\my.ini" For example: "C:\wamp\bin\mysql[mysql5.6.12]\my.ini"
And change default port 3306 to 80. (Lines 20 & 27, in both)
port = 3306 To port = 80
I hope this is helpful.
I just found how.
I delete the first occurrence of lombok @Slf4j
or log
where the compiler complains, and wait for the warning(the red bubble) of IDEA, suggesting "add the lombok.extern.Slf4j.jar to classpath". Since then all goes well. It seems IDEA likes to complain about lombok.
I had the same issue. I was calling parent page "Save" from Popup window Close. Found that I was using ClientIDMode="Static"
on both parent and popup page with same control id. Removing ClientIDMode="Static"
from one of the pages solved the issue.
Just use the *
before it
:
set<unsigned long>::iterator it;
for (it = myset.begin(); it != myset.end(); ++it) {
cout << *it;
}
This dereferences it and allows you to access the element the iterator is currently on.
Firebug shows this correctly because your Browser automagically fixes the bad markup for you. This behaviour is not specified anywhere and can (will) vary from browser to browser. Those tags are required by the DOCTYPE you're using and should not be omitted.
The html element is the root element of every html page. If you look at all other elements' description it says where an element can be used (and almost all elements require either head or body).
just run this command from command prompt and it will launch chrome instance with CORS disabled:
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
For this purposes I do the following:
<c:set var="abc">
<%=Status.OLD.getStatus()%>
</c:set>
<c:if test="${someVariable == abc}">
....
</c:if>
It's looks ugly, but works!
There are three options shown in this tutorial. In case the link breaks I'll leave the main steps here.
1 Revert the full commit
git revert dd61ab23
2 Delete the last commit
git push <<remote>> +dd61ab23^:<<BRANCH_NAME_HERE>>
or, if the branch is available locally
git reset HEAD^ --hard
git push <<remote>> -f
where +dd61... is your commit hash and git interprets x^ as the parent of x, and + as a forced non-fastforwared push.
3 Delete the commit from a list
git rebase -i dd61ab23^
This will open and editor showing a list of all commits. Delete the one you want to get rid off. Finish the rebase and push force to repo.
git rebase --continue
git push <remote_repo> <remote_branch> -f
This still loops through the cartesian product of the two lists, but it does it one line:
>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False
This also have the advantage that any
short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings
in linesX
. If you want to find multiple occurrences you could do something like this:
>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]
If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.
MobileConsole can be embedded within any page for debugging. It will catch errors and behave exactly as the native JavaScript console in the browser. It also outputs all the logs you've written via an API of window.console.
If M2_HOME
is configured to point to the Maven home directory then:
File -> Settings
Maven
Runner
Insert in the field VM Options
the following string:
Dmaven.multiModuleProjectDirectory=$M2_HOME
Click Apply
and OK
You can use String.Join
. If you have a List<string>
then you can call ToArray
first:
List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());
In .NET 4 you don't need the ToArray
anymore, since there is an overload of String.Join
that takes an IEnumerable<string>
.
Results:
John, Anna, Monica
Why work harder than you have to? postForEntity
accepts a simple Map
object as input. The following works fine for me while writing tests for a given REST endpoint in Spring. I believe it's the simplest possible way of making a JSON POST request in Spring:
@Test
public void shouldLoginSuccessfully() {
// 'restTemplate' below has been @Autowired prior to this
Map map = new HashMap<String, String>();
map.put("username", "bob123");
map.put("password", "myP@ssw0rd");
ResponseEntity<Void> resp = restTemplate.postForEntity(
"http://localhost:8000/login",
map,
Void.class);
assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
}
You can use this command and the video duration is still unaltered.
ffmpeg -i input.mp4 -r 24 output.mp4
In Unix-like environments, I also recommend checking the actual running process command line:
$ ps aux | grep java
...
/usr/lib/jvm/java-8-openjdk-amd64/bin/java -Djava.util.logging.config.file=/srv/tomcat-instances/bla/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.awt.headless=true -Xmx4096M -XX:+UseConcMarkSweepGC -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n -Xmx4096m -Xms4096m -XX:MaxPermSize=2048m -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=8090 -Dcom.sun.management.jmxremote.rmi.port=8090 -Djava.rmi.server.hostname=localhost -Djava.endorsed.dirs=/opt/apache-tomcat-8.0.47/endorsed -classpath /opt/apache-tomcat-8.0.47/bin/bootstrap.jar:/opt/apache-tomcat-8.0.47/bin/tomcat-juli.jar -Dcatalina.base=/srv/tomcat-instances/bla -Dcatalina.home=/opt/apache-tomcat-8.0.47 -Djava.io.tmpdir=/tmp/tomcat8-bla-tmp org.apache.catalina.startup.Bootstrap start
...
One can run on subtle weird behaviors due to (operating system) environment variables and (Java) system properties being set to unexpected values. I had a situation where due to an outdated Tomcat setenv.sh
, A Tomcat 8 started with classes from a Tomcat 7 on the classpath. Make sure that in the process command line options such as -Dcatalina.base
, -Dcatalina.home
and -classpath
make sense.
if You are Using Toolbar the just Add
android:layout_gravity="center_horizontal"
Under the Toolbar Just like this snippet
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" //Important
android:textColor="@color/whitecolor"
android:textSize="20sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
My PHP framework uses
SET LOCAL time_zone='Whatever'
on after connect, where 'Whatever' == date_default_timezone_get()
Not my solution, but this ensures SYSTEM
timezone of MySQL server is always the same as PHP's one
So, yes, PHP is strongly envolved and can affect it
If you NEED to do it on your phone, I use a terminal emulator and standard linux commands.
Example:
http://www.appbrain.com/app/android-terminal-emulator/jackpal.androidterm
There is a tool called MySQL Pivot table generator, it can help you create web based pivot table that you can later export to excel(if you like). it can work if your data is in a single table or in several tables .
All you need to do is to specify the data source of the columns (it supports dynamic columns), rows , the values in the body of the table and table relationship (if there are any)
The home page of this tool is http://mysqlpivottable.net
That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.
To change your Platform Toolset:
I don't think there's a jQuery-way to directly access the pseudoclass' rules, but you could always append a new style
element to the document's head like:
$('head').append('<style>.column:before{width:800px !important;}</style>');
See a live demo here
I also remember having seen a plugin that tackles this issue once but I couldn't find it on first googling unfortunately.
The identity
section goes under the system.web
section, not under authentication
:
<system.web>
<authentication mode="Windows"/>
<identity impersonate="true" userName="foo" password="bar"/>
</system.web>
try this
SELECT group_name, employees, surveys, COUNT( surveys ) AS test1,
concat(round(( surveys/employees * 100 ),2),'%') AS percentage
FROM a_test
GROUP BY employees
Use an XDocument
to create the DOM, then write it out using an XmlWriter
. This will give you a wonderfully concise and readable notation as well as nicely formatted output.
Take this sample program:
using System.Xml;
using System.Xml.Linq;
class Program {
static void Main() {
var xDocument = new XDocument(
new XDocumentType("html", null, null, null),
new XElement("html",
new XElement("head"),
new XElement("body",
new XElement("p",
"This paragraph contains ", new XElement("b", "bold"), " text."
),
new XElement("p",
"This paragraph has just plain text."
)
)
)
);
var settings = new XmlWriterSettings {
OmitXmlDeclaration = true, Indent = true, IndentChars = "\t"
};
using (var writer = XmlWriter.Create(@"C:\Users\wolf\Desktop\test.html", settings)) {
xDocument.WriteTo(writer);
}
}
}
This generates the following output:
<!DOCTYPE html >
<html>
<head />
<body>
<p>This paragraph contains <b>bold</b> text.</p>
<p>This paragraph has just plain text.</p>
</body>
</html>
Through the below code i'm able to maximize the window,
((JavascriptExecutor) driver).executeScript("if(window.screen){
window.moveTo(0, 0);
window.resizeTo(window.screen.availWidth, window.screen.availHeight);
};");
The time difference b/w to time will be shown use this method.
private void HoursCalculator()
{
var t1 = txtfromtime.Text.Trim();
var t2 = txttotime.Text.Trim();
var Fromtime = t1.Substring(6);
var Totime = t2.Substring(6);
if (Fromtime == "M")
{
Fromtime = t1.Substring(5);
}
if (Totime == "M")
{
Totime = t2.Substring(5);
}
if (Fromtime=="PM" && Totime=="AM" )
{
var dt1 = DateTime.Parse("1900-01-01 " + txtfromtime.Text.Trim());
var dt2 = DateTime.Parse("1900-01-02 " + txttotime.Text.Trim());
var t = dt1.Subtract(dt2);
//int temp = Convert.ToInt32(t.Hours);
//temp = temp / 2;
lblHours.Text =t.Hours.ToString() + ":" + t.Minutes.ToString();
}
else if (Fromtime == "AM" && Totime == "PM")
{
var dt1 = DateTime.Parse("1900-01-01 " + txtfromtime.Text.Trim());
var dt2 = DateTime.Parse("1900-01-01 " + txttotime.Text.Trim());
TimeSpan t = (dt2.Subtract(dt1));
lblHours.Text = t.Hours.ToString() + ":" + t.Minutes.ToString();
}
else
{
var dt1 = DateTime.Parse("1900-01-01 " + txtfromtime.Text.Trim());
var dt2 = DateTime.Parse("1900-01-01 " + txttotime.Text.Trim());
TimeSpan t = (dt2.Subtract(dt1));
lblHours.Text = t.Hours.ToString() + ":" + t.Minutes.ToString();
}
}
use your field id's
var t1 captures a value of 4:00AM
check this code may be helpful to someone.
If you want to revert the file to its state in master
:
git checkout origin/master [filename]
Other solutions are good enough to answer your query. However, if you are looking for just one command to do that for you -
Create a file name "run", in directory where your Java files are. And save this in your file -
javac "$1.java"
if [ $? -eq 0 ]; then
echo "--------Run output-------"
java "$1"
fi
give this file run permission by running -
chmod 777
Now you can run any of your files by merely running -
./run <yourfilename> (don't add .java in filename)
Easy way to solve OutOfMemoryError
in java is to increase the maximum heap size by using JVM options -Xmx512M
, this will immediately solve your OutOfMemoryError. This is my preferred solution when I get OutOfMemoryError in Eclipse, Maven or ANT while building project because based upon size of project you can easily ran out of Memory.
Here is an example of increasing maximum heap size of JVM, Also its better to keep -Xmx to -Xms ration either 1:1 or 1:1.5 if you are setting heap size in your java application.
export JVM_ARGS="-Xms1024m -Xmx1024m"
According to the documentation for that plugin, .visible()
returns a boolean indicating if the element is visible. So you'd use it like this:
if ($('#element').visible(true)) {
// The element is visible, do something
} else {
// The element is NOT visible, do something else
}
To quickly see the duplicate rows you can run a single simple query
Here I am querying the table and listing all duplicate rows with same user_id, market_place and sku:
select user_id, market_place,sku, count(id)as totals from sku_analytics group by user_id, market_place,sku having count(id)>1;
To delete the duplicate row you have to decide which row you want to delete. Eg the one with lower id (usually older) or maybe some other date information. In my case I just want to delete the lower id since the newer id is latest information.
First double check if the right records will be deleted. Here I am selecting the record among duplicates which will be deleted (by unique id).
select a.user_id, a.market_place,a.sku from sku_analytics a inner join sku_analytics b where a.id< b.id and a.user_id= b.user_id and a.market_place= b.market_place and a.sku = b.sku;
Then I run the delete query to delete the dupes:
delete a from sku_analytics a inner join sku_analytics b where a.id< b.id and a.user_id= b.user_id and a.market_place= b.market_place and a.sku = b.sku;
Backup, Double check, verify, verify backup then execute.
It blurs the separation of concerns.
Supposed that you have a singleton, you can call this instance from anywhere inside your class. Your class is no longer as pure as it should be. Your class will now no longer operate on its members and the members that it receives explicitly. This will create confusion, because the users of the class don't know what is the sufficient information the class needs. The whole idea of encapsulation is to hide the how of a method from the users, but if a singleton is used inside the method, one will have to know the state of the singleton in order to use the method correctly. This is anti-OOP.
You can use GCHandleType.Weak instead of Pinned. On the other hand, there is another way to get a pointer to an object:
object o = new object();
TypedReference tr = __makeref(o);
IntPtr ptr = **(IntPtr**)(&tr);
Requires unsafe block and is very, very dangerous and should not be used at all. ?
Back in the day when by-ref locals weren't possible in C#, there was one undocumented mechanism that could accomplish a similar thing – __makeref
.
object o = new object();
ref object r = ref o;
//roughly equivalent to
TypedReference tr = __makeref(o);
There is one important difference in that TypedReference is "generic"; it can be used to store a reference to a variable of any type. Accessing such a reference requires to specify its type, e.g. __refvalue(tr, object)
, and if it doesn't match, an exception is thrown.
To implement the type checking, TypedReference must have two fields, one with the actual address to the variable, and one with a pointer to its type representation. It just so happens that the address is the first field.
Therefore, __makeref
is used first to obtain a reference to the variable o
. The cast (IntPtr**)(&tr)
treats the structure as an array (represented via a pointer) of IntPtr*
(pointers to a generic pointer type), accessed via a pointer to it. The pointer is first dereferenced to obtain the first field, then the pointer there is dereferenced again to obtain the value actually stored in the variable o
– the pointer to the object itself.
However, since 2012, I have come up with a better and safer solution:
public static class ReferenceHelpers
{
public static readonly Action<object, Action<IntPtr>> GetPinnedPtr;
static ReferenceHelpers()
{
var dyn = new DynamicMethod("GetPinnedPtr", typeof(void), new[] { typeof(object), typeof(Action<IntPtr>) }, typeof(ReferenceHelpers).Module);
var il = dyn.GetILGenerator();
il.DeclareLocal(typeof(object), true);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Call, typeof(Action<IntPtr>).GetMethod("Invoke"));
il.Emit(OpCodes.Ret);
GetPinnedPtr = (Action<object, Action<IntPtr>>)dyn.CreateDelegate(typeof(Action<object, Action<IntPtr>>));
}
}
This creates a dynamic method that first pins the object (so its storage doesn't move in the managed heap), then executes a delegate that receives its address. During the execution of the delegate, the object is still pinned and thus safe to be manipulated via the pointer:
object o = new object();
ReferenceHelpers.GetPinnedPtr(o, ptr => Console.WriteLine(Marshal.ReadIntPtr(ptr) == typeof(object).TypeHandle.Value)); //the first pointer in the managed object header in .NET points to its run-time type info
This is the easiest way to pin an object, since GCHandle requires the type to be blittable in order to pin it. It has the advantage of not using implementation details, undocumented keywords and memory hacking.
Table names in MySQL are file system entries, so they are case insensitive if the underlying file system is.
Translate all characters into their hex-entity equivalents. In this case, Null
would be converted into E;KC;C;
I don't think you have what you need with:
0 0 */3 * * ## <<< WARNING!!! CAUSES UNEVEN INTERVALS AT END OF MONTH!!
Unfortunately, the */3 is setting the interval on every n day of the month and not every n days. See: explanation here. At the end of the month there is recurring issue guaranteed.
1st at 2019-02-01 00:00:00
then at 2019-02-04 00:00:00 << 3 days, etc. OK
then at 2019-02-07 00:00:00
...
then at 2019-02-25 00:00:00
then at 2019-01-28 00:00:00
then at 2019-03-01 00:00:00 << 1 day WRONG
then at 2019-03-04 00:00:00
...
According to this article, you need to add some modulo math to the command being executed to get a TRUE "every N days". For example:
0 0 * * * bash -c '(( $(date +\%s) / 86400 \% 3 == 0 )) && runmyjob.sh
In this example, the job will be checked daily at 12:00 AM, but will only execute when the number of days since 01-01-1970 modulo 3 is 0.
If you want it to be every 3 days from a specific date, use the following format:
0 0 * * * bash -c '(( $(date +\%s -d "2019-01-01") / 86400 \% 3 == 0 )) && runmyjob.sh
Using with FILEPATH
option might work:
set(CMAKE_CXX_COMPILER:FILEPATH C:/MinGW/bin/gcc.exe)
This examples shows calling a method
class ParentPage extends StatefulWidget {
@override
_ParentPageState createState() => _ParentPageState();
}
class _ParentPageState extends State<ParentPage> {
final GlobalKey<ChildPageState> _key = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Parent")),
body: Center(
child: Column(
children: <Widget>[
Expanded(
child: Container(
color: Colors.grey,
width: double.infinity,
alignment: Alignment.center,
child: RaisedButton(
child: Text("Call method in child"),
onPressed: () => _key.currentState.methodInChild(), // calls method in child
),
),
),
Text("Above = Parent\nBelow = Child"),
Expanded(
child: ChildPage(
key: _key,
function: methodInParent,
),
),
],
),
),
);
}
methodInParent() => Fluttertoast.showToast(msg: "Method called in parent", gravity: ToastGravity.CENTER);
}
class ChildPage extends StatefulWidget {
final Function function;
ChildPage({Key key, this.function}) : super(key: key);
@override
ChildPageState createState() => ChildPageState();
}
class ChildPageState extends State<ChildPage> {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.teal,
width: double.infinity,
alignment: Alignment.center,
child: RaisedButton(
child: Text("Call method in parent"),
onPressed: () => widget.function(), // calls method in parent
),
);
}
methodInChild() => Fluttertoast.showToast(msg: "Method called in child");
}
`
@Component({
selector: 'app-component',
template: `
<button type="button" (click)="modal.show()">test</button>
<app-modal #modal>
<div class="app-modal-header">
header
</div>
<div class="app-modal-body">
Whatever content you like, form fields, anything
</div>
<div class="app-modal-footer">
<button type="button" class="btn btn-default" (click)="modal.hide()">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</app-modal>
`
})
export class AppComponent {
}
@Component({
selector: 'app-modal',
template: `
<div (click)="onContainerClicked($event)" class="modal fade" tabindex="-1" [ngClass]="{'in': visibleAnimate}"
[ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<ng-content select=".app-modal-header"></ng-content>
</div>
<div class="modal-body">
<ng-content select=".app-modal-body"></ng-content>
</div>
<div class="modal-footer">
<ng-content select=".app-modal-footer"></ng-content>
</div>
</div>
</div>
</div>
`
})
export class ModalComponent {
public visible = false;
public visibleAnimate = false;
public show(): void {
this.visible = true;
setTimeout(() => this.visibleAnimate = true, 100);
}
public hide(): void {
this.visibleAnimate = false;
setTimeout(() => this.visible = false, 300);
}
public onContainerClicked(event: MouseEvent): void {
if ((<HTMLElement>event.target).classList.contains('modal')) {
this.hide();
}
}
}
To show the backdrop, you'll need something like this CSS:
.modal {
background: rgba(0,0,0,0.6);
}
The example now allows for multiple modals at the same time. (see the onContainerClicked()
method).
For Bootstrap 4 css users, you need to make 1 minor change (because a css class name was updated from Bootstrap 3). This line:
[ngClass]="{'in': visibleAnimate}"
should be changed to:
[ngClass]="{'show': visibleAnimate}"
To demonstrate, here is a plunkr
You need to indicate the groupId, the artifactId and the version for your artifact:
mvn install:install-file \
-DgroupId=javax.transaction \
-DartifactId=jta \
-Dpackaging=jar \
-Dversion=1.0.1B \
-Dfile=jta-1.0.1B.jar \
-DgeneratePom=true
Been doing it for years. Never run into a problem.
I usually set up my DB's to have one table that contains all the keys and the modified dates and such. Haven't run into a problem of duplicate keys ever.
The only drawback that it has is when you are writing some queries to find some information quickly you are doing a lot of copying and pasting of the keys. You don't have the short easy to remember ids anymore.
Solved it -- Component is part of the declaration of 2 modules
And Run the command ionic cordova build android --prod --release its Working in my app
Do you mean finding a stack trace of the thrown exception location? That's either Debug/Exceptions, or better - Ctrl-Alt-E. Set filters for the exceptions you want to break on.
There's even a way to reconstruct the thrower stack after the exception was caught, but it's really unpleasant. Much, much easier to set a break on the throw.
You can run nodejs using pm2 if you want to manage each microservice means and run it. Node will be running in a port right just configure that port in nginx(/etc/nginx/sites-enabled/domain.com)
server{
listen 80;
server_name domain.com www.domain.com;
location / {
return 403;
}
location /url {
proxy_pass http://localhost:51967/info;
}
}
Check whether localhost is running or not by using ping.
And
Create one single Node.js server which handles all Node.js requests. This reads the requested files and evals their contents. So the files are interpreted on each request, but the server logic is much simpler.
This is best and as you said easier too
If this is happening to you with Android 6 and compile target >= 23, don't forget that we are now using runtime permissions. So giving permissions in the manifest is not enough anymore.
here is my implementation
that if you want to disable the swipe animation you can you use the swipeListener left and right and still want the scroll by finger but without animation
1-Override Viewpager
method onInterceptTouchEvent
and onTouchEvent
2- create your own GestureDetector
3- detect the swipe gesture and use the setCurrentItem(item, false)
ViewPager
public class ViewPagerNoSwipe extends ViewPager {
private final GestureDetector gestureDetector;
private OnSwipeListener mOnSwipeListener;
public void setOnSwipeListener(OnSwipeListener onSwipeListener) {
mOnSwipeListener = onSwipeListener;
}
public ViewPagerNoSwipe(@NonNull Context context) {
super(context);
gestureDetector = new GestureDetector(context, new GestureListener());
}
public ViewPagerNoSwipe(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
gestureDetector = new GestureDetector(context, new GestureListener());
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return true;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
gestureDetector.onTouchEvent(ev);
return false;
}
public class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
if(mOnSwipeListener!=null)
mOnSwipeListener.onSwipeRight();
} else {
if(mOnSwipeListener!=null)
mOnSwipeListener.onSwipeLeft();
}
result = true;
}
} else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
if(mOnSwipeListener!=null)
mOnSwipeListener.onSwipeBottom();
} else {
if(mOnSwipeListener!=null)
mOnSwipeListener.onSwipeTop();
}
result = true;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public interface OnSwipeListener {
void onSwipeRight();
void onSwipeLeft();
void onSwipeTop();
void onSwipeBottom();
}
}
the when you are set up the ViewPager set the swipeListener
postsPager.setOnSwipeListener(new ViewPagerNoSwipe.OnSwipeListener() {
@Override
public void onSwipeRight() {
postsPager.setCurrentItem(postsPager.getCurrentItem() + 1,false);
}
@Override
public void onSwipeLeft() {
postsPager.setCurrentItem(postsPager.getCurrentItem() - 1, false);
}
...
}
const loop (fn, times) => {
if (!times) { return }
fn()
loop(fn, times - 1)
}
loop(something, 3)
You can also find the use of lambda expressions in writing generic codes to act on your methods.
For example: Generic function to calculate the time taken by a method call. (i.e. Action
in here)
public static long Measure(Action action)
{
Stopwatch sw = new Stopwatch();
sw.Start();
action();
sw.Stop();
return sw.ElapsedMilliseconds;
}
And you can call the above method using the lambda expression as follows,
var timeTaken = Measure(() => yourMethod(param));
Expression allows you to get return value from your method and out param as well
var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));
This should help you: W3Schools - Labels
<form>
<label for="male">Male</label>
<input type="radio" name="sex" id="male" />
<br />
<label for="female">Female</label>
<input type="radio" name="sex" id="female" />
</form>
Using @EmbeddableId for the PK entity has solved my issue.
@Entity
@Table(name="SAMPLE")
public class SampleEntity implements Serializable{
private static final long serialVersionUID = 1L;
@EmbeddedId
SampleEntityPK id;
}
I've got the error while using Chrome as client and golang gorilla websocket as server under nginx proxy
And sending just some "ping" message from server to client every x second resolved problem
Honestly, with 8 objects max and 8 properties max per object, your best bet is to just traverse each object and make the comparisons directly. It'll be fast and it'll be easy.
If you're going to be using these types of comparisons often, then I agree with Jason about JSON serialization...but otherwise there's no need to slow down your app with a new library or JSON serialization code.
I think what you are looking for is:
startDate.setDate(startDate.getDate() + 1);
Also, you can have a look at Moment.js
A javascript date library for parsing, validating, manipulating, and formatting dates.
You could use cast
(as int) after replacing NaN
with 0
,
data_df = df.withColumn("Plays", df.call_time.cast('float'))
The list.append
function does not return any value(but None
), it just adds the value to the list you are using to call that method.
In the first loop round you will assign None
(because the no-return of append
) to a
, then in the second round it will try to call a.append
, as a is None
it will raise the Exception you are seeing
You just need to change it to:
a=[]
for i in range(5):
a.append(i)
print(a)
# [0, 1, 2, 3, 4]
list.append
is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).
If you would like to create a new list based in one list without destroying or mutating it you can do something like this:
a=['a', 'b', 'c']
result = a + ['d']
print result
# ['a', 'b', 'c', 'd']
print a
# ['a', 'b', 'c']
As a corollary only, you can mimic the append
method by doing the following:
a=['a', 'b', 'c']
a = a + ['d']
print a
# ['a', 'b', 'c', 'd']
I do not have factual evidence to prove this but I already ran into this issue. It seems that triggering a click() event on an <a>
tag doesn't seem to behave the same way you would expect with say, a input button.
The workaround I employed was to set the location.href property on the window which causes the browser to load the request resource like so:
$(document).ready(function()
{
var href = $('.cssbuttongo').attr('href');
window.location.href = href; //causes the browser to refresh and load the requested url
});
});
Edit:
I would make a js fiddle but the nature of the question intermixed with how jsfiddle uses an iframe to render code makes that a no go.
How about this approach, which splits the problem into two parts:
textarea
, which turns red when it hits zero but still allows the user to type.textarea
is greater than 160.My textarea
has an id of Message
, and the span
in which I display the number of remaining characters has an id of counter
. The css class of error
gets applied when the number of remaining characters hits zero.
var charactersAllowed = 160;
$(document).ready(function () {
$('#Message').keyup(function () {
var left = charactersAllowed - $(this).val().length;
if (left < 0) {
$('#counter').addClass('error');
left = 0;
}
else {
$('#counter').removeClass('error');
}
$('#counter').text('Characters left: ' + left);
});
});
who still facing the problem on linux and didnt find it on trash try this solution
https://github.com/Microsoft/vscode/issues/32078#issuecomment-434393058
find / -name "delete_file_name"
my rule of thumb is:
rebase
for branches with the same name,merge
otherwise.
examples for same names would be master
, origin/master
and otherRemote/master
.
if develop
exists only in the local repository, and it is always based on a recent origin/master
commit, you should call it master
, and work there directly. it simplifies your life, and presents things as they actually are: you are directly developing on the master
branch.
if develop
is shared, it should not be rebased on master
, just merged back into it with --no-ff
. you are developing on develop
. master
and develop
have different names, because we want them to be different things, and stay separate. do not make them same with rebase
.
This snippet is straight from Stroustrup's The C++ Programming Language (4th Edition), §40.7; it requires C++11:
#include <functional>
#include <random>
class Rand_double
{
public:
Rand_double(double low, double high)
:r(std::bind(std::uniform_real_distribution<>(low,high),std::default_random_engine())){}
double operator()(){ return r(); }
private:
std::function<double()> r;
};
#include <iostream>
int main() {
// create the random number generator:
Rand_double rd{0,0.5};
// print 10 random number between 0 and 0.5
for (int i=0;i<10;++i){
std::cout << rd() << ' ';
}
return 0;
}
saving in any format is very much possible. Check following- http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
2ndly , What exactly you are expecting the save dialog to work , it works like that, Opening a doc file is very much possible- http://srikanthtechnologies.com/blog/openworddoc.html
I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent]
from decorator.
import {myDirective} from './myDirective';
Even my Intellisense in Pycharm was not working for modules like time Problem in my system was no Interpreter was selected Go to File --> Settings... (Ctrl+Alt+S) Open Project Interpreter
Project Interpreter In my case was selected. I selected the available python interpreter. If not available you can add a new interpreter.
try this to get the box-shadow under your full control.
<html>
<head>
<style>
div {
width:300px;
height:100px;
background-color:yellow;
box-shadow: 0 10px black inset,0 -10px red inset, -10px 0 blue inset, 10px 0 green inset;
}
</style>
</head>
<body>
<div>
</div>
</body>
</html>
this would apply to outer box-shadow as well.
Sorry for being late, I have tried all above answers but none of them is giving me correct value, After doing the lot of R&D I have found a simple way that gives me exact value.
Declare this method in your class
private String hmacSha(String KEY, String VALUE, String SHA_TYPE) {
try {
SecretKeySpec signingKey = new SecretKeySpec(KEY.getBytes("UTF-8"), SHA_TYPE);
Mac mac = Mac.getInstance(SHA_TYPE);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(VALUE.getBytes("UTF-8"));
byte[] hexArray = {(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'};
byte[] hexChars = new byte[rawHmac.length * 2];
for ( int j = 0; j < rawHmac.length; j++ ) {
int v = rawHmac[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
Use this like
Log.e("TAG", "onCreate: "+hmacSha("key","text","HmacSHA256"));
Verification
1.Android studio output 2. Online HMAC generator Output(Visit here for Online Genrator)
Update for Django 1.10+:
is_authenticated
is now an attribute in Django 1.10.
The method was removed in Django 2.0.
For Django 1.9 and older:
is_authenticated
is a function. You should call it like
if request.user.is_authenticated():
# do something if the user is authenticated
As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:
{% if user.is_authenticated %}
However, in Python code, it is indeed a method in the User
class.
Here's a Perl one-liner that will print out a list of installed modules:
perl -MExtUtils::Installed -MData::Dumper -e 'my ($inst) = ExtUtils::Installed->new(); print Dumper($inst->modules());'
Just make sure you have Data::Dumper installed.
Here is an approach, based on MSquare's nice idea for detecting a long press of a button, that has an additional feature: not only is an operation performed in response to a long press, but the operation is repeated until a MotionEvent.ACTION_UP message is received. In this case, the long-press and short-press actions are the same, but they could be different.
Note that, as others have reported, removing the callback in response to a MotionEvent.ACTION_MOVE message prevented the callback from ever getting executed since I could not keep my finger still enough. I got around that problem by ignoring that message.
private void setIncrementButton() {
final Button btn = (Button) findViewById(R.id.btn);
final Runnable repeater = new Runnable() {
@Override
public void run() {
increment();
final int milliseconds = 100;
btn.postDelayed(this, milliseconds);
}
};
btn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
increment();
v.postDelayed(repeater, ViewConfiguration.getLongPressTimeout());
} else if (e.getAction() == MotionEvent.ACTION_UP) {
v.removeCallbacks(repeater);
}
return true;
}
});
}
private void increment() {
Log.v("Long Press Example", "TODO: implement increment operation");
}
This was the top result when googling "cannot open source file" so I figured I would share what my issue was since I had already included the correct path.
I'm not sure about other IDEs or compilers, but least for Visual Studio, make sure there isn't a space in your list of include directories. I had put a space between the ;
of the last entry and the beginning of my new entry which then caused Visual Studio to disregard my inclusion.
Just use this this decrypter to decrypt your locally cached username & password.
By default, TortoiseSVN stores your cached credentials inside files in the %APPDATA%\Subversion\auth\svn.simple directory. The passwords are encrypted using the Windows Data Protection API, with a key tied to your user account. This tool reads the files and uses the API to decrypt your passwords
You can also use the [Required]
data annotation attribute to solve this:
public class Foo
{
public string FooId { get; set; }
public Boo Boo { get; set; }
}
public class Boo
{
public string BooId { get; set; }
[Required]
public Foo Foo {get; set; }
}
Foo
is required for Boo
.
I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:
curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"
The basic idea is that each part (split by string in boundary
with --
) has it's own headers (Content-Type
in the second part, for example.) The FormData
object manages all this for you, so it's a better way to accomplish our goals.
This translates to fetch API like this:
const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')
fetch('http://localhost:5001/api/v0/add', {
method: 'POST',
body: formData
})
.then(r => r.json())
.then(data => {
console.log(data)
})
Need to convert it in base64.
JS have btoa() function for it.
For example:
var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
document.body.appendChild(img);
But i think what your binary data in pastebin is invalid - the jpeg data must be ended on 'ffd9'.
Update:
Need to write simple hex to base64 converter:
function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}
And use it:
img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');
See working example with your hex data on jsfiddle
In my case I was trying to install Flask. I wanted to run pip install Flask command. But when I open command prompt it I goes to C:\Users[user]>. If you give here it will say pip is not recognized. I did below steps
On your desktop right click Computer and select Properties
Select Advanced Systems Settings
In popup which you see select Advanced tab and then click Environment Variables
In popup double click PATH and from popup copy variable value for variable name PATH and paste the variable value in notepad or so and look for an entry for Python.
In my case it was C:\Users\[user]\AppData\Local\Programs\Python\Python36-32
Now in my command prompt i moved to above location and gave pip install Flask
Here's my efficient approach for displaying 2-D integer array using a StringBuilder array.
public static void printMatrix(int[][] arr) {
if (null == arr || arr.length == 0) {
// empty or null matrix
return;
}
int idx = -1;
StringBuilder[] sbArr = new StringBuilder[arr.length];
for (int[] row : arr) {
sbArr[++idx] = new StringBuilder("(\t");
for (int elem : row) {
sbArr[idx].append(elem + "\t");
}
sbArr[idx].append(")");
}
for (int i = 0; i < sbArr.length; i++) {
System.out.println(sbArr[i]);
}
System.out.println("\nDONE\n");
}
My answer won't probably be useful to the writer of this question (I am 8 months late so not the right timing I guess) but I think it will probably be useful for many other developers that might come across this answer.
Today, I just released (in the name of my company) an HTML to POJO complete framework that you can use to map HTML to any POJO class with simply some annotations. The library itself is quite handy and features many other things all the while being very pluggable. You can have a look to it right here : https://github.com/whimtrip/jwht-htmltopojo
Imagine we need to parse the following html page :
<html>
<head>
<title>A Simple HTML Document</title>
</head>
<body>
<div class="restaurant">
<h1>A la bonne Franquette</h1>
<p>French cuisine restaurant for gourmet of fellow french people</p>
<div class="location">
<p>in <span>London</span></p>
</div>
<p>Restaurant n*18,190. Ranked 113 out of 1,550 restaurants</p>
<div class="meals">
<div class="meal">
<p>Veal Cutlet</p>
<p rating-color="green">4.5/5 stars</p>
<p>Chef Mr. Frenchie</p>
</div>
<div class="meal">
<p>Ratatouille</p>
<p rating-color="orange">3.6/5 stars</p>
<p>Chef Mr. Frenchie and Mme. French-Cuisine</p>
</div>
</div>
</div>
</body>
</html>
Let's create the POJOs we want to map it to :
public class Restaurant {
@Selector( value = "div.restaurant > h1")
private String name;
@Selector( value = "div.restaurant > p:nth-child(2)")
private String description;
@Selector( value = "div.restaurant > div:nth-child(3) > p > span")
private String location;
@Selector(
value = "div.restaurant > p:nth-child(4)"
format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
indexForRegexPattern = 1,
useDeserializer = true,
deserializer = ReplacerDeserializer.class,
preConvert = true,
postConvert = false
)
// so that the number becomes a valid number as they are shown in this format : 18,190
@ReplaceWith(value = ",", with = "")
private Long id;
@Selector(
value = "div.restaurant > p:nth-child(4)"
format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
// This time, we want the second regex group and not the first one anymore
indexForRegexPattern = 2,
useDeserializer = true,
deserializer = ReplacerDeserializer.class,
preConvert = true,
postConvert = false
)
// so that the number becomes a valid number as they are shown in this format : 18,190
@ReplaceWith(value = ",", with = "")
private Integer rank;
@Selector(value = ".meal")
private List<Meal> meals;
// getters and setters
}
And now the Meal
class as well :
public class Meal {
@Selector(value = "p:nth-child(1)")
private String name;
@Selector(
value = "p:nth-child(2)",
format = "^([0-9.]+)\/5 stars$",
indexForRegexPattern = 1
)
private Float stars;
@Selector(
value = "p:nth-child(2)",
// rating-color custom attribute can be used as well
attr = "rating-color"
)
private String ratingColor;
@Selector(
value = "p:nth-child(3)"
)
private String chefs;
// getters and setters.
}
We provided some more explanations on the above code on our github page.
For the moment, let's see how to scrap this.
private static final String MY_HTML_FILE = "my-html-file.html";
public static void main(String[] args) {
HtmlToPojoEngine htmlToPojoEngine = HtmlToPojoEngine.create();
HtmlAdapter<Restaurant> adapter = htmlToPojoEngine.adapter(Restaurant.class);
// If they were several restaurants in the same page,
// you would need to create a parent POJO containing
// a list of Restaurants as shown with the meals here
Restaurant restaurant = adapter.fromHtml(getHtmlBody());
// That's it, do some magic now!
}
private static String getHtmlBody() throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(MY_HTML_FILE));
return new String(encoded, Charset.forName("UTF-8"));
}
Another short example can be found here
Hope this will help someone out there!
There are two important points to the Swift 2 error handling model: exhaustiveness and resiliency. Together, they boil down to your do
/catch
statement needing to catch every possible error, not just the ones you know you can throw.
Notice that you don't declare what types of errors a function can throw, only whether it throws at all. It's a zero-one-infinity sort of problem: as someone defining a function for others (including your future self) to use, you don't want to have to make every client of your function adapt to every change in the implementation of your function, including what errors it can throw. You want code that calls your function to be resilient to such change.
Because your function can't say what kind of errors it throws (or might throw in the future), the catch
blocks that catch it errors don't know what types of errors it might throw. So, in addition to handling the error types you know about, you need to handle the ones you don't with a universal catch
statement -- that way if your function changes the set of errors it throws in the future, callers will still catch its errors.
do {
let sandwich = try makeMeSandwich(kitchen)
print("i eat it \(sandwich)")
} catch SandwichError.NotMe {
print("Not me error")
} catch SandwichError.DoItYourself {
print("do it error")
} catch let error {
print(error.localizedDescription)
}
But let's not stop there. Think about this resilience idea some more. The way you've designed your sandwich, you have to describe errors in every place where you use them. That means that whenever you change the set of error cases, you have to change every place that uses them... not very fun.
The idea behind defining your own error types is to let you centralize things like that. You could define a description
method for your errors:
extension SandwichError: CustomStringConvertible {
var description: String {
switch self {
case NotMe: return "Not me error"
case DoItYourself: return "Try sudo"
}
}
}
And then your error handling code can ask your error type to describe itself -- now every place where you handle errors can use the same code, and handle possible future error cases, too.
do {
let sandwich = try makeMeSandwich(kitchen)
print("i eat it \(sandwich)")
} catch let error as SandwichError {
print(error.description)
} catch {
print("i dunno")
}
This also paves the way for error types (or extensions on them) to support other ways of reporting errors -- for example, you could have an extension on your error type that knows how to present a UIAlertController
for reporting the error to an iOS user.
Or simply:
view.getLayoutParams().width = 400;
view.requestLayout();
I found the that either IE or Chrome choked on most of these, or they required external libraries. I just wanted to play an MP3, and I found the page http://www.w3schools.com/html/html_sounds.asp very helpful.
<audio controls>
<source src="horse.mp3" type="audio/mpeg">
<embed height="50" width="100" src="horse.mp3">
</audio>
Worked for me in the browsers I tried, but I didn't have some of the old ones around at this time.
For a File
git add -u
git reset -- main/dontcheckmein.txt
For a folder
git add -u
git reset -- main/*
Another option now may be HTML5 text to speech, which is in Chrome 33+ and many others.
Here is a sample:
var msg = new SpeechSynthesisUtterance('Hello World');
window.speechSynthesis.speak(msg);
With this, perhaps you do not need to use a web service at all.
Variation of the code by Bijaya Bidari that is accepted by Java 8 without warnings in regard with overridable method calls in constructor:
public class Graph extends JFrame {
JPanel jp;
public Graph() {
super("Simple Drawing");
super.setSize(300, 300);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
jp = new GPanel();
super.add(jp);
}
public static void main(String[] args) {
Graph g1 = new Graph();
g1.setVisible(true);
}
class GPanel extends JPanel {
public GPanel() {
super.setPreferredSize(new Dimension(300, 300));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//rectangle originated at 10,10 and end at 240,240
g.drawRect(10, 10, 240, 240);
//filled Rectangle with rounded corners.
g.fillRoundRect(50, 50, 100, 100, 80, 80);
}
}
}
The following solution was born when I've noticed a $break parameter of wordwrap function:
string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )
Here is the solution:
/**
* Truncates the given string at the specified length.
*
* @param string $str The input string.
* @param int $width The number of chars at which the string will be truncated.
* @return string
*/
function truncate($str, $width) {
return strtok(wordwrap($str, $width, "...\n"), "\n");
}
Example #1.
print truncate("This is very long string with many chars.", 25);
The above example will output:
This is very long string...
Example #2.
print truncate("This is short string.", 25);
The above example will output:
This is short string.
RecyclerView
is, by default, unaware of your dataset changes.
This means that whenever you make a deletion/addition on your data list, those changes won't be reflected to your RecyclerView directly. (i.e. you remove the item at index 5, but the 6th element remains in your recycler view).
RecyclerView
exposes some methods for you to communicate your dataset changes, reflecting those changes directly on your list items.
The standard Android APIs allow you to bind the process of data removal (for the purpose of the question) with the process of View removal.
The methods we talked about are:
notifyItemChanged(index: Int)
notifyItemInserted(index: Int)
notifyItemRemoved(index: Int)
notifyItemRangeChanged(startPosition: Int, itemCount: Int)
notifyItemRangeInserted(startPosition: Int, itemCount: Int)
notifyItemRangeRemoved(startPosition: Int, itemCount: Int)
If you don't properly specify what happens on each addition, change or removal of items, RecyclerView
children are animated unresponsively because of a lack of information about how to move the different views around the list.
Instead, the following code will precisely play the animation, just on the child that is being removed (And as a side note, it fixed any IndexOutOfBoundException
s, marked by the stacktrace as "data inconsistency").
void remove(position: Int) {
dataset.removeAt(position)
notifyItemChanged(position)
notifyItemRangeRemoved(position, 1)
}
Under the hood, if we look into RecyclerView
we can find documentation explaining that the second parameter we pass to notifyItemRangeRemoved
is the number of items that are removed from the dataset, not the total number of items (As wrongly reported in some others information sources).
/**
* Notify any registered observers that the <code>itemCount</code> items previously
* located at <code>positionStart</code> have been removed from the data set. The items
* previously located at and after <code>positionStart + itemCount</code> may now be found
* at <code>oldPosition - itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the data
* set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Previous position of the first item that was removed
* @param itemCount Number of items removed from the data set
*/
public final void notifyItemRangeRemoved(int positionStart, int itemCount) {
mObservable.notifyItemRangeRemoved(positionStart, itemCount);
}
Do not use any of those functions. That's my personal view. They are counterintuitive, error-prone and they feel really verbose and unnecessary. Let a library like FastAdapter, Epoxy or Groupie take care of this business, or use an observable recycler view with data binding.
This is easy way to remove default null values from arraylist
tourists.removeAll(Arrays.asList(null));
otherwise String value "null" remove from arraylist
tourists.removeAll(Arrays.asList("null"));
Answering the headline of the question (what attracted people here) and ignoring that the example used anonymous types....
This solution will also work for non-anonymous types. It should not be needed for anonymous types.
Helper class:
/// <summary>
/// Allow IEqualityComparer to be configured within a lambda expression.
/// From https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer
/// </summary>
/// <typeparam name="T"></typeparam>
public class LambdaEqualityComparer<T> : IEqualityComparer<T>
{
readonly Func<T, T, bool> _comparer;
readonly Func<T, int> _hash;
/// <summary>
/// Simplest constructor, provide a conversion to string for type T to use as a comparison key (GetHashCode() and Equals().
/// https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer, user "orip"
/// </summary>
/// <param name="toString"></param>
public LambdaEqualityComparer(Func<T, string> toString)
: this((t1, t2) => toString(t1) == toString(t2), t => toString(t).GetHashCode())
{
}
/// <summary>
/// Constructor. Assumes T.GetHashCode() is accurate.
/// </summary>
/// <param name="comparer"></param>
public LambdaEqualityComparer(Func<T, T, bool> comparer)
: this(comparer, t => t.GetHashCode())
{
}
/// <summary>
/// Constructor, provide a equality comparer and a hash.
/// </summary>
/// <param name="comparer"></param>
/// <param name="hash"></param>
public LambdaEqualityComparer(Func<T, T, bool> comparer, Func<T, int> hash)
{
_comparer = comparer;
_hash = hash;
}
public bool Equals(T x, T y)
{
return _comparer(x, y);
}
public int GetHashCode(T obj)
{
return _hash(obj);
}
}
Simplest usage:
List<Product> products = duplicatedProducts.Distinct(
new LambdaEqualityComparer<Product>(p =>
String.Format("{0}{1}{2}{3}",
p.ProductId,
p.ProductName,
p.CategoryId,
p.CategoryName))
).ToList();
The simplest (but not that efficient) usage is to map to a string representation so that custom hashing is avoided. Equal strings already have equal hash codes.
Reference:
Wrap a delegate in an IEqualityComparer
d1G
= delete to top including current line (vi)
I think that in this question is missing one important information.
How many records will you insert?
you need the libblas and liblapack dev packages if you are using Ubuntu.
aptitude install libblas-dev liblapack-dev
pip install scipy
Perhaps the best two browser techs for this are Canvas, with Flash as a back up.
We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.
With jSignature ( http://willowsystems.github.com/jSignature/ ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.
The caller-saved / callee-saved terminology is based on a pretty braindead inefficient model of programming where callers actually do save/restore all the call-clobbered registers (instead of keeping long-term-useful values elsewhere), and callees actually do save/restore all the call-preserved registers (instead of just not using some or any of them).
Or you have to understand that "caller-saved" means "saved somehow if you want the value later".
In reality, efficient code lets values get destroyed when they're no longer needed. Compilers typically make functions that save a few call-preserved registers at the start of a function (and restore them at the end). Inside the function, they use those regs for values that need to survive across function calls.
I prefer "call-preserved" vs. "call-clobbered", which are unambiguous and self-describing once you've heard of the basic concept, and don't require any serious mental gymnastics to think about from the caller's perspective or the callee's perspective. (Both terms are from the same perspective).
Plus, these terms differ by more than one letter.
The terms volatile / non-volatile are pretty good, by analogy with storage which loses its value on power-loss or not, (like DRAM vs. Flash). But the C volatile
keyword has a totally different technical meaning, so that's a downside to "(non)-volatile" when describing C calling conventions.
From the callee's perspective, your function can freely overwrite (aka clobber) these registers without saving/restoring.
From a caller's perspective, call foo
destroys (aka clobbers) all the call-clobbered registers, or at least you have to assume it does.
You can write private helper functions that have a custom calling convention, e.g. you know they don't modify a certain register. But if all you know (or want to assume or depend on) is that the target function follows the normal calling convention, then you have to treat a function call as if it does destroy all the call-clobbered registers. That's literally what the name come from: a call clobbers those registers.
Some compilers that do inter-procedural optimization can also create internal-use-only definitions of functions that don't follow the ABI, using a custom calling convention.
From a callee's perspective, these registers can't be modified unless you save the original value somewhere so you can restore it before returning. Or for registers like the stack pointer (which is almost always call-preserved), you can subtract a known offset and add it back again before returning, instead of actually saving the old value anywhere. i.e. you can restore it by dead reckoning, unless you allocate a runtime-variable amount of stack space. Then typically you restore the stack pointer from another register.
A function that can benefit from using a lot of registers can save/restore some call-preserved registers just so it can use them as more temporaries, even if it doesn't make any function calls. Normally you'd only do this after running out of call-clobbered registers to use, because save/restore typically costs a push/pop at the start/end of the function. (Or if your function has multiple exit paths, a pop
in each of them.)
The name "caller-saved" is misleading: you don't have to specially save/restore them. Normally you arrange your code to have values that need to survive a function call in call-preserved registers, or somewhere on the stack, or somewhere else that you can reload from. It's normal to let a call
destroy temporary values.
See for example What registers are preserved through a linux x86-64 function call for the x86-64 System V ABI.
Also, arg-passing registers are always call-clobbered in all function-calling conventions I'm aware of. See Are rdi and rsi caller saved or callee saved registers?
But system-call calling conventions typically make all the registers except the return value call-preserved. (Usually including even condition-codes / flags.) See What are the calling conventions for UNIX & Linux system calls on i386 and x86-64
import psutil
pid_list=psutil.get_pid_list()
print pid_list
p = psutil.Process(1052)
print p.name
for i in pid_list:
p = psutil.Process(i)
p_name=p.name
print str(i)+" "+str(p.name)
if p_name=="PerfExp.exe":
print "*"*20+" mam ho "+"*"*20
p.kill()
If you only want to commit all the changes in one commit as if you typed yourself, --squash will do too
$ git merge --squash v1.0
$ git commit
I have fixed the similar issue by passing associative array as the first argument inside Builder::with
method.
Imagine you want to include child relations by some dynamic parameters but don't want to filter parent results.
Model.php
public function child ()
{
return $this->hasMany(ChildModel::class);
}
Then, in other place, when your logic is placed you can do something like filtering relation by HasMany
class. For example (very similar to my case):
$search = 'Some search string';
$result = Model::query()->with(
[
'child' => function (HasMany $query) use ($search) {
$query->where('name', 'like', "%{$search}%");
}
]
);
Then you will filter all the child results but parent models will not filter. Thank you for attention.