I sometimes use NULLIF like so...
IF NULLIF(@PreviousStartDate, '') IS NULL
There's probably no reason it's better than the way suggested by @Oded and @bluefeet, just stylistic preference.
@danihp's method is really cool but my tired old brain wouldn't go to COALESCE when I'm thinking is null or empty :-)
Try this instead:
var responseObject = proxy.CallService(new RequestObject
{
Data = "misc. data",
Guid = new Guid.NewGuid()
});
This will generate a 'real' Guid value. When you new a reference type, it will give you the default value (which in this case, is all zeroes for a Guid).
When you create a new Guid, it will initialize it to all zeroes, which is the default value for Guid. It's basically the same as creating a "new" int (which is a value type but you can do this anyways):
Guid g1; // g1 is 00000000-0000-0000-0000-000000000000
Guid g2 = new Guid(); // g2 is 00000000-0000-0000-0000-000000000000
Guid g3 = default(Guid); // g3 is 00000000-0000-0000-0000-000000000000
Guid g4 = Guid.NewGuid(); // g4 is not all zeroes
Compare this to doing the same thing with an int:
int i1; // i1 is 0
int i2 = new int(); // i2 is 0
int i3 = default(int); // i3 is 0
When render_template() function is used it tries to search for template in the folder called templates and it throws error jinja2.exceptions.TemplateNotFound when :
To solve the problem :
overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.
overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.
overflow: hidden;
would remove both scrollbars
I have google search many ways to import csv to mysql, include " load data infile ", use mysql workbench, etc.
when I use mysql workbench import button, first you need to create the empty table on your own, set each column type on your own. Note: you have to add ID column at the end as primary key and not null and auto_increment, otherwise, the import button will not visible at later. However, when I start load CSV file, nothing loaded, seems like a bug. I give up.
Lucky, the best easy way so far I found is to use Oracle's mysql for excel. you can download it from here mysql for excel
This is what you are going to do: open csv file in excel, at Data tab, find mysql for excel button
select all data, click export to mysql. Note to set a ID column as primary key.
when finished, go to mysql workbench to alter the table, such as currency type should be decimal(19,4) for large amount decimal(10,2) for regular use. other field type may be set to varchar(255).
Another option would be file_get_contents()
:
// $xml_str = your xml
// $url = target url
$post_data = array('xml' => $xml_str);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
You can make a list copy of the dict.Values
, then you can use the List.ForEach
lambda function for iteration, (or a foreach
loop, as suggested before).
new List<string>(myDict.Values).ForEach(str =>
{
//Use str in any other way you need here.
Console.WriteLine(str);
});
The only parameter you need right now is ?u=<YOUR_URL>
. All other data will be fetched from page or (better) from your open graph meta tags:
<meta property="og:url" content="http://www.nytimes.com/2015/02/19/arts/international/when-great-minds-dont-think-alike.html" />
<meta property="og:type" content="article" />
<meta property="og:title" content="When Great Minds Don’t Think Alike" />
<meta property="og:description" content="How much does culture influence creative thinking?" />
<meta property="og:image" content="http://static01.nyt.com/images/2015/02/19/arts/international/19iht-btnumbers19A/19iht-btnumbers19A-facebookJumbo-v2.jpg" />
You can test your page for accordance in the debugger.
I recommend HeadFirst DesignPattern. Reading the book is not enough, after assimilating the concepts you need to findout the answers for lot of questions arise in your mind and try to findout the real life applications where in these patterns can be used. I am doing the same and started asking questions even those questions look silly.
I was trying to do a similar task to get a dropdown arrow always on the right side of the table header and came up with this which seemed to work in Chrome and Firefox, but safari was telling me it was an invalid property.
background: url(http://goo.gl/P93P5Q) center right 10px no-repeat;
After doing a bit of messing around in the inspector, I came up with this cross-browser solution that works in IE8+, Chrome, Firefox, and Safari, as well as responsive designs.
background: url(http://goo.gl/P93P5Q) no-repeat 95% center;
Here is a codepen of how it looks and works. Codepen is written with SCSS - http://cdpn.io/xqGbk
The short answer is: No. The only way to post images is through the mobile app.
From the Instagram API documentation: http://instagram.com/developer/endpoints/media/
At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:
- Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
- We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.
All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.
The _id
field is always present unless you explicitly exclude it. Do so using the -
syntax:
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select('name -_id');
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
Or explicitly via an object:
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
Sorry to pile on to an old item. I found partial answers to my questions here but had to do some work so I wanted to share my results for the next person.
I ended up using the same approach as the other contributors, but with a few tweaks to fix the following
The below will give you a working solution with the above issues fixed. Note: I used a white arrow for my use case, you may need to change the color of the arrow for yours.
here's a preview:
select{
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgaWQ9IkxheWVyXzEiICAgZGF0YS1uYW1lPSJMYXllciAxIiAgIHZpZXdCb3g9IjAgMCA0Ljk1IDEwIiAgIHZlcnNpb249IjEuMSIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxIHIxMzcyNSIgICBzb2RpcG9kaTpkb2NuYW1lPSJkb3dubG9hZC5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE0MjAyIj4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgIDwvY2M6V29yaz4gICAgPC9yZGY6UkRGPiAgPC9tZXRhZGF0YT4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTkyMCIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9IjEwMjciICAgICBpZD0ibmFtZWR2aWV3NDIwMCIgICAgIHNob3dncmlkPSJmYWxzZSIgICAgIGlua3NjYXBlOnpvb209Ijg0LjMiICAgICBpbmtzY2FwZTpjeD0iMi40NzQ5OTk5IiAgICAgaW5rc2NhcGU6Y3k9IjUiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMTkyMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyNyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjEiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJMYXllcl8xIiAvPiAgPGRlZnMgICAgIGlkPSJkZWZzNDE5MCI+ICAgIDxzdHlsZSAgICAgICBpZD0ic3R5bGU0MTkyIj4uY2xzLTJ7ZmlsbDojNDQ0O308L3N0eWxlPiAgPC9kZWZzPiAgPHRpdGxlICAgICBpZD0idGl0bGU0MTk0Ij5hcnJvd3M8L3RpdGxlPiAgPHBvbHlnb24gICAgIGNsYXNzPSJjbHMtMiIgICAgIHBvaW50cz0iMy41NCA1LjMzIDIuNDggNi44MiAxLjQxIDUuMzMgMy41NCA1LjMzIiAgICAgaWQ9InBvbHlnb240MTk4IiAgICAgc3R5bGU9ImZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MSIgLz48L3N2Zz4=) no-repeat 101% 50%;
padding-right:20px;
}
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
one int;
two int;
BEGIN
one := 1;
two := 2;
RETURN one + two;
END
$$;
SELECT somefuncname();
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.
You could use the System.Web.UI.WebControls.CheckBoxList
control or use the System.Web.UI.WebControls.ListBox
control with the SelectionMode
property set to Multiple
.
Personally I would use something like mplayer with the audio pass though option eg -oac copy
If the logic for choosing the files is not trivial, I would trigger script execution on each change and then write a script to check if indeed a build is required, then triggering a build if it is.
I had this issue using Angular and SCSS. I had all my CSS nested so I decided to remove cursor: pointer;
out of it. And it worked.
Example:
.container{
.Approved{
color:green;
}
.ApprovedAndVerified{
color:black;
}
.lock_button{
font-size:35px;
display:block;
text-align:center;
}
}
.lock_button{
cursor:pointer;
}
Late to the party, but... why not just this.hasAttribute("name")
?
Refer This
I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.
On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.
I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.
I use something like this in my document.ready
var height = $(window).height();//gets height from device
var width = $(window).width(); //gets width from device
$("#container").width(width+"px");
$("#container").height(height+"px");
You could simply use
return
which does exactly the same as
return None
Your function will also return None
if execution reaches the end of the function body without hitting a return
statement. Returning nothing is the same as returning None
in Python.
You have your storyboard set up to expect an outlet called tableView
but the actual outlet name is myTableView
.
If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.
prods.Remove(prods.Single(p=>p.ID == 1));
you can't modify collection in foreach, as Vincent suggests
J(2)EE, strictly speaking, is a set of API
s (as the current top answer has it) which enable a programmer to build distributed, transactional systems. The idea was to abstract away the complicated distributed, transactional bits (which would be implemented by a Container such as WebSphere or Weblogic), leaving the programmer to develop business logic free from worries about storage mechanisms and synchronization.
In reality, it was a cobbled-together, design-by-committee mish-mash, which was pushed pretty much for the benefit of vendors like IBM, Oracle and BEA so they could sell ridicously over-complicated, over-engineered, over-useless products. Which didn't have the most basic features (such as scheduling)!
J2EE was a marketing construct.
In sql server, you can do
SELECT *
FROM table t
WHERE t.date > DATEADD(dd,90,now())
I love jtbandes answer, but since it is pretty long, I will add my own compact answer:
==
, ===
, eql?
, equal?
are 4 comparators, ie. 4 ways to compare 2 objects, in Ruby.
As, in Ruby, all comparators (and most operators) are actually method-calls, you can change, overwrite, and define the semantics of these comparing methods yourself. However, it is important to understand, when Ruby's internal language constructs use which comparator:
==
(value comparison)
Ruby uses :== everywhere to compare the values of 2 objects, eg. Hash-values:
{a: 'z'} == {a: 'Z'} # => false
{a: 1} == {a: 1.0} # => true
===
(case comparison)
Ruby uses :=== in case/when constructs. The following code snippets are logically identical:
case foo
when bar; p 'do something'
end
if bar === foo
p 'do something'
end
eql?
(Hash-key comparison)
Ruby uses :eql? (in combination with the method hash) to compare Hash-keys. In most classes :eql? is identical with :==.
Knowledge about :eql? is only important, when you want to create your own special classes:
class Equ
attr_accessor :val
alias_method :initialize, :val=
def hash() self.val % 2 end
def eql?(other) self.hash == other.hash end
end
h = {Equ.new(3) => 3, Equ.new(8) => 8, Equ.new(15) => 15} #3 entries, but 2 are :eql?
h.size # => 2
h[Equ.new(27)] # => 15
Note: The commonly used Ruby-class Set also relies on Hash-key-comparison.
equal?
(object identity comparison)
Ruby uses :equal? to check if two objects are identical. This method (of class BasicObject) is not supposed to be overwritten.
obj = obj2 = 'a'
obj.equal? obj2 # => true
obj.equal? obj.dup # => false
Regarding the freezing issue, we found this occurred when processing CSV files with at least one extremely long line.
To reproduce:
[print(x) for x in (['A' * 54790] + (['a' * 1421] * 10))]
However, it appears to have been fixed in PyCharm 4.5.4, so if you experience this, try updating your PyCharm.
$('#select option[data-id-estado="3"]').prop("selected",true).trigger("change");
or
$('#select option[value="myValue"]').prop("selected",true).trigger("change");
You're thinking too much in pure Javascript. Get rid of your listeners on those React lifecycle methods and use event.key
instead of event.keyCode
(because this is not a JS event object, it is a React SyntheticEvent). Your entire component could be as simple as this (assuming you haven't bound your methods in a constructor).
onKeyPressed(e) {
console.log(e.key);
}
render() {
let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
return (
<div
className="player"
style={{ position: "absolute" }}
onKeyDown={this.onKeyPressed}
>
<div className="light-circle">
<div className="image-wrapper">
<img src={IMG_URL+player.img} />
</div>
</div>
</div>
)
}
function do_ajax(elem, mydata, filename)
{
$.ajax({
url: filename,
context: elem,
data: mydata,
**contentType: false,
processData: false**
datatype: "html",
success: function (data, textStatus, xhr) {
elem.innerHTML = data;
}
});
}
This is by far the best post for exporting to excel from SQL:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926
To quote from user madhivanan
,
Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel
Create an Excel file named testing having the headers same as that of table columns and use these queries
1 Export data to existing EXCEL file from SQL Server table
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;',
'SELECT * FROM [SheetName$]') select * from SQLServerTable
2 Export data from Excel to new SQL Server table
select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [Sheet1$]')
3 Export data from Excel to existing SQL Server table (edited)
Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\testing.xls;HDR=YES',
'SELECT * FROM [SheetName$]')
4 If you dont want to create an EXCEL file in advance and want to export data to it, use
EXEC sp_makewebtask
@outputfile = 'd:\testing.xls',
@query = 'Select * from Database_name..SQLServerTable',
@colheaders =1,
@FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
(Now you can find the file with data in tabular format)
5 To export data to new EXCEL file with heading(column names), create the following procedure
create procedure proc_generate_excel_with_columns
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
information_schema.columns
where
table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')
--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
After creating the procedure, execute it by supplying database name, table name and file path:
EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.
Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.
To update single cells
A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?
This is the principle of how you do manage that
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
You can also add formulas to Excel using this:
update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
Exporting with column names using T-SQL
Member Mladen Prajdic also has a blog entry on how to do this here
References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this
If you get the following error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries
Then run this:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
In case some wonders how to do it using Scala (using Spark 2.0.+), here you go:
scala> df.createOrReplaceTempView("TEMP_DF")
scala> val myMax = spark.sql("SELECT MAX(x) as maxval FROM TEMP_DF").
collect()(0).getInt(0)
scala> print(myMax)
117
If your compiler supports (at least part of) C++11 you could do something like:
for (auto& t : myMap)
std::cout << t.first << " "
<< t.second.first << " "
<< t.second.second << "\n";
For C++03 I'd use std::copy
with an insertion operator instead:
typedef std::pair<string, std::pair<string, string> > T;
std::ostream &operator<<(std::ostream &os, T const &t) {
return os << t.first << " " << t.second.first << " " << t.second.second;
}
// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));
Import System.Web.Optimization on top of your razor view as follows:
@using System.Web.Optimization
In Android Studio
1. Menu -> Edit -> Select All
2. Menu -> Edit -> Copy
In Notepad
4. Menu -> Edit -> Paste
5. Menu -> Edit -> Select All
6. Menu -> Edit -> Copy
Back In Android Studio
7. Menu -> Edit -> Paste
In Java 8, it's a 1-liner via Files.find()
with an arbitrarily large depth (eg 999
) and BasicFileAttributes
of isRegularFile()
public static printFnames(String sDir) {
Files.find(Paths.get(sDir), 999, (p, bfa) -> bfa.isRegularFile()).forEach(System.out::println);
}
To add more filtering, enhance the lambda, for example all jpg files modified in the last 24 hours:
(p, bfa) -> bfa.isRegularFile()
&& p.getFileName().toString().matches(".*\\.jpg")
&& bfa.lastModifiedTime().toMillis() > System.currentMillis() - 86400000
Long story short, EOF
marker(but a different literal can be used as well) is a heredoc format that allows you to provide your input as multiline.
A lot of confusion comes from how cat
actually works it seems.
You can use cat
with >>
or >
as follows:
$ cat >> temp.txt
line 1
line 2
While cat
can be used this way when writing manually into console, it's not convenient if I want to provide the input in a more declarative way so that it can be reused by tools and also to keep indentations, whitespaces, etc.
Heredoc allows to define your entire input as if you are not working with stdin
but typing in a separate text editor. This is what Wikipedia article means by:
it is a section of a source code file that is treated as if it were a separate file.
Regarding 4., you still need to ensure that your "dummy script stub" is actually the target URL after all the rewriting is done, or you won't see anything!
A similar/related trick (see this question) is to insert a temporary rule such as:
RewriteRule (.*) /show.php?url=$1 [END]
Where show.php
is some very simple script that just displays its $_GET
parameters (you can display environment variables too, if you want).
This will stop the rewriting at the point you insert it into the ruleset, rather like a breakpoint in a debugger.
If you're using Apache <2.3.9, you'll need to use [L]
rather than [END]
, and you may then need to add:
RewriteRule ^show.php$ - [L]
At the very top of your ruleset, if the URL /show.php
is itself being rewritten.
I don't think this would be possible to do across all browsers.
W3Schools reports that the option events exist in all browsers, but after setting up this test demo. I can only get it to work for Firefox (not Chrome or IE), I haven't tested it on other browsers.
Firefox also allows mouseenter and mouseleave but this is not reported on the w3schools page.
Update: Honestly, from looking at the example code you provided, I wouldn't even use a select box. I think it would look nicer with a slider. I've updated your demo. I had to make a few minor changes to your ratings object (adding a level number) and the safesurf tab. But I left pretty much everything else intact.
The difference between .dylib and .so on mac os x is how they are compiled. For .so files you use -shared and for .dylib you use -dynamiclib. Both .so and .dylib are interchangeable as dynamic library files and either have a type as DYLIB or BUNDLE. Heres the readout for different files showing this.
libtriangle.dylib:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 DYLIB 17 1368 NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS
libtriangle.so:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 DYLIB 17 1256 NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS
triangle.so:
Mach header
magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
MH_MAGIC_64 X86_64 ALL 0x00 BUNDLE 16 1696 NOUNDEFS DYLDLINK TWOLEVEL
The reason the two are equivalent on Mac OS X is for backwards compatibility with other UNIX OS programs that compile to the .so file type.
Compilation notes: whether you compile a .so file or a .dylib file you need to insert the correct path into the dynamic library during the linking step. You do this by adding -install_name and the file path to the linking command. If you dont do this you will run into the problem seen in this post: Mac Dynamic Library Craziness (May be Fortran Only).
Use the property TextWrapping
of the TextBlock
element:
<TextBlock Text="StackOverflow Forum"
Width="100"
TextWrapping="WrapWithOverflow"/>
Assuming your json object from your GET request looks like the one you posted above simply do:
let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});
Or am I missing something that prevents you from doing it this way?
f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)]
f(A)
n
- the predefined length of result arrays
figure (1)
hFig = figure(1);
set(gcf,'PaperPositionMode','auto')
set(hFig, 'Position', [0 0 xwidth ywidth])
plot(x,y)
print -depsc2 correlation.eps; % for saving in eps, look up options for saving as png or other formats you may need
This saves the figure in the dimensions specified
You can also use ng-template, I think that would be more efficient while run time :)
<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
<div>2</div>
</ng-template>
Cheers
Now that pandas' indexes support string operations, arguably the simplest and best way to select columns beginning with 'foo' is just:
df.loc[:, df.columns.str.startswith('foo')]
Alternatively, you can filter column (or row) labels with df.filter()
. To specify a regular expression to match the names beginning with foo.
:
>>> df.filter(regex=r'^foo\.', axis=1)
foo.aa foo.bars foo.fighters foo.fox foo.manchu
0 1.0 0 0 2 NA
1 2.1 0 1 4 0
2 NaN 0 NaN 1 0
3 4.7 0 0 0 0
4 5.6 0 0 0 0
5 6.8 1 0 5 0
To select only the required rows (containing a 1
) and the columns, you can use loc
, selecting the columns using filter
(or any other method) and the rows using any
:
>>> df.loc[(df == 1).any(axis=1), df.filter(regex=r'^foo\.', axis=1).columns]
foo.aa foo.bars foo.fighters foo.fox foo.manchu
0 1.0 0 0 2 NA
1 2.1 0 1 4 0
2 NaN 0 NaN 1 0
5 6.8 1 0 5 0
ALTER TABLE [dbo].[TableName]
ALTER COLUMN ColumnName VARCHAR(Max) NULL
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
CARL LANGE also showed how to get hidden, autoplaying audio in html5 on a iOS device. Works for me.
In HTML,
<div id="hideme">
<audio id="audioTag" controls>
<source src="/path/to/audio.mp3">
</audio>
</div>
with JS
<script type="text/javascript">
window.onload = function() {
var audioEl = document.getElementById("audioTag");
audioEl.load();
audioEl.play();
};
</script>
In CSS,
#hideme {display: none;}
Dependency Injection is passing dependency to other objects or framework( dependency injector).
Dependency injection makes testing easier. The injection can be done through constructor.
SomeClass()
has its constructor as following:
public SomeClass() {
myObject = Factory.getObject();
}
Problem:
If myObject
involves complex tasks such as disk access or network access, it is hard to do unit test on SomeClass()
. Programmers have to mock myObject
and might intercept the factory call.
Alternative solution:
myObject
in as an argument to the constructorpublic SomeClass (MyClass myObject) {
this.myObject = myObject;
}
myObject
can be passed directly which makes testing easier.
It is harder to isolate components in unit testing without dependency injection.
In 2013, when I wrote this answer, this was a major theme on the Google Testing Blog. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.
The problem with using the git hash as the build number is that it's not monotonically increasing. OSGi suggests using a time-stamp for the build number. It looks like the number of commits to the branch could be used in place of the subversion or perforce change number.
Simply compare the width of the documents root element (i.e. html element) against the inner portion of the window:
if ((window.innerWidth - document.documentElement.clientWidth) >0) console.log('V-scrollbar active')
If you also need to know the scrollbar width:
vScrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
Get to the registry to configuration of the client and change the LANG. For Oracle, go to HLM\SOFTWARE\ORACLE\KEY_ORACLIENT...HOME\NLS_LANG and change to appropriate language.
There's nothing wrong with passing integers to str. One reason you might not do this is that myList is really supposed to be a list of integers e.g. it would be reasonable to sum the values in the list. In that case, do not pass your ints to str before appending them to myList. If you end up not converting to strings before appending, you can construct one big string by doing something like
', '.join(map(str, myList))
It would be something like this
function CustomInputBox([string] $title, [string] $message, [string] $defaultText)
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript"
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" )
$_userInput = $inputObject.eval("getInput")
return $_userInput
}
Then you can call the function similar to this.
$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null )
{
echo "Input was [$userInput]"
}
else
{
echo "User cancelled the form!"
}
This is the most simple way to do this that I can think of.
You have to include one more jar.
xmlbeans-2.3.0.jar
Add this and try.
Note: It is required for the files with .xlsx formats only, not for just .xls formats.
As ROM size does not count one does not need any additional RAM besides the TCP buffers. Just implement a big finite-state machine. Each state represents a multi-set of numbers read in. After reading a million numbers one has just to print the numbers corresponding to the reached state.
In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.
Explanation:
Regardless of the decimal part, the second statement, int i2 = (int)score
will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.
Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.
E.g. Consider:
double score = 8.5;
int i1 = Convert.ToInt32(score); // 8
int i2 = (int)score; // 8
score += 1;
i1 = Convert.ToInt32(score); // 10
i2 = (int)score; // 9
Showing how to use this answer
const object= {key1: 'data', key2: 'data2'};
Object.keys(object).includes('key1') //returns true
We can use indexOf
as well, I prefer includes
Firstly, understand that DateTime
objects aren't formatted. They just store the Year, Month, Day, Hour, Minute, Second, etc as a numeric value and the formatting occurs when you want to represent it as a string somehow. You can compare DateTime
objects without formatting them.
To compare an input date with DateTime.Now
, you need to first parse the input into a date and then compare just the Year/Month/Day portions:
DateTime inputDate;
if(!DateTime.TryParse(inputString, out inputDate))
throw new ArgumentException("Input string not in the correct format.");
if(inputDate.Date == DateTime.Now.Date) {
// Same date!
}
$("tr.item").each(function() {
$this = $(this);
var value = $this.find("span.value").html();
var quantity = $this.find("input.quantity").val();
});
It seems that the problem is not related to the module being in a parent directory or anything like that.
You need to add the directory that contains ptdraft
to PYTHONPATH
You said that import nib
worked with you, that probably means that you added ptdraft
itself (not its parent) to PYTHONPATH.
This works for non-associative arrays:
while(($item = array_shift($array2)) !== null && array_push($array1, $item));
If you have https
server, change your url to use https://
protocol.
I got into similar issue with this one. My url has http://
protocol and I want to make a POST
request, but the server wants to redirect it to https
. What happen is that, turns out to be node http behavior sends the redirect request (next) in GET
method which is not the case.
What I did is to change my url to https://
protocol and it works.
Bootstrap 3
Here is a working left sidebar example:
http://bootply.com/90936 (similar to the Bootstrap docs)
The trick is using the affix
component along with some CSS to position it:
#sidebar.affix-top {
position: static;
margin-top:30px;
width:228px;
}
#sidebar.affix {
position: fixed;
top:70px;
width:228px;
}
EDIT- Another example with footer and affix-bottom
Bootstrap 4
The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top
class is explained in this answer.
Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?
Classes are like categories. Many HTML elements can belong to a class, and an HTML element can have more than one class. Classes are used to apply general styles or styles that can be applied across multiple HTML elements.
IDs are identifiers. They're unique; no one else is allowed to have that same ID. IDs are used to apply unique styles to an HTML element.
I use IDs and classes in this fashion:
<div id="header">
<h1>I am a header!</h1>
<p>I am subtext for a header!</p>
</div>
<div id="content">
<div class="section">
<p>I am a section!</p>
</div>
<div class="section special">
<p>I am a section!</p>
</div>
<div class="section">
<p>I am a section!</p>
</div>
</div>
In this example, the header and content sections can be styled via #header and #content. Each section of the content can be applied a common style through #content .section. Just for kicks, I added a "special" class for the middle section. Suppose you wanted a particular section to have a special styling. This can be achieved with the .special class, yet the section still inherits the common styles from #content .section.
When I do JavaScript or CSS development, I typically use IDs to access/manipulate a very specific HTML element, and I use classes to access/apply styles to a broad range of elements.
I ended up here because I was trying to conditionally add header parameters in Swagger UI, based on my own [Authentication]
attribute I added to my API method. Following the hint that @Corcus listed in a comment, I was able to derive my solution, and hopefully it will help others.
Using Reflection, it's checking if the method nested down in apiDescription
has the desired attribute (MyApiKeyAuthenticationAttribute, in my case). If it does, I can append my desired header parameters.
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) {
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
var attributes = ((System.Web.Http.Controllers.ReflectedHttpActionDescriptor)
((apiDescription.ActionDescriptor).ActionBinding.ActionDescriptor)).MethodInfo
.GetCustomAttributes(false);
if(attributes != null && attributes.Any()) {
if(attributes.Where(x => x.GetType()
== typeof(MyApiKeyAuthenticationAttribute)).Any()) {
operation.parameters.Add(new Parameter {
name = "MyApiKey",
@in = "header",
type = "string",
description = "My API Key",
required = true
});
operation.parameters.Add(new Parameter {
name = "EID",
@in = "header",
type = "string",
description = "Employee ID",
required = true
});
}
}
}
I have uninstalled 8.0.19 (64) and installed 8.0.18 (64 bit) and now it Opens.
- What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?
I'm not sure at what level you are looking for an answer at, so let's take a little trip. Some of this you may already know.
When you build your project, Xcode invokes clang
for Objective-C targets and swift
/swiftc
for Swift targets. Both of these compilers compile the app to an intermediate representation (IR), one of these IRs is bitcode. From this IR, a program called LLVM takes over and creates the binaries needed for x86 32 and 64 bit modes (for the simulator) and arm6/arm7/arm7s/arm64 (for the device). Normally, all of these different binaries are lumped together in a single file called a fat binary.
The ENABLE_BITCODE option cuts out this final step. It creates a version of the app with an IR bitcode binary. This has a number of nice features, but one giant drawback: it can't run anywhere. In order to get an app with a bitcode binary to run, the bitcode needs to be recompiled (maybe assembled or transcoded… I'm not sure of the correct verb) into an x86 or ARM binary.
When a bitcode app is submitted to the App Store, Apple will do this final step and create the finished binaries.
Right now, bitcode apps are optional, but history has shown Apple turns optional things into requirements (like 64 bit support). This usually takes a few years, so third party developers (like Parse) have time to update.
- can I use the above method without any negative impact and without compromising a future appstore submission?
Yes, you can turn off ENABLE_BITCODE and everything will work just like before. Until Apple makes bitcode apps a requirement for the App Store, you will be fine.
- Are there any performance impacts if I enable / disable it?
There will never be negative performance impacts for enabling it, but internal distribution of an app for testing may get more complicated.
As for positive impacts… well that's complicated.
For distribution in the App Store, Apple will create separate versions of your app for each machine architecture (arm6/arm7/arm7s/arm64) instead of one app with a fat binary. This means the app installed on iOS devices will be smaller.
In addition, when bitcode is recompiled (maybe assembled or transcoded… again, I'm not sure of the correct verb), it is optimized. LLVM is always working on creating new a better optimizations. In theory, the App Store could recreate the separate version of the app in the App Store with each new release of LLVM, so your app could be re-optimized with the latest LLVM technology.
java.util.UUID.randomUUID();
Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.
mongoexport -d <database> -c <collection_name>
Also helpful:
-o
: write the output to file, otherwise standard output is used (docs)
--jsonArray
: generates a valid json document, instead of one json object per line (docs)
--pretty
: outputs formatted json (docs)
No, arrays/lists can't be passed to SQL Server directly.
The following options are available:
Sometimes you may want to let the server know that the user is leaving the page. This is useful, for example, to clean up unsaved images stored temporarily on the server, to mark that user as "offline", or to log when they are done their session.
Historically, you would send an AJAX request in the beforeunload
function, however this has two problems. If you send an asynchronous request, there is no guarantee that the request would be executed correctly. If you send a synchronous request, it is more reliable, but the browser would hang until the request has finished. If this is a slow request, this would be a huge inconvenience to the user.
Later came navigator.sendBeacon()
. By using the sendBeacon()
method, the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. This solves all of the problems with submission of analytics data: the data is sent reliably, it's sent asynchronously, and it doesn't impact the loading of the next page.
Unless you are targeting only desktop users, sendBeacon()
should not be used with unload
or beforeunload
since these do not reliably fire on mobile devices. Instead you can listen to the visibilitychange
event. This event will fire every time your page is visible and the user switches tabs, switches apps, goes to the home screen, answers a phone call, navigates away from the page, closes the tab, refreshes, etc.
Here is an example of its usage:
document.addEventListener('visibilitychange', function() {
if (document.visibilityState == 'hidden') {
navigator.sendBeacon("/log.php", analyticsData);
}
});
When the user returns to the page, document.visibilityState
will change to 'visible'
, so you can also handle that event as well.
sendBeacon()
is supported in:
It is NOT currently supported in:
Here is a polyfill for sendBeacon() in case you need to add support for unsupported browsers. If the method is not available in the browser, it will send a synchronous AJAX request instead.
Update:
It might be worth mentioning that sendBeacon()
only sends POST
requests. If you need to send a request using any other method, an alternative would be to use the fetch API
with the keepalive
flag set to true
, which causes it to behave the same way as sendBeacon()
. Browser support for the fetch API is about the same.
fetch(url, {
method: ...,
body: ...,
headers: ...,
credentials: 'include',
mode: 'no-cors',
keepalive: true,
})
At the current version of Spring-Boot (1.4.1.RELEASE) , each pooling datasource implementation has its own prefix for properties.
For instance, if you are using tomcat-jdbc:
spring.datasource.tomcat.max-wait=10000
You can find the explanation out here
spring.datasource.max-wait=10000
this have no effect anymore.
also had same problem once,
if you are unable to solve the problem you can run the following command on command line
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
Note: you have to navigate to the installation path of your chrome.
For example:cd C:\Program Files\Google\Chrome\Application
A developer session chrome browser will be opened, you can now launch your app on the new chrome browse.
I hope this should be helpful
First of all, both cases calls a constructor. If you write
Example *example = new Example();
then you are creating an object, call the constructor and retrieve a pointer to it.
If you write
Example example;
The only difference is that you are getting the object and not a pointer to it. The constructor called in this case is the same as above, the default (no argument) constructor.
As for the singleton question, you must simple invoke your static method by writing:
Example *e = Singleton::getExample();
var elem = $('#some-id');
elem.mouseover(function () {
// Some code here
}).mouseout(function (event) {
var e = event.toElement || event.relatedTarget;
if (elem.has(e).length > 0) return;
// Some code here
});
Sure, a Linked List is a bit confusing for programming n00bs, pretty much the temptation is to look at it as Russian Dolls, because that's what it seems like, a LinkedList Object in a LinkedList Object. But that's a touch difficult to visualize, instead look at it like a computer.
LinkedList = Data + Next Member
Where it's the last member of the list if next is NULL
So a 5 member LinkedList would be:
LinkedList(Data1, LinkedList(Data2, LinkedList(Data3, LinkedList(Data4, LinkedList(Data5, NULL)))))
But you can think of it as simply:
Data1 -> Data2 -> Data3 -> Data4 -> Data5 -> NULL
So, how do we find the end of this? Well, we know that the NULL is the end so:
public void append(LinkedList myNextNode) {
LinkedList current = this; //Make a variable to store a pointer to this LinkedList
while (current.next != NULL) { //While we're not at the last node of the LinkedList
current = current.next; //Go further down the rabbit hole.
}
current.next = myNextNode; //Now we're at the end, so simply replace the NULL with another Linked List!
return; //and we're done!
}
This is very simple code of course, and it will infinitely loop if you feed it a circularly linked list! But that's the basics.
Posting parameters Using POST:-
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
The part which you missed is in the the following... i.e., as follows..
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();
The rest of the thing you can do it.
just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.
let's play a bit ;) :
import cv2
import numpy as np
>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168, 58, 2, 1], # uninitialized memory counts as random, too ? fun ;)
[ 0, 100, 2, 0, 101],
[ 0, 0, 106, 2, 0],
[131, 2, 0, 90, 3],
[ 0, 100, 1, 0, 83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99)) # normal
array([[ 0, 76, 0, 129, 0],
[ 0, 0, 0, 188, 27],
[ 0, 152, 0, 0, 0],
[ 0, 0, 134, 79, 0],
[ 0, 181, 36, 128, 0]], dtype=uint8)
>>> cv2.randu(im,(0),(99)) # uniform
array([[19, 53, 2, 86, 82],
[86, 73, 40, 64, 78],
[34, 20, 62, 80, 7],
[24, 92, 37, 60, 72],
[40, 12, 27, 33, 18]], dtype=uint8)
to apply it to an existing image, just generate noise in the desired range, and add it:
img = ...
noise = ...
image = img + noise
Extend HttpServletRequestWrapper
, override the header getters to return the parameters as well:
public class AddParamsToHeader extends HttpServletRequestWrapper {
public AddParamsToHeader(HttpServletRequest request) {
super(request);
}
public String getHeader(String name) {
String header = super.getHeader(name);
return (header != null) ? header : super.getParameter(name); // Note: you can't use getParameterValues() here.
}
public Enumeration getHeaderNames() {
List<String> names = Collections.list(super.getHeaderNames());
names.addAll(Collections.list(super.getParameterNames()));
return Collections.enumeration(names);
}
}
..and wrap the original request with it:
chain.doFilter(new AddParamsToHeader((HttpServletRequest) request), response);
That said, I personally find this a bad idea. Rather give it direct access to the parameters or pass the parameters to it.
Reading this original article on The Code Project will help you a lot: Visual Representation of SQL Joins.
Also check this post: SQL SERVER – Better Performance – LEFT JOIN or NOT IN?.
Find original one at: Difference between JOIN and OUTER JOIN in MySQL.
For me the issue turned out to be I was using es6's right arrow functions =>
as opposed to function ()
.
Replacing =>
with function ()
resolved for me.
I had assumed it was a jQuery issue.
You have a wrong idea of what fgets returns. Take a look at this: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/
It returns null when it finds an EOF character. Try running the program above and pressing CTRL+D (or whatever combination is your EOF character), and the loop will exit succesfully.
How do you want to detect the end of the input? Newline? Dot (you said sentence xD)?
I've had good results with this one. Much easier to use than Sharpen.
http://tangiblesoftwaresolutions.com/Product_Details/Java_to_CSharp_Converter.html
I mean a prompt script would work if the variable was not needed for the HTML aspect, even then in certain situations, a function could be used.
var save_user_input = prompt('what needs to be saved?');
//^ makes a variable of the prompt's answer
if (save_user_input == null) {
//^ if the answer is null, it is nothing
//however, if it is nothing, it is cancelled (as seen below). If it is "null" it is what the user said, then assigned to the variable(i think), but also null as in nothing in the prompt answer window, but ok pressed. So you cant do an or "null" (which would look like: if (save_user_input == null || "null") {)because (I also don't really know if this is right) the variable is "null". Very confusing
alert("cancelled");
//^ alerts the user the cancel button was pressed. No long explanation this time.
}
//^ is an end for the if (i got stumped as to why it wasn’t working and then realised this. very important to remember.)
else {
alert(save_user_input + " is what you said");
//^ alerts the user the variable and adds the string " is what you said" on the end
}
_x000D_
There is a quirk with this that might be relevant for some people... From the PHP docs comments.
If you want cURL to timeout in less than one second, you can use
CURLOPT_TIMEOUT_MS
, although there is a bug/"feature" on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached". The explanation for this behavior is:"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."
What this means to PHP developers is "You can't use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"
The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.
The solution is to disable signals using CURLOPT_NOSIGNAL. Here's an example script that requests itself causing a 10-second delay so you can test timeouts:
if (!isset($_GET['foo'])) {
// Client
$ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
$data = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_errno > 0) {
echo "cURL Error ($curl_errno): $curl_error\n";
} else {
echo "Data received: $data\n";
}
} else {
// Server
sleep(10);
echo "Done.";
}
From http://www.php.net/manual/en/function.curl-setopt.php#104597
Alternatively, and this would give you more flexibility if testing for values other than 1 or 2 in future, is to use a switch statement
switch(value)
{
case 1:
case 2:
return true;
default:
return false
}
This work for me
from flask import Flask
from flask import Response
app = Flask(__name__)
@app.route("/")
def home():
return Response(headers={'Access-Control-Allow-Origin':'*'})
if __name__ == "__main__":
app.run()
C:> cmd
Microsoft Windows [Version 10.0.17130.1233]
(c) 2018 Microsoft Corporation. All rights reserved.
Since the <script>
tag is exempted from the Same Origin Policy which is a security necessity in the web world, while(1)
when added to the JSON response prevents misuse of it in the <script>
tag.
When I'm doing something like this I use the onKeyUp event.
<script type="text/javascript">
function bar() {
//do stuff
}
<input type="text" name="foo" onKeyUp="return bar()" />
but if you don't want to use an HTML event you could try to use jQuerys .change() method
$('.target').change(function() {
//do stuff
});
in this example, the input would have to have a class "target"
if you're going to have multiple text boxes that you want to have done the same thing when their text is changed and you need their data then you could do this:
$('.target').change(function(event) {
//do stuff with the "event" object as the object that called the method
)};
that way you can use the same code, for multiple text boxes using the same class without having to rewrite any code.
This should work.
using System.Drawing.Printing;
...
PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "The printer name"; // Load the appropriate printer's setting
After that, the various properties of PrinterSettings can be read.
Note that ps.isValid()
can see if the printer actually exists.
Edit: One additional comment. Microsoft recommends you use a PrintDocument and modify its PrinterSettings rather than creating a PrinterSettings directly.
Try this CSS
input[type=checkbox] {width:100px; height:100px;}
Among other already mentioned tools you can use also readelf
(manual). It is similar to objdump
but goes more into detail. See this for the difference explanation.
$ readelf -sW /lib/liblzma.so.5 |head -n10
Symbol table '.dynsym' contains 128 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FUNC GLOBAL DEFAULT UND pthread_mutex_unlock@GLIBC_2.0 (4)
2: 00000000 0 FUNC GLOBAL DEFAULT UND pthread_mutex_destroy@GLIBC_2.0 (4)
3: 00000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable
4: 00000000 0 FUNC GLOBAL DEFAULT UND memmove@GLIBC_2.0 (5)
5: 00000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.0 (5)
6: 00000000 0 FUNC GLOBAL DEFAULT UND memcpy@GLIBC_2.0 (5)
From my experience, once you include the chartjs-plugin-datalabels plugin (make sure to place the <script>
tag after the chart.js tag on your page), your charts begin to display values.
If you then choose you can customize it to fit your needs. The customization is clearly documented here but basically, the format is like this hypothetical example:
var myBarChart = new Chart(ctx, {
type: 'bar',
data: yourDataObject,
options: {
// other options
plugins: {
datalabels: {
anchor :'end',
align :'top',
// and if you need to format how the value is displayed...
formatter: function(value, context) {
return GetValueFormatted(value);
}
}
}
}
});
You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:
class ModelAttachment {
var id: String?
var url: String?
var thumb: String?
}
var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"
var imgs: Array<ModelAttachment> = [modelAttachementObj]
for img in imgs {
let url = img.url
NSLog(url!)
}
If your script is a directory or ZIP file rather than a single python file, __main__.py
will be executed when the "script" is passed as an argument to the python interpreter.
Most of the other answers are a little complex for me on this question (I'm new to C#), so I am writing mine:
I have a WPF application and have defined a worker as below:
Issue:
BackgroundWorker workerAllocator;
workerAllocator.DoWork += delegate (object sender1, DoWorkEventArgs e1) {
// This is my DoWork function.
// It is given as an anonymous function, instead of a separate DoWork function
// I need to update a message to textbox (txtLog) from this thread function
// Want to write below line, to update UI
txt.Text = "my message"
// But it fails with:
// 'System.InvalidOperationException':
// "The calling thread cannot access this object because a different thread owns it"
}
Solution:
workerAllocator.DoWork += delegate (object sender1, DoWorkEventArgs e1)
{
// The below single line works
txtLog.Dispatcher.BeginInvoke((Action)(() => txtLog.Text = "my message"));
}
I am yet to find out what the above line means, but it works.
For WinForms:
Solution:
txtLog.Invoke((MethodInvoker)delegate
{
txtLog.Text = "my message";
});
While the above answers are probably best for this situation, if you just want to do a one-off and don't want to bother with modifying other files, you can in-line the CSS.
<p style="margin-bottom:3cm;">This is the first question?</p>
The accepted answer refers to Object. Beware using the in
operator on Array to find data instead of keys:
("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)
To test existing elements in an Array: Best way to find if an item is in a JavaScript array?
in my case, this error is raised due to sequence was not created..
CREATE SEQUENCE J.SOME_SEQ MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE ;
Update as of March 2018.
I tried various techniques given in other answers to download my file (6 GB) directly from Google drive to my AWS ec2 instance but none of them work (might be because they are old).
So, for the information of others, here is how I did it successfully:
https://drive.google.com/file/d/FILEIDENTIFIER/view?usp=sharing
Copy the below script to a file. It uses curl and processes the cookie to automate the downloading of the file.
#!/bin/bash
fileid="FILEIDENTIFIER"
filename="FILENAME"
curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${fileid}" > /dev/null
curl -Lb ./cookie "https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=${fileid}" -o ${filename}
As shown above, paste the FILEIDENTIFIER in the script. Remember to keep the double quotes!
myfile.zip
).sudo chmod +x download-gdrive.sh
.PS: Here is the Github gist for the above given script: https://gist.github.com/amit-chahar/db49ce64f46367325293e4cce13d2424
As many pointed out in other answers, changing the default authentication plugin of MySQL to native does the trick.
Still, since I can't use the new caching_sha2_password plugin, I'll wait until compatibility is developed to close the topic.
Jersey makes the process very easy, my service class worked well with JSON, all I had to do is to add the dependencies in the pom.xml
@Path("/customer")
public class CustomerService {
private static Map<Integer, Customer> customers = new HashMap<Integer, Customer>();
@POST
@Path("save")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public SaveResult save(Customer c) {
customers.put(c.getId(), c);
SaveResult sr = new SaveResult();
sr.sucess = true;
return sr;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Customer getCustomer(@PathParam("id") int id) {
Customer c = customers.get(id);
if (c == null) {
c = new Customer();
c.setId(id * 3);
c.setName("unknow " + id);
}
return c;
}
}
And in the pom.xml
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>
This is how to retrieve a Column Name from a DataColumn:
MyDataTable.Columns(1).ColumnName
To get the name of all DataColumns within your DataTable:
Dim name(DT.Columns.Count) As String
Dim i As Integer = 0
For Each column As DataColumn In DT.Columns
name(i) = column.ColumnName
i += 1
Next
References
Parse that string into a Date
object:
var myDate = new Date('10/11/1955 10:40:50 AM');
Then use the usual methods to get the date's day of month (getDate
) / month (getMonth
) / year (getFullYear
).
var noTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());
This is because strings are immutable in Python.
Which means that X.replace("hello","goodbye")
returns a copy of X
with replacements made. Because of that you need replace this line:
X.replace("hello", "goodbye")
with this line:
X = X.replace("hello", "goodbye")
More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace
,strip
,translate
,lower
/upper
,join
,...
You must assign their output to something if you want to use it and not throw it away, e.g.
X = X.strip(' \t')
X2 = X.translate(...)
Y = X.lower()
Z = X.upper()
A = X.join(':')
B = X.capitalize()
C = X.casefold()
and so on.
The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.
AWS S3:
aws.example.com
Redirect all requests to another host name
and enter your URL:
https://myaccount.signin.aws.amazon.com/console/
AWS Route53:
Yes
. Click on Alias
Target
field and select the S3 bucket you created in the previous
step.Reference: How to redirect domains using Amazon Web Services
AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?
Assume you stored that dictionary in a variable called values. To get id
in to a variable, do:
idValue = values['criteria'][0]['id']
If that json is in a file, do the following to load it:
import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
If that json is from a URL, do the following to load it:
import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()
To print ALL of the criteria, you could:
for criteria in values['criteria']:
for key, value in criteria.iteritems():
print key, 'is:', value
print ''
These are several ways to apply style to an element. Try any one of the examples below:
1. document.getElementById('div_register').className = 'wide';
/* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';
Just use plain objects:
var map = { key1: "value1", key2: "value2" }
function get(k){
return map[k];
}
You can do it like this:
$str = "abc-123-xyz-789";
$last = array_pop( explode('-', $str) );
echo $last; //echoes 789
When you allow the 9000 port to firewall on your desired operating System the following error "ERROR: Sonar server 'http://localhost:9000' can not be reached" will remove successfully.In ubuntu it is just like as by typing the following command in terminal "sudo ufw allow 9000/tcp" this error will removed from the Jenkins server by clicking on build now in jenkins.
You can try using this way :
sentence ["Robert"] = "Roger"
Then the sentence will become :
sentence = "My name is Roger" # Robert is replaced with Roger
For cases of appending to end of existing string:
string = "Sec_"
string += "C_type"
print(string)
results in
Sec_C_type
KB's answer to use [Environment]::GetFolderPath("Desktop")
is obviously the official Windows API for doing this.
However, if you're working interactively at the prompt, or just want something that works on your machine, the tilda (~) character refers to the current user's home folder. So ~/desktop
is the user's desktop folder.
First of all, requesting a method of a controller from another controller is EVIL. This will cause many hidden problems in Laravel's life-cycle.
Anyway, there are many solutions for doing that. You can select one of these various ways.
But you can't add any parameters or authentication with this way.
app(\App\Http\Controllers\PrintReportContoller::class)->getPrintReport();
You can add any parameters and something with this. The best solution for your programming life. You can make Repository
instead Service
.
class PrintReportService
{
...
public function getPrintReport() {
return ...
}
}
class PrintReportController extends Controller
{
...
public function getPrintReport() {
return (new PrintReportService)->getPrintReport();
}
}
class SubmitPerformanceController
{
...
public function getSomethingProxy() {
...
$a = (new PrintReportService)->getPrintReport();
...
return ...
}
}
MakesHttpRequests
trait that used in Application Unit Testing.I recommend this if you have special reason for making this proxy, you can use any parameters and custom headers. Also this will be an internal request in laravel. (Fake HTTP Request) You can see more details for the call
method in here.
class SubmitPerformanceController extends \App\Http\Controllers\Controller
{
use \Illuminate\Foundation\Testing\Concerns\MakesHttpRequests;
protected $baseUrl = null;
protected $app = null;
function __construct()
{
// Require if you want to use MakesHttpRequests
$this->baseUrl = request()->getSchemeAndHttpHost();
$this->app = app();
}
public function getSomethingProxy() {
...
$a = $this->call('GET', '/printer/report')->getContent();
...
return ...
}
}
However this is not a 'good' solution, too.
This is the most terrible solution I think. You can use any parameters and custom headers, too. But this would be making an external extra http request. So HTTP Webserver must be running.
$client = new Client([
'base_uri' => request()->getSchemeAndhttpHost(),
'headers' => request()->header()
]);
$a = $client->get('/performance/submit')->getBody()->getContents()
Finally I am using Way 1 of Case 2. I need parameters and
You can use union method for sets: set.union(other_set)
Note that it returns a new set i.e it doesn't modify itself.
XML is not a format for storing images, neither binary data. I think it all depends on how you want to use those images. If you are in a web application and would want to read them from there and display them, I would store the URLs. If you need to send them to another web endpoint, I would serialize them, rather than persisting manually in XML. Please explain what is the scenario.
The basic answer is to accumulate the sum of both x (call it 'sum_x1') and x2 (call it 'sum_x2') as you go. The value of the standard deviation is then:
stdev = sqrt((sum_x2 / n) - (mean * mean))
where
mean = sum_x / n
This is the sample standard deviation; you get the population standard deviation using 'n' instead of 'n - 1' as the divisor.
You may need to worry about the numerical stability of taking the difference between two large numbers if you are dealing with large samples. Go to the external references in other answers (Wikipedia, etc) for more information.
var obj = $.parseJSON(result);
for (var prop in obj) {
alert(prop + " is " + obj[prop]);
}
Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
@RestController
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
@Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
@Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
$('input[type=checkbox]').on("change",function(){
var target = $(this).parent().find('input[type=hidden]').val();
if(target == 0)
{
target = 1;
}
else
{
target = 0;
}
$(this).parent().find('input[type=hidden]').val(target);
});
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
If you leave out the name of the checkbox it doesn't get passed. Only the test_checkbox array.
Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.
Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.
@Baxter's is mostly correct but it is missing one important Windows-specific detail.
Subversion's runtime configuration area is stored in the %APPDATA%\Subversion\
directory. The files are config
and servers
.
However, in addition to text-based configuration files, Subversion clients can use Windows Registry to store the client settings. It makes it possible to modify the settings with PowerShell in a convenient manner, and also distribute these settings to user workstations in Active Directory environment via AD Group Policy. See SVNBook | Configuration and the Windows Registry (you can find examples and a sample *.reg
file there).
I've searched a lot and the best way I've found so far is on this article:
Class to serialize
package net.sghill.example;
import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonDeserialize(using = UserDeserializer.class)
public class User {
private ObjectId id;
private String username;
private String password;
public User(ObjectId id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public ObjectId getId() { return id; }
public String getUsername() { return username; }
public String getPassword() { return password; }
}
Deserializer class
package net.sghill.example;
import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import java.io.IOException;
public class UserDeserializer extends JsonDeserializer<User> {
@Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
}
}
Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.
signal
isn't the most reliable way as it differs in implementations. I would recommend using sigaction
. Tom's code would now look like this :
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
void my_handler(int s){
printf("Caught signal %d\n",s);
exit(1);
}
int main(int argc,char** argv)
{
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = my_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
pause();
return 0;
}
Here are the outputs of isset()
and empty()
for the 4 possibilities: undeclared, null, false and true.
$a=null;
$b=false;
$c=true;
var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared
var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared
//array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) }
//array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) }
You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false
. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset
and false when tested by 'empty'.
So use isset()
when you're concerned about the existence of a variable. And use empty
when you're testing for true or false. If the actual type of emptiness matters, use is_null
and ===0
, ===false
, ===''
.
I use Singletons as an interview test.
When I ask a developer to name some design patterns, if all they can name is Singleton, they're not hired.
Well, while googling about this throw specification, I had a look at this article :- (http://blogs.msdn.com/b/larryosterman/archive/2006/03/22/558390.aspx)
I am reproducing a part of it here also, so that it can be used in future irrespective of the fact that the above link works or not.
class MyClass
{
size_t CalculateFoo()
{
:
:
};
size_t MethodThatCannotThrow() throw()
{
return 100;
};
void ExampleMethod()
{
size_t foo, bar;
try
{
foo = CalculateFoo();
bar = foo * 100;
MethodThatCannotThrow();
printf("bar is %d", bar);
}
catch (...)
{
}
}
};
When the compiler sees this, with the "throw()" attribute, the compiler can completely optimize the "bar" variable away, because it knows that there is no way for an exception to be thrown from MethodThatCannotThrow(). Without the throw() attribute, the compiler has to create the "bar" variable, because if MethodThatCannotThrow throws an exception, the exception handler may/will depend on the value of the bar variable.
In addition, source code analysis tools like prefast can (and will) use the throw() annotation to improve their error detection capabilities - for example, if you have a try/catch and all the functions you call are marked as throw(), you don't need the try/catch (yes, this has a problem if you later call a function that could throw).
It's also possible to customise your bootstrap build by using:
http://twitter.github.com/bootstrap/customize.html
All the plugins are included by default.
Aside from getting decode
and encode
backwards, I think part of the answer here is actually don't use the ascii
encoding. It's probably not what you want.
To begin with, think of str
like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is up to whatever piece of code is reading it. If you don't know what this paragraph is talking about, go read Joel's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets right now before you go any further.
Naturally, we're all aware of the mess that created. The answer is to, at least within memory, have a standard encoding for all strings. That's where unicode
comes in. I'm having trouble tracking down exactly what encoding Python uses internally for sure, but it doesn't really matter just for this. The point is that you know it's a sequence of bytes that are interpreted a certain way. So you only need to think about the characters themselves, and not the bytes.
The problem is that in practice, you run into both. Some libraries give you a str
, and some expect a str
. Certainly that makes sense whenever you're streaming a series of bytes (such as to or from disk or over a web request). So you need to be able to translate back and forth.
Enter codecs
: it's the translation library between these two data types. You use encode
to generate a sequence of bytes (str
) from a text string (unicode
), and you use decode
to get a text string (unicode
) from a sequence of bytes (str
).
For example:
>>> s = "I look like a string, but I'm actually a sequence of bytes. \xe2\x9d\xa4"
>>> codecs.decode(s, 'utf-8')
u"I look like a string, but I'm actually a sequence of bytes. \u2764"
What happened here? I gave Python a sequence of bytes, and then I told it, "Give me the unicode
version of this, given that this sequence of bytes is in 'utf-8'
." It did as I asked, and those bytes (a heart character) are now treated as a whole, represented by their Unicode codepoint.
Let's go the other way around:
>>> u = u"I'm a string! Really! \u2764"
>>> codecs.encode(u, 'utf-8')
"I'm a string! Really! \xe2\x9d\xa4"
I gave Python a Unicode string, and I asked it to translate the string into a sequence of bytes using the 'utf-8'
encoding. So it did, and now the heart is just a bunch of bytes it can't print as ASCII; so it shows me the hexadecimal instead.
We can work with other encodings, too, of course:
>>> s = "I have a section \xa7"
>>> codecs.decode(s, 'latin1')
u'I have a section \xa7'
>>> codecs.decode(s, 'latin1')[-1] == u'\u00A7'
True
>>> u = u"I have a section \u00a7"
>>> u
u'I have a section \xa7'
>>> codecs.encode(u, 'latin1')
'I have a section \xa7'
('\xa7'
is the section character, in both
Unicode and Latin-1.)
So for your question, you first need to figure out what encoding your str
is in.
Did it come from a file? From a web request? From your database? Then the source determines the encoding. Find out the encoding of the source and use that to translate it into a unicode
.
s = [get from external source]
u = codecs.decode(s, 'utf-8') # Replace utf-8 with the actual input encoding
Or maybe you're trying to write it out somewhere. What encoding does the destination expect? Use that to translate it into a str
. UTF-8 is a good choice for plain text documents; most things can read it.
u = u'My string'
s = codecs.encode(u, 'utf-8') # Replace utf-8 with the actual output encoding
[Write s out somewhere]
Are you just translating back and forth in memory for interoperability or something? Then just pick an encoding and stick with it; 'utf-8'
is probably the best choice for that:
u = u'My string'
s = codecs.encode(u, 'utf-8')
newu = codecs.decode(s, 'utf-8')
In modern programming, you probably never want to use the 'ascii'
encoding for any of this. It's an extremely small subset of all possible characters, and no system I know of uses it by default or anything.
Python 3 does its best to make this immensely clearer simply by changing the names. In Python 3, str
was replaced with bytes
, and unicode
was replaced with str
.
Some more:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25
You build the object before encoding it to a JSON string:
import json
data = {}
data['key'] = 'value'
json_data = json.dumps(data)
JSON is a serialization format, textual data representing a structure. It is not, itself, that structure.
Finally worked out how to change the collapse width by fiddling with '@grid-float-breakpoint' at http://getbootstrap.com/customize/.
Go to line 2923 in bootstrap.css(also min version) and change @media screen and (min-width: 768px) {
to @media screen and (min-width: 1000px) {
So the code will end up being:
@media screen and (min-width: 1000px) {
.navbar-brand {
float: left;
margin-right: 5px;
margin-left: -15px;
}
.navbar-nav {
float: left;
margin-top: 0;
margin-bottom: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
border-radius: 0;
}
.navbar-nav.pull-right {
float: right;
width: auto;
}
.navbar-toggle {
position: relative;
top: auto;
left: auto;
display: none;
}
.nav-collapse.collapse {
display: block !important;
height: auto !important;
overflow: visible !important;
}
}
JavaScript code is usually called from the onclick
event of a link. For example, you could instead do:
In Head Section of HTML Document
<script type='text/javascript'>
function myFunction(){
//...script code
}
</script>
In Body of HTML Document
<a href="#" id="mylink" onclick="myFunction(); return false">Call JavaScript </a>
Alternatively, you can also attach your function to the link using the links' ID, and HTML DOM or a framework like JQuery.
For example:
In Head Section of HTML Document
<script type='text/javascript'>
document.getElementById("mylink").onclick = function myFunction(){ ...script code};
</script>
In Body of HTML Document
<a href="#" id="mylink">Call JavaScript </a>
Probably not the most efficient code, but here it goes:
$dateElements = explode('-', $dateValue);
$year = $dateElements[0];
echo $year; //2012
switch ($dateElements[1]) {
case '01' : $mo = "January";
break;
case '02' : $mo = "February";
break;
case '03' : $mo = "March";
break;
.
.
.
case '12' : $mo = "December";
break;
}
echo $mo; //January
The easiest way:
Step 1: Open AndroidManifest.xml file
Step 2: Locate android:theme="@style/AppTheme" >
Step 3: Change to android:theme="@style/Theme.AppCompat.NoActionBar" >
Step 4: Then Add ImageView & Image
Step 4: That's it!
Having a table with a foreign key to itself does make sense to me.
You can then use a common table expression in SQL or the connect by prior statement in Oracle to build your tree.
Swift 3 / Alamofire 4.0 (Addendum to the accepted answer)
To append to multipartFormData
in Swift 3 / Alamofire 4.0, use the following method of MultipartFormData
:
public func append(_ data: Data, withName name: String) { /* ... */ }
And, to convert String
to Data
, the data(using:)
method of String
. E.g.,
multipartFormData.append("comment".data(using: .utf8)!, withName: "comment")
The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:
The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?
This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.
In other words, the feature is missing to remove the temptation to use the feature insecurely.
Just want to share another option:
# mark two objects to be deleted
session.delete(obj1)
session.delete(obj2)
# commit (or flush)
session.commit()
http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting
In this example, the following codes shall works fine:
obj = User.query.filter_by(id=123).one()
session.delete(obj)
session.commit()
if you are using same date format and have select query where date in oracle :
select count(id) from Table_name where TO_DATE(Column_date)='07-OCT-2015';
To_DATE provided by oracle
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
It would actually be more effort, but you could just build in VS.Net, run it from the regular command line (cmd.exe), and then attach to the process after it starts running. This is probably not the solution you are looking for however.
multiple criteria can also be implemented through lambda function
sorted_list = sorted(list_to_sort, key=lambda x: (x[1], x[0]))
Adding to Julia Passynkova's answer
To set validation error in component:
formData.form.controls['email'].setErrors({'incorrect': true});
To unset validation error in component:
formData.form.controls['email'].setErrors(null);
Be careful with unsetting the errors using null
as this will overwrite all errors. If you want to keep some around you may have to check for the existence of other errors first:
if (isIncorrectOnlyError){
formData.form.controls['email'].setErrors(null);
}
Use git clone
with the --depth
option set to 1
to create a shallow clone with a history truncated to the latest commit.
For example:
git clone --depth 1 https://github.com/user/repo.git
To also initialize and update any nested submodules, also pass --recurse-submodules
and to clone them shallowly, also pass --shallow-submodules
.
For example:
git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git
Try the following:
print "First is: %f" % (first)
print "Second is: %f" % (second)
I am unsure what answer is. But apart from that, this will be:
print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)
There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:
If you try this:
print "First is: %s" % (first)
It converts the float value in first to a string. So that would work as well.
I started Eclipse as admin, and it worked.
Matplot colors your plot with different colors , but incase you wanna put specific colors
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
plt.plot(x, x)
plt.plot(x, 2 * x,color='blue')
plt.plot(x, 3 * x,color='red')
plt.plot(x, 4 * x,color='green')
plt.show()
In my case, I tried everything above, nothing worked. I am pretty sure, my database looks like below.
mysql Ver 14.14 Distrib 5.7.17, for Linux (x86_64) using EditLine wrapper
Connection id: 12
Current database: xxx
Current user: yo@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 5.7.17-0ubuntu0.16.04.1 (Ubuntu)
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: utf8
Db characterset: utf8
Client characterset: utf8
Conn. characterset: utf8
UNIX socket: /var/run/mysqld/mysqld.sock
Uptime: 42 min 49 sec
Threads: 1 Questions: 372 Slow queries: 0 Opens: 166 Flush tables: 1 Open tables: 30 Queries per second avg: 0.144
so, I look up the column charset in every table
show create table company;
It turns out the column charset is latin. That's why, I can not insert Chinese into database.
ALTER TABLE company CONVERT TO CHARACTER SET utf8;
That might help you. :)
You can simply use the data-interval
attribute of the carousel
class.
It's default value is set to data-interval="3000"
i.e 3seconds.
All you need to do is set it to your desired requirements.
I did not find the answer to my question after searching Google & stackoverflow for a while so I would like to share my solution here.
git config --global credential.helper "/bin/bash /git_creds.sh"
echo '#!/bin/bash' > /git_creds.sh
echo "sleep 1" >> /git_creds.sh
echo "echo username=$SERVICE_USER" >> /git_creds.sh
echo "echo password=$SERVICE_PASS" >> /git_creds.sh
# to test it
git clone https://my-scm-provider.com/project.git
I did it for Windows too. Full answer here
Do something like this:
<script>
function changeColor(id)
{
document.getElementById(id).style.color = "#ff0000"; // forecolor
document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>
<div id="myid">Hello There !!</div>
<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>
Try this
Dim app As Excel.Application = Nothing
Dim Active_Cell As Excel.Range = Nothing
Try
app = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
Active_Cell = app.ActiveCell
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
' .address will return the cell reference :)
To answer the question How to delete specific columns in vba for excel. I use Array as below.
sub del_col()
dim myarray as variant
dim i as integer
myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i
end sub
Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:
/search?searchquery=text and 'query' is provided.
In this case searchquery param value is changed.
Code:
function replaceUrlParam(url, paramName, paramValue){
var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
var newUrl=url
if(url.search(pattern)>=0){
newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
}
else{
newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
}
return newUrl
}
Java always uses at least 32 bit values for calculations. This is due to the 32-bit architecture which was common 1995 when java was introduced. The register size in the CPU was 32 bit and the arithmetic logic unit accepted 2 numbers of the length of a cpu register. So the cpus were optimized for such values.
This is the reason why all datatypes which support arithmetic opperations and have less than 32-bits are converted to int (32 bit) as soon as you use them for calculations.
So to sum up it mainly was due to performance issues and is kept nowadays for compatibility.
The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.
More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html
The easiest solution working fine for me is this:
export CFLAGS=-ggdb
export CXXFLAGS=-ggdb
CMake will append them to all configurations' flags. Just make sure to clear CMake cache.
Assumed imports:
import pandas as pd
John Galt's answer is basically a reduce
operation. If I have more than a handful of dataframes, I'd put them in a list like this (generated via list comprehensions or loops or whatnot):
dfs = [df0, df1, df2, dfN]
Assuming they have some common column, like name
in your example, I'd do the following:
df_final = reduce(lambda left,right: pd.merge(left,right,on='name'), dfs)
That way, your code should work with whatever number of dataframes you want to merge.
Edit August 1, 2016: For those using Python 3: reduce
has been moved into functools
. So to use this function, you'll first need to import that module:
from functools import reduce
I put the line:
export JAVA_HOME=/usr/lib/jvm/java-7-oracle
in my ~/.bashrc
file.
/usr/lib/jvm/java7-oracle
should be a symbolic link pointing to /usr/lib/jvm/java-7-oracle-[version number here]
.
The reason it's a symbolic link is that in case there's a new version of the JVM, you don't need to update your .bashrc
file, it should automatically point to the new version.
If you want to set JAVA_HOME
environment variables globally and at system level means use should set in /etc/environment
file.
Um, why not just:
>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'
AngularJS charting plugin along with FusionCharts library to add interactive JavaScript graphs and charts to your web/mobile applications - with just a single directive. Link: http://www.fusioncharts.com/angularjs-charts/#/demos/ex1
try using IP instead of pc name. If the ip working, then it might be the name pipe is not enable. If it;s still not working then the login using windows might be disabled.
The git blame
command is used to examine the contents of a file line by line and see when each line was last modified and who the author of the modifications was.
If there was a bug in code,use it to identify who cased it,then you can blame him. Git blame is get blame(d).
If you need to know history of one line code,use git log -S"code here"
, simpler than git blame.
An implementation of Sean's answer in JavaScript:
function calcArea(poly) {_x000D_
if(!poly || poly.length < 3) return null;_x000D_
let end = poly.length - 1;_x000D_
let sum = poly[end][0]*poly[0][1] - poly[0][0]*poly[end][1];_x000D_
for(let i=0; i<end; ++i) {_x000D_
const n=i+1;_x000D_
sum += poly[i][0]*poly[n][1] - poly[n][0]*poly[i][1];_x000D_
}_x000D_
return sum;_x000D_
}_x000D_
_x000D_
function isClockwise(poly) {_x000D_
return calcArea(poly) > 0;_x000D_
}_x000D_
_x000D_
let poly = [[352,168],[305,208],[312,256],[366,287],[434,248],[416,186]];_x000D_
_x000D_
console.log(isClockwise(poly));_x000D_
_x000D_
let poly2 = [[618,186],[650,170],[701,179],[716,207],[708,247],[666,259],[637,246],[615,219]];_x000D_
_x000D_
console.log(isClockwise(poly2));
_x000D_
Pretty sure this is right. It seems to be working :-)
Those polygons look like this, if you're wondering:
Thanx, Alexander!
And to set the fancy-close button above the youtube's flash-content add 'wmode' to 'swf' parameters:
'swf': {'allowfullscreen':'true', 'wmode':'transparent'}
Here's a simple function that creates a CSS color string from RGB values ranging from 0 to 255:
function rgb(r, g, b){
return "rgb("+r+","+g+","+b+")";
}
Alternatively (to create fewer string objects), you could use array join():
function rgb(r, g, b){
return ["rgb(",r,",",g,",",b,")"].join("");
}
The above functions will only work properly if (r, g, and b) are integers between 0 and 255. If they are not integers, the color system will treat them as in the range from 0 to 1. To account for non-integer numbers, use the following:
function rgb(r, g, b){
r = Math.floor(r);
g = Math.floor(g);
b = Math.floor(b);
return ["rgb(",r,",",g,",",b,")"].join("");
}
You could also use ES6 language features:
const rgb = (r, g, b) =>
`rgb(${Math.floor(r)},${Math.floor(g)},${Math.floor(b)})`;
I managed to solved this by adding FcgidBusyTimeout . Just in case if anyone have similar issue with me.
Here is my settings on my apache.conf:
<VirtualHost *:80>
.......
<IfModule mod_fcgid.c>
FcgidBusyTimeout 3600
</IfModule>
</VirtualHost>
You can use javascript for this provblem. It's retrieve link from browser history.
<script>_x000D_
function goBack() {_x000D_
window.history.back();_x000D_
}_x000D_
</script>
_x000D_
<button onclick="goBack()">Go Back</button>
_x000D_
I went with a slightly modified version of @shibbir's answer:
// Clear form fields in a designated area of a page
$.clearFormFields = function(area) {
$(area).find('input[type="text"],input[type="email"],textarea,select').val('');
};
Called this way:
$('#my-modal').on('hidden', function(){
$.clearFormFields(this)
});
When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT
variable for you; after all, your script runs in their environment.
Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000
instead of process.env.PORT || 3000
where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.
This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;
app.listen(port);
First you must create an empty figure with the following command.
figure('name','Title of the window here');
By doing this, the newly created figure becomes you active figure. Immediately after calling a plot()
command, it will print your plotting onto this figure. So your window will have a title.
This is the code you must use:
figure('name','Title of the window here');
hold on
x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [0; 0.198669; 0.389418; 0.564642; 0.717356; 0.841471; 0.932039; 0.98545; 0.999574; 0.973848; 0.909297; 0.808496; 0.675463; 0.515501; 0.334988; 0.14112; -0.0583741; -0.255541; -0.44252; -0.611858; -0.756802; -0.871576; -0.951602; -0.993691; -0.996165; -0.958924; -0.883455; -0.772764; -0.631267; -0.464602; -0.279415; -0.0830894; 0.116549; 0.311541; 0.494113; 0.656987; 0.793668; 0.898708; 0.96792; 0.998543; 0.989358; 0.940731; 0.854599; 0.734397; 0.584917; 0.412118; 0.22289; 0.0247754; -0.174327; -0.366479; -0.544021; -0.699875; -0.827826; -0.922775; -0.980936; -0.99999; -0.979178; -0.919329; -0.822829; -0.693525; -0.536573; -0.358229; -0.165604; 0.033623; 0.23151; 0.420167; 0.592074; 0.740376; 0.859162; 0.943696; 0.990607; 0.998027; 0.965658; 0.894791; 0.788252; 0.650288; 0.486399; 0.303118; 0.107754; -0.0919069; -0.287903; -0.472422; -0.638107; -0.778352; -0.887567; -0.961397; -0.9969; -0.992659; -0.948844; -0.867202; -0.750987; -0.604833; -0.434566; -0.246974; -0.0495356];
plot(x, y, '--b');
x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [-1; -0.980133; -0.921324; -0.825918; -0.697718; -0.541836; -0.364485; -0.172736; 0.0257666; 0.223109; 0.411423; 0.583203; 0.731599; 0.850695; 0.935744; 0.983355; 0.991629; 0.960238; 0.890432; 0.784994; 0.648128; 0.48529; 0.302972; 0.108443; -0.0905427; -0.286052; -0.470289; -0.635911; -0.776314; -0.885901; -0.960303; -0.996554; -0.993208; -0.950399; -0.869833; -0.754723; -0.609658; -0.44042; -0.253757; -0.057111; 0.141679; 0.334688; 0.514221; 0.673121; 0.805052; 0.904756; 0.968256; 0.993023; 0.978068; 0.923987; 0.832937; 0.708548; 0.555778; 0.380717; 0.190346; -0.00774649; -0.205663; -0.395514; -0.56973; -0.721365; -0.844375; -0.933855; -0.986238; -0.999436; -0.972923; -0.907755; -0.806531; -0.673287; -0.513333; -0.333047; -0.139617; 0.0592467; 0.255615; 0.44166; 0.609964; 0.753818; 0.867487; 0.946439; 0.987526; 0.989111; 0.95113; 0.875097; 0.764044; 0.622398; 0.455806; 0.27091; 0.0750802; -0.123876; -0.318026; -0.499631; -0.66145; -0.797032; -0.900972; -0.969126; -0.998776];
plot(x, y, '-r');
hold off
title('My plot title');
xlabel('My x-axis title');
ylabel('My y-axis title');
Try jquery debugger plugin if you're using chrome: https://chrome.google.com/webstore/detail/jquery-debugger/dbhhnnnpaeobfddmlalhnehgclcmjimi?hl=en
To see the first n rows of DataFrame:
df.head(n) # (n=5 by default)
To see the last n rows:
df.tail(n)
Use this for windows Server 2008 r2 and Windows Server 2012 R2
Click Start, click Run, type dcomcnfg and then click OK to open Component Services.
In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, click to expand Distributed Transaction Coordinator and then click Local DTC.
Right click Local DTC and click Properties to display the Local DTC Properties dialog box.
Click the Security tab.
Check mark "Network DTC Access" checkbox.
Finally check mark "Allow Inbound" and "Allow Outbound" checkboxes.
Click Apply, OK.
A message will pop up about restarting the service.
Click OK and That's all.
Reference : https://msdn.microsoft.com/en-us/library/dd327979.aspx
Note: Sometimes the network firewall on the Local Computer or the Server could interrupt your connection so make sure you create rules to "Allow Inbound" and "Allow Outbound" connection for C:\Windows\System32\msdtc.exe
Try this:
Grid grid = new Grid(); //Define the grid
for (int i = 0; i < 36; i++) //Add 36 rows
{
ColumnDefinition columna = new ColumnDefinition()
{
Name = "Col_" + i,
Width = new GridLength(32.5),
};
grid.ColumnDefinitions.Add(columna);
}
for (int i = 0; i < 36; i++) //Add 36 columns
{
RowDefinition row = new RowDefinition();
row.Height = new GridLength(40, GridUnitType.Pixel);
grid.RowDefinitions.Add(row);
}
for (int i = 0; i < 36; i++)
{
for (int j = 0; j < 36; j++)
{
Label t1 = new Label()
{
FontSize = 10,
FontFamily = new FontFamily("consolas"),
FontWeight = FontWeights.SemiBold,
BorderBrush = Brushes.LightGray,
BorderThickness = new Thickness(2),
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
};
Grid.SetRow(t1, i);
Grid.SetColumn(t1, j);
grid.Children.Add(t1); //Add the Label Control to the Grid created
}
}
A while
loop can be simulated in cmd.exe
with:
:still_more_files
if %countfiles% leq 21 (
rem change countfile here
goto :still_more_files
)
For example, the following script:
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 0"
:more_to_process
if %x% leq 5 (
echo %x%
set /a "x = x + 1"
goto :more_to_process
)
endlocal
outputs:
0
1
2
3
4
5
For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:
@echo off
set backupdir=c:\test
:more_files_to_process
for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set num=%%x
if %num% gtr 20 (
cscript /nologo c:\deletefile.vbs %backupdir%
goto :more_files_to_process
)
That's my way:
$lines = preg_split('/[\r\n]+/', $db_text, NULL, PREG_SPLIT_NO_EMPTY);
This also will skip all empty lines too.
An IDE is an integrated development environment - a suped-up text editor with additional support for developing (such as forms designers, resource editors, etc), compiling and debugging applications. e.g Eclipse, Visual Studio.
A Library is a chunk of code that you can call from your own code, to help you do things more quickly/easily. For example, a Bitmap Processing library will provide facilities for loading and manipulating bitmap images, saving you having to write all that code for yourself. Typically a library will only offer one area of functionality (processing images or operating on zip files)
An API (application programming interface) is a term meaning the functions/methods in a library that you can call to ask it to do things for you - the interface to the library.
An SDK (software development kit) is a library or group of libraries (often with extra tool applications, data files and sample code) that aid you in developing code that uses a particular system (e.g. extension code for using features of an operating system (Windows SDK), drawing 3D graphics via a particular system (DirectX SDK), writing add-ins to extend other applications (Office SDK), or writing code to make a device like an Arduino or a mobile phone do what you want). An SDK will still usually have a single focus.
A toolkit is like an SDK - it's a group of tools (and often code libraries) that you can use to make it easier to access a device or system... Though perhaps with more focus on providing tools and applications than on just code libraries.
A framework is a big library or group of libraries that provides many services (rather than perhaps only one focussed ability as most libraries/SDKs do). For example, .NET provides an application framework - it makes it easier to use most (if not all) of the disparate services you need (e.g. Windows, graphics, printing, communications, etc) to write a vast range of applications - so one "library" provides support for pretty much everything you need to do. Often a framework supplies a complete base on which you build your own code, rather than you building an application that consumes library code to do parts of its work.
There are of course many examples in the wild that won't exactly match these descriptions though.
import { Router } from '@angular/router';
constructor(router: Router) {
console.log(router.routerState.snapshot.url);
}
Use collect($comments_collection)
.
Else, try json_encode($comments_collection)
to convert to json.
bool isMultiple = a % b == 0;
This will be true if a is a multiple of b
I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful
See the bit twiddling hacks for many solutions. Copypasting from there is obviously simple to implement. =)
For example (on a 32-bit CPU):
uint8_t b = byte_to_reverse;
b = ((b * 0x0802LU & 0x22110LU) | (b * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
If by “simple to implement” one means something that can be done without a reference in an exam or job interview, then the safest bet is probably the inefficient copying of bits one by one into another variable in reverse order (already shown in other answers).
You can use HttpPost, there are methods to add Header to the Request.
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("header-name" , "header-value");
HttpResponse response = httpclient.execute(httpPost);
The fastest way is to do a*a
or a**2
or np.square(a)
whereas np.power(a, 2)
showed to be considerably slower.
np.power()
allows you to use different exponents for each element if instead of 2
you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2
or a*a
, which become important in cases where you have small tolerances.
I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:
In [29]: a = np.random.random((1000, 1000))
In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop
In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop
In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop
I have created a library to batch delete or update records with a round trip on EF Core 5.
Sample code as follows:
await ctx.DeleteRangeAsync(b => b.Price > n || b.AuthorName == "zack yang");
await ctx.BatchUpdate()
.Set(b => b.Price, b => b.Price + 3)
.Set(b=>b.AuthorName,b=>b.Title.Substring(3,2)+b.AuthorName.ToUpper())
.Set(b => b.PubTime, b => DateTime.Now)
.Where(b => b.Id > n || b.AuthorName.StartsWith("Zack"))
.ExecuteAsync();
Github repository: https://github.com/yangzhongke/Zack.EFCore.Batch Report: https://www.reddit.com/r/dotnetcore/comments/k1esra/how_to_batch_delete_or_update_in_entity_framework/
It's a designated initializer, introduced with the C99 standard; it allows you to initialize specific members of a struct or union object by name. my_data
is obviously a typedef for a struct
type that has a member name
of type char *
or char [N]
.
To everyone who said that this is a bad idea I want to say it is not always a bad one. Sometimes it is very boring to have to zoom out to see all the content. For example when you type on an input on iOS it zooms to get it in the center of the screen. You have to zoom out after that cause closing the keyboard does not do the work. Also I agree that when you put many I hours in making a great layout and user experience you don't want it to be messed up by a zoom.
But the other argument is valuable as well for people with vision issues. However In my opinion if you have issues with your eyes you are already using the zooming features of the system so there is no need to disturb the content.
try this
CSS add your code
.select_join option{
font-size:13px;
}
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
Short Answer:
Simple rule of thumb: Use POST to create, use PUT to update.
Long Answer:
POST:
PUT:
Longer Answer:
To understand it we need to question why PUT was required, what were the problems PUT was trying to solve that POST couldn't.
From a REST architecture's point of view there is none that matters. We could have lived without PUT as well. But from a client developer's point of view it made his/her life a lot simpler.
Prior to PUT, clients couldn't directly know the URL that the server generated or if all it had generated any or whether the data to be sent to the server is already updated or not. PUT relieved the developer of all these headaches. PUT is idempotent, PUT handles race conditions, and PUT lets the client choose the URL.