This means that Python.h
isn't in your compiler's default include paths. Have you installed it system-wide or locally? What's your OS?
You could use the -I<path>
flag to specify an additional directory where your compiler should look for headers. You will probably have to follow up with -L<path>
so that gcc can find the library you'll be linking with using -l<name>
.
You can add the id="MyID123"
at the start of the cartHTML text appends.
The first line would therefore be:
var cartHTML = '<div id="MyID123" class="soft_add_wrapper" onmouseover="setTimer();">';
-OR-
If you want the ID to be in a variable, then something like this:
var MyIDvariable = "MyID123";
var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
/* ... the rest of your code ... */
\xa0 is actually non-breaking space in Latin1 (ISO 8859-1), also chr(160). You should replace it with a space.
string = string.replace(u'\xa0', u' ')
When .encode('utf-8'), it will encode the unicode to utf-8, that means every unicode could be represented by 1 to 4 bytes. For this case, \xa0 is represented by 2 bytes \xc2\xa0.
Read up on http://docs.python.org/howto/unicode.html.
Please note: this answer in from 2012, Python has moved on, you should be able to use unicodedata.normalize
now
Although the answer that Gunter posted was correct, it is not different than what I already had posted. The problem was not the ENV
directive, but the subsequent instruction RUN export $PATH
There's no need to export the environment variables, once you have declared them via ENV
in your Dockerfile.
As soon as the RUN export ...
lines were removed, my image was built successfully
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.
"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.
"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.
You can try the Boost Tokenizer library, in particular the Escaped List Separator
If your file contains n lines, then your script has to read the file n times; so if you double the length of the file, you quadruple the amount of work your script does — and almost all of that work is simply thrown away, since all you want to do is loop over the lines in order.
Instead, the best way to loop over the lines of a file is to use a while
loop, with the condition-command being the read
builtin:
while IFS= read -r line ; do
# $line is a single line of the file, as a single string
: ... commands that use $line ...
done < input_file.txt
In your case, since you want to split the line into an array, and the read
builtin actually has special support for populating an array variable, which is what you want, you can write:
while read -r -a line ; do
echo ""${line[1]}" "${line[3]}"" >> out.txt
done < /path/of/my/text
or better yet:
while read -r -a line ; do
echo "${line[1]} ${line[3]}"
done < /path/of/my/text > out.txt
However, for what you're doing you can just use the cut
utility:
cut -d' ' -f2,4 < /path/of/my/text > out.txt
(or awk
, as Tom van der Woerdt suggests, or perl
, or even sed
).
You want an independent for loop for all the rows in grid view, then refer the below link
http://nikhilsreeni.wordpress.com/asp-net/checkbox/
Select all checkbox in Gridview
CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);
cb.Checked = ((CheckBox)sender).Checked;
}
Select checked rows to a dataset; For gridview multiple edit
CheckBox cb = default(CheckBox);
foreach (GridViewRow row in grdforumcomments.Rows)
{
cb = (CheckBox)row.FindControl("cbsel");
if (cb.Checked)
{
drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
}
}
The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :
connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
Initial Catalog=databaseName;
User ID=theuser if u use it;
Password=thepassword if u use it;
integrated security=true(if u don t use user and pass; else change it false)"
Without to knowing your instance, I could help with this one. Hope it helped
You can grant system privileges with or without the admin option. The default being without admin option.
GRANT CREATE SESSION TO username
or with admin option:
GRANT CREATE SESSION TO username WITH ADMIN OPTION
The Grantee with the ADMIN OPTION
can grant and revoke privileges to other users
Your code is correct. You can also assign one directly to the other (see Joachim Pileborg's answer).
When you later come to compare the two structs, you need to be careful to compare the structs the long way, one member at a time, instead of using memcmp
; see How do you compare structs for equality in C?
How I fixed this issue was I manually changed the code behind (from the menu View/code).
The section below should have as many number of pairs <TablixMember> </TablixMember>
as the number of rows are in the tablix. In my case I had more pairs <TablixMember> </TablixMember>
than the number of rows in the tablix. Also if you go to "Advanced mode" (to the right of "Column Groups") the number of static lines behind the "Row groups" should be equal to the number of rows in the tablix. The way to make it equal is changing the code.
<TablixRowHierarchy>
<TablixMembers>
<TablixMember>
<KeepWithGroup>After</KeepWithGroup>
<RepeatOnNewPage>true</RepeatOnNewPage>
</TablixMember>
<TablixMember>
<Group Name="Detail" />
</TablixMember>
</TablixMembers>
</TablixRowHierarchy>
Insert a "line break" or a "paragraph break" in a RichTextBox "rtb" like this:
var range = new TextRange(rtb.SelectionStart, rtb.Selection.End);
range.Start.Paragraph.ContentStart.InsertLineBreak();
range.Start.Paragraph.ContentStart.InsertParagraphBreak();
The only way to get the NewLine items is by inserting text with "\r\n" items first, and then applying more code which works on Selection and/or TextRange objects. This makes sure that the \par items are converted to \line items, are saved as desired, and are still correct when reopening the *.Rtf file. That is what I found so far after hard tries. My three code lines need to be surrounded by more code (with loops) to set the TextPointer items (.Start .End .ContentStart .ContentEnd) where the Lines and Breaks should go, which I have done with success for my purposes.
You can use the new YouTube Data API v3
if you retrieve the video, the statistics part contains the viewCount:
from the doc:
https://developers.google.com/youtube/v3/docs/videos#resource
statistics.viewCount / The number of times the video has been viewed.
You can retrieve this info in the client side, or in the server side using some of the client libraries:
https://developers.google.com/youtube/v3/libraries
And you can test the API call from the doc:
https://developers.google.com/youtube/v3/docs/videos/list
Sample:
Request:
GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Q5mHPo2yDG8&key={YOUR_API_KEY}
Authorization: Bearer ya29.AHES6ZSCT9BmIXJmjHlRlKMmVCU22UQzBPRuxzD7Zg_09hsG
X-JavaScript-User-Agent: Google APIs Explorer
Response:
200 OK
- Show headers -
{
"kind": "youtube#videoListResponse",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/dZ8K81pnD1mOCFyHQkjZNynHpYo\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"id": "Q5mHPo2yDG8",
"kind": "youtube#video",
"etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/4NA7C24hM5mprqQ3sBwI5Lo9vZE\"",
"statistics": {
"viewCount": "36575966",
"likeCount": "127569",
"dislikeCount": "5715",
"favoriteCount": "0",
"commentCount": "20317"
}
}
]
}
to indent a ul
dropdown menu, use
/* Main Level */
ul{
margin-left:10px;
}
/* Second Level */
ul ul{
margin-left:15px;
}
/* Third Level */
ul ul ul{
margin-left:20px;
}
/* and so on... */
You can indent the li
s and (if applicable) the a
s (or whatever content elements you have) as well , each with differing effects.
You could also use padding-left
instead of margin-left
, again depending on the effect you want.
Update
By default, many browsers use padding-left
to set the initial indentation. If you want to get rid of that, set padding-left: 0px;
Still, both margin-left
and padding-left
settings impact the indentation of lists in different ways. Specifically: margin-left
impacts the indentation on the outside of the element's border, whereas padding-left
affects the spacing on the inside of the element's border. (Learn more about the CSS box model here)
Setting padding-left: 0;
leaves the li's bullet icons hanging over the edge of the element's border (at least in Chrome), which may or may not be what you want.
Examples of padding-left vs margin-left and how they can work together on ul: https://jsfiddle.net/daCrosby/bb7kj8cr/1/
The hardest part is not about generating a duplicated Guid.
The hardest part is designed a database to store all of the generated ones to check if it is actually duplicated.
From WIKI:
For example, the number of random version 4 UUIDs which need to be generated in order to have a 50% probability of at least one collision is 2.71 quintillion, computed as follows:
This number is equivalent to generating 1 billion UUIDs per second for about 85 years, and a file containing this many UUIDs, at 16 bytes per UUID, would be about 45 exabytes, many times larger than the largest databases currently in existence, which are on the order of hundreds of petabytes
You have 2 choices:
1) Either specify the column name list (without the identity column).
2) SET IDENTITY_INSERT tablename ON, followed by insert statements that provide explicit values for the identity column, followed by SET IDENTITY_INSERT tablename OFF.
If you are avoiding a column name list, perhaps this 'trick' might help?:
-- Get a comma separated list of a table's column names
SELECT STUFF(
(SELECT
',' + COLUMN_NAME AS [text()]
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'TableName'
Order By Ordinal_position
FOR XML PATH('')
), 1,1, '')
Have you tried the import text function.
HTML
<ul id="list">
<li>alpha</li>
<li>gamma</li>
<li>beta</li>
</ul>
JavaScript
function sort(ul) {
var ul = document.getElementById(ul)
var liArr = ul.children
var arr = new Array()
for (var i = 0; i < liArr.length; i++) {
arr.push(liArr[i].textContent)
}
arr.sort()
arr.forEach(function(content, index) {
liArr[index].textContent = content
})
}
sort("list")
JSFiddle Demo https://jsfiddle.net/97oo61nw/
Here we are push all values of li
elements inside ul
with specific id
(which we provided as function argument) to array arr
and sort it using sort() method which is sorted alphabetical by default. After array arr
is sorted we are loop this array using forEach() method and just replace text content of all li
elements with sorted content
You could search all the option values until it finds the correct one.
var defaultVal = "Country";
$("#select").find("option").each(function () {
if ($(this).val() == defaultVal) {
$(this).prop("selected", "selected");
}
});
You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.
var model = (Fruit) bindingSource1.DataSource;
model.FruitType = "oranges";
bindingSource.ResetBindings();
Read up on BindingSource and simple data binding for Windows Forms.
function checkTime(i) {_x000D_
if (i < 10) {_x000D_
i = "0" + i;_x000D_
}_x000D_
return i;_x000D_
}_x000D_
_x000D_
function startTime() {_x000D_
var today = new Date();_x000D_
var h = today.getHours();_x000D_
var m = today.getMinutes();_x000D_
var s = today.getSeconds();_x000D_
// add a zero in front of numbers<10_x000D_
m = checkTime(m);_x000D_
s = checkTime(s);_x000D_
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;_x000D_
t = setTimeout(function() {_x000D_
startTime()_x000D_
}, 500);_x000D_
}_x000D_
startTime();
_x000D_
<div id="time"></div>
_x000D_
DEMO using javaScript only
Update
(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime() {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
COMBOBOXID.DropDownStyle = ComboBoxStyle.DropDownList;
A simular answer but i made it so you don't have to specify the type of returned pointer (note that the generic version requires C++20):
#include <iostream>
template<typename Function>
struct function_traits;
template <typename Ret, typename... Args>
struct function_traits<Ret(Args...)> {
typedef Ret(*ptr)(Args...);
};
template <typename Ret, typename... Args>
struct function_traits<Ret(*const)(Args...)> : function_traits<Ret(Args...)> {};
template <typename Cls, typename Ret, typename... Args>
struct function_traits<Ret(Cls::*)(Args...) const> : function_traits<Ret(Args...)> {};
using voidfun = void(*)();
template <typename F>
voidfun lambda_to_void_function(F lambda) {
static auto lambda_copy = lambda;
return []() {
lambda_copy();
};
}
// requires C++20
template <typename F>
auto lambda_to_pointer(F lambda) -> typename function_traits<decltype(&F::operator())>::ptr {
static auto lambda_copy = lambda;
return []<typename... Args>(Args... args) {
return lambda_copy(args...);
};
}
int main() {
int num;
void(*foo)() = lambda_to_void_function([&num]() {
num = 1234;
});
foo();
std::cout << num << std::endl; // 1234
int(*bar)(int) = lambda_to_pointer([&](int a) -> int {
num = a;
return a;
});
std::cout << bar(4321) << std::endl; // 4321
std::cout << num << std::endl; // 4321
}
Both IP and DNS can be specified with the keytool additional argument -ext SAN=dns:abc.com,ip:1.1.1.1
Example:
keytool -genkeypair -keystore <keystore> -dname "CN=test, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass <keypwd> -storepass <storepass> -keyalg RSA -alias unknown -ext SAN=dns:test.abc.com,ip:1.1.1.1
I'm running Microsoft Windows 10 Pro, Version 10.0.17763 Build 17763, and I see my .ssh folder easily at C:\Users\jrosario\.ssh without having to edit permissions or anything (though in File Explorer, I did select "Show hidden files, folders and drives"):
The keys are stored in a text file named known_hosts, which looks roughly like this:
You can use this code, it can return true
or false
:
$(document).ready(function(){_x000D_
_x000D_
//add selector of your checkbox_x000D_
_x000D_
var status=$('#IdSelector')[0].checked;_x000D_
_x000D_
console.log(status);_x000D_
_x000D_
});
_x000D_
Set IFS to ,:
sorin@sorin:~$ IFS=',' ;for i in `echo "Hello,World,Questions,Answers,bash shell,script"`; do echo $i; done
Hello
World
Questions
Answers
bash shell
script
sorin@sorin:~$
While the accepted answer isn't technically wrong, it doesn't answer the original question nor the follow up question in the comments, which was what I came here looking for. But I figured it out, so here goes.
If you want to find all Posts that have Users (and only the ones that have users) where the SQL would look like this:
SELECT * FROM posts INNER JOIN users ON posts.user_id = users.id
Which is semantically the same thing as the OP's original SQL:
SELECT * FROM posts, users WHERE posts.user_id = users.id
then this is what you want:
Posts.findAll({
include: [{
model: User,
required: true
}]
}).then(posts => {
/* ... */
});
Setting required to true is the key to producing an inner join. If you want a left outer join (where you get all Posts, regardless of whether there's a user linked) then change required to false, or leave it off since that's the default:
Posts.findAll({
include: [{
model: User,
// required: false
}]
}).then(posts => {
/* ... */
});
If you want to find all Posts belonging to users whose birth year is in 1984, you'd want:
Posts.findAll({
include: [{
model: User,
where: {year_birth: 1984}
}]
}).then(posts => {
/* ... */
});
Note that required is true by default as soon as you add a where clause in.
If you want all Posts, regardless of whether there's a user attached but if there is a user then only the ones born in 1984, then add the required field back in:
Posts.findAll({
include: [{
model: User,
where: {year_birth: 1984}
required: false,
}]
}).then(posts => {
/* ... */
});
If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in 1984, you'd do this:
Posts.findAll({
where: {name: "Sunshine"},
include: [{
model: User,
where: {year_birth: 1984}
}]
}).then(posts => {
/* ... */
});
If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in the same year that matches the post_year attribute on the post, you'd do this:
Posts.findAll({
where: {name: "Sunshine"},
include: [{
model: User,
where: ["year_birth = post_year"]
}]
}).then(posts => {
/* ... */
});
I know, it doesn't make sense that somebody would make a post the year they were born, but it's just an example - go with it. :)
I figured this out (mostly) from this doc:
If you're on a Linux system, use the awesomeness of gdb
with Python debug extensions (can be in python-dbg
or python-debuginfo
package). It also helps with multithreaded applications, GUI applications and C modules.
Run your program with:
$ gdb -ex r --args python <programname>.py [arguments]
This instructs gdb
to prepare python <programname>.py <arguments>
and r
un it.
Now when you program hangs, switch into gdb
console, press Ctr+C and execute:
(gdb) thread apply all py-list
See example session and more info here and here.
You can also use the didSet
to set the variable to a different value. This does not cause the observer to be called again as stated in Properties guide. For example, it is useful when you want to limit the value as below:
let minValue = 1
var value = 1 {
didSet {
if value < minValue {
value = minValue
}
}
}
value = -10 // value is minValue now.
I'm going to add a somewhat longer and more detailed explanation of the steps to take to solve this problem. I apologize if it's too long.
I'll start out with the base you've given and use it to define a couple of terms that I'll use for the rest of this post. This will be the base table:
select * from history;
+--------+----------+-----------+
| hostid | itemname | itemvalue |
+--------+----------+-----------+
| 1 | A | 10 |
| 1 | B | 3 |
| 2 | A | 9 |
| 2 | C | 40 |
+--------+----------+-----------+
This will be our goal, the pretty pivot table:
select * from history_itemvalue_pivot;
+--------+------+------+------+
| hostid | A | B | C |
+--------+------+------+------+
| 1 | 10 | 3 | 0 |
| 2 | 9 | 0 | 40 |
+--------+------+------+------+
Values in the history.hostid
column will become y-values in the pivot table. Values in the history.itemname
column will become x-values (for obvious reasons).
When I have to solve the problem of creating a pivot table, I tackle it using a three-step process (with an optional fourth step):
Let's apply these steps to your problem and see what we get:
Step 1: select columns of interest. In the desired result, hostid
provides the y-values and itemname
provides the x-values.
Step 2: extend the base table with extra columns. We typically need one column per x-value. Recall that our x-value column is itemname
:
create view history_extended as (
select
history.*,
case when itemname = "A" then itemvalue end as A,
case when itemname = "B" then itemvalue end as B,
case when itemname = "C" then itemvalue end as C
from history
);
select * from history_extended;
+--------+----------+-----------+------+------+------+
| hostid | itemname | itemvalue | A | B | C |
+--------+----------+-----------+------+------+------+
| 1 | A | 10 | 10 | NULL | NULL |
| 1 | B | 3 | NULL | 3 | NULL |
| 2 | A | 9 | 9 | NULL | NULL |
| 2 | C | 40 | NULL | NULL | 40 |
+--------+----------+-----------+------+------+------+
Note that we didn't change the number of rows -- we just added extra columns. Also note the pattern of NULL
s -- a row with itemname = "A"
has a non-null value for new column A
, and null values for the other new columns.
Step 3: group and aggregate the extended table. We need to group by hostid
, since it provides the y-values:
create view history_itemvalue_pivot as (
select
hostid,
sum(A) as A,
sum(B) as B,
sum(C) as C
from history_extended
group by hostid
);
select * from history_itemvalue_pivot;
+--------+------+------+------+
| hostid | A | B | C |
+--------+------+------+------+
| 1 | 10 | 3 | NULL |
| 2 | 9 | NULL | 40 |
+--------+------+------+------+
(Note that we now have one row per y-value.) Okay, we're almost there! We just need to get rid of those ugly NULL
s.
Step 4: prettify. We're just going to replace any null values with zeroes so the result set is nicer to look at:
create view history_itemvalue_pivot_pretty as (
select
hostid,
coalesce(A, 0) as A,
coalesce(B, 0) as B,
coalesce(C, 0) as C
from history_itemvalue_pivot
);
select * from history_itemvalue_pivot_pretty;
+--------+------+------+------+
| hostid | A | B | C |
+--------+------+------+------+
| 1 | 10 | 3 | 0 |
| 2 | 9 | 0 | 40 |
+--------+------+------+------+
And we're done -- we've built a nice, pretty pivot table using MySQL.
Considerations when applying this procedure:
itemvalue
in this exampleNULL
, but it could also be 0
or ""
, depending on your exact situationsum
, but count
and max
are also often used (max
is often used when building one-row "objects" that had been spread across many rows)group by
clause (and don't forget to select
them)Known limitations:
Seba Illingworth's code, In case you need time in your file name (it gives 2014-02-21_1035)
echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=.
echo.
sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause
From MSDN
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://contoso.com/PostAccepter.aspx ");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
Take into account that the information must be sent in the format key1=value1&key2=value2
You can also use MyGeneration (free tool) to write your own sql generated scripts. There is a "insert into" script for SQL Server included in MyGeneration, which can be easily changed to run under Oracle.
As you see in an error UseCalls.java:27: error: cannot find symbol
return String.parseString(input);
there is no method parseString
in String
class. There is no need to parse it as long as JOptionPane.showInputDialog(prompt);
already returns a string.
If you have more as one Project in your Project Map use THE SAME hard coded PathFile PDB Name in all your Sub-Projects:
Use e.g.
D:\Visual Studio Projects\my_app\MyFile.pdb
Dont use e.g.
$(IntDir)\MyFile.pdb
in all the Sub-Projects !!!
= Compiler Param /Fd
We are used to
class ClassTypeA implements InterfaceTypeA {}
class ClassTypeB extends ClassTypeA {}
and any slight deviation from these rules greatly confuses us.
The syntax of a type bound is defined as
TypeBound:
extends TypeVariable
extends ClassOrInterfaceType {AdditionalBound}
(JLS 12 > 4.4. Type Variables > TypeBound
)
If we were to change it, we would surely add the implements
case
TypeBound:
extends TypeVariable
extends ClassType {AdditionalBound}
implements InterfaceType {AdditionalBound}
and end up with two identically processed clauses
ClassOrInterfaceType:
ClassType
InterfaceType
(JLS 12 > 4.3. Reference Types and Values > ClassOrInterfaceType
)
except we would also need to take care of implements
, which would complicate things further.
I believe it's the main reason why extends ClassOrInterfaceType
is used instead of extends ClassType
and implements InterfaceType
- to keep things simple within the complicated concept. The problem is we don't have the right word to cover both extends
and implements
and we definitely don't want to introduce one.
<T is ClassTypeA>
<T is InterfaceTypeA>
Although extends
brings some mess when it goes along with an interface, it's a broader term and it can be used to describe both cases. Try to tune your mind to the concept of extending a type (not extending a class, not implementing an interface). You restrict a type parameter by another type and it doesn't matter what that type actually is. It only matters that it's its upper bound and it's its supertype.
Mac OS apps cannot read bash environment variables. Look at this question Setting environment variables in OS X? to expose M2_HOME
to all applications including IntelliJ. You do need to restart after doing this.
I believe this won't work because you are using a console application and there is no Event Loop running. An Event Loop / Message Pump used for event handling is setup automatically when a Winforms application is created, but not for a console app.
Something like this should do the trick (However, read after the snippet for more info)
CREATE PROCEDURE GetFilteredData()
BEGIN
DECLARE bDone INT;
DECLARE var1 CHAR(16); -- or approriate type
DECLARE Var2 INT;
DECLARE Var3 VARCHAR(50);
DECLARE curs CURSOR FOR SELECT something FROM somewhere WHERE some stuff;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
DROP TEMPORARY TABLE IF EXISTS tblResults;
CREATE TEMPORARY TABLE IF NOT EXISTS tblResults (
--Fld1 type,
--Fld2 type,
--...
);
OPEN curs;
SET bDone = 0;
REPEAT
FETCH curs INTO var1,, b;
IF whatever_filtering_desired
-- here for whatever_transformation_may_be_desired
INSERT INTO tblResults VALUES (var1, var2, var3 ...);
END IF;
UNTIL bDone END REPEAT;
CLOSE curs;
SELECT * FROM tblResults;
END
A few things to consider...
Concerning the snippet above:
More generally: trying to avoid needing a cursor.
I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.
Maybe you can look into expressing the transformation and filtering desired in the context of a "plain" (declarative) SQL query.
You can set the 3rd argument of $watch
to true
:
$scope.$watch('data', function (newVal, oldVal) { /*...*/ }, true);
See https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch
Since Angular 1.1.x you can also use $watchCollection to watch shallow watch (just the "first level" of) the collection.
$scope.$watchCollection('data', function (newVal, oldVal) { /*...*/ });
See https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchCollection
You are also able to do some text manipulation inside the braces:
STRING="./folder/subfolder/file.txt"
echo ${STRING} ${STRING%/*/*}
Result:
./folder/subfolder/file.txt ./folder
or
STRING="This is a string"
echo ${STRING// /_}
Result:
This_is_a_string
You are right in "regular variables" are not needed... But it is more helpful for the debugging and to read a script.
Please check this
<a href="#" ng-click="logout(event)">Logout</a>
$scope.logout = function(event)
{
event.preventDefault();
alert("working..");
}
You can also achieve this by using following SQL with date and hour in same columns and proper date time format and ordered by date time
SELECT dateadd(hour, datediff(hour, 0, StartDate), 0) as 'ForDate',
COUNT(*) as 'Count'
FROM #Events
GROUP BY dateadd(hour, datediff(hour, 0, LogTime), 0)
ORDER BY ForDate
var objectA = {}
is a lot quicker and, in my experience, more commonly used, so it's probably best to adopt the 'standard' and save some typing.
For me what worked by combining all the posts I have read is:
1.Enable OLE automation - if not enabled
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
2.Create a folder where the generated files will be stored:
C:\GREGTESTING
3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
CREATE TABLE [dbo].[Document](
[Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Extension] [varchar](50) NULL,
[FileName] [varchar](200) NULL,
[Doc_Content] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)
Important note!
Don't forget to add in Doc_Content column the varbinary of file you want to generate!
4.Run the below script
DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max)
, @fPath varchar(max)
, @folderPath varchar(max)
--Get Data into temp Table variable so that we can iterate over it
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num] varchar(100) , [FileName] varchar(100), [Doc_Content] varBinary(max) )
INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM [dbo].[Document]
SELECT @i = COUNT(1) FROM @Doctable
WHILE @i >= 1
BEGIN
SELECT
@data = [Doc_Content],
@fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
@folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+ @fPath
--Reset the variables for next use
SELECT @data = NULL
, @init = NULL
, @fPath = NULL
, @folderPath = NULL
SET @i -= 1
END
I found those function in UIViewController.h
.
/*
These four methods can be used in a view controller's appearance callbacks to determine if it is being
presented, dismissed, or added or removed as a child view controller. For example, a view controller can
check if it is disappearing because it was dismissed or popped by asking itself in its viewWillDisappear:
method by checking the expression ([self isBeingDismissed] || [self isMovingFromParentViewController]).
*/
- (BOOL)isBeingPresented NS_AVAILABLE_IOS(5_0);
- (BOOL)isBeingDismissed NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingToParentViewController NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingFromParentViewController NS_AVAILABLE_IOS(5_0);
Maybe the above functions can detect the ViewController
is appeared or not.
New style classes may use super(Foo, self)
where Foo
is a class and self
is the instance.
super(type[, object-or-type])
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.
And in Python 3.x you can simply use super()
inside a class without any parameters.
To keep the code easy to read, you can use square brackets []
to quote the string containing '
or vice versa .
Here is another answer using Spring MVC's standaloneSetup. Using this way you can either autowire the controller class or Mock it.
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.server.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.server.MockMvc;
import org.springframework.test.web.server.setup.MockMvcBuilders;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class DemoApplicationTests {
final String BASE_URL = "http://localhost:8080/";
@Autowired
private HelloWorld controllerToTest;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(controllerToTest).build();
}
@Test
public void testSayHelloWorld() throws Exception{
//Mocking Controller
controllerToTest = mock(HelloWorld.class);
this.mockMvc.perform(get("/")
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().mimeType(MediaType.APPLICATION_JSON));
}
@Test
public void contextLoads() {
}
}
In other words, doesn't DEFAULT render NOT NULL redundant ?
No, it is not redundant. To extended accepted answer. For column col
which is nullable awe can insert NULL even when DEFAULT is defined:
CREATE TABLE t(id INT PRIMARY KEY, col INT DEFAULT 10);
-- we just inserted NULL into column with DEFAULT
INSERT INTO t(id, col) VALUES(1, NULL);
+-----+------+
| ID | COL |
+-----+------+
| 1 | null |
+-----+------+
Oracle introduced additional syntax for such scenario to overide explicit NULL with default DEFAULT ON NULL
:
CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10);
-- same as
--CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10 NOT NULL);
INSERT INTO t2(id, col) VALUES(1, NULL);
+-----+-----+
| ID | COL |
+-----+-----+
| 1 | 10 |
+-----+-----+
Here we tried to insert NULL but get default instead.
If you specify the ON NULL clause, then Oracle Database assigns the DEFAULT column value when a subsequent INSERT statement attempts to assign a value that evaluates to NULL.
When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE constraint state are implicitly specified.
cat ~/exit.scpt
command + w
to close the tab)tell application "Terminal"
set WindowNum to get window count
if WindowNum = 1 then
quit
else
tell application "System Events" to keystroke "w" using command down
end if
end tell
just like vi ~/.bashrc
or zshrc
(anything else?)
add it:
alias exit="osascript ~/exit.scpt"
Based on the above post i tried this and this worked fine I wanted to use the value of Map B as keys for Map A:
<c:if test="${not empty activityCodeMap and not empty activityDescMap}">
<c:forEach var="valueMap" items="${auditMap}">
<tr>
<td class="activity_white"><c:out value="${activityCodeMap[valueMap.value.activityCode]}"/></td>
<td class="activity_white"><c:out value="${activityDescMap[valueMap.value.activityDescCode]}"/></td>
<td class="activity_white">${valueMap.value.dateTime}</td>
</tr>
</c:forEach>
</c:if>
If you want to format your table via kable
, you can use row.names = F
kable(df, row.names = F)
Public SUB test()
Dim mdate As Date
mdate = now()
MsgBox (Round(CDbl(mdate), 0))
End SUB
Before the problem arises, try to avoid it as much as possible:
Use appropriate tools for debugging. On Unix:
-fsanitize=address
flag.Finally I would recommend the usual things. The more your program is readable, maintainable, clear and neat, the easiest it will be to debug.
You could try, div tag will auto fit height with content inside:
height: fit-content;
I face this problem 5 minutes before.
I think that a solution (with visual studio 2005) is:
myString = comboBoxTest.GetItemText(comboBoxTest.SelectedItem);
Forgive me if I am wrong.
If you want to pause then use java.util.concurrent.TimeUnit
:
TimeUnit.SECONDS.sleep(1);
To sleep for one second or
TimeUnit.MINUTES.sleep(1);
To sleep for a minute.
As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep
.
Further, sleep
isn't very flexible when it comes to control.
For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService
and either scheduleAtFixedRate
or scheduleWithFixedDelay
.
For example, to run the method myTask
every second (Java 8):
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
And in Java 7:
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
myTask();
}
}, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
SELECT
T1.ID
T1.PhoneNumber1,
T1.PhoneNumber2
T2A.SomeOtherField AS "SomeOtherField of PhoneNumber1",
T2B.SomeOtherField AS "SomeOtherField of PhoneNumber2"
FROM
Table1 T1
LEFT JOIN Table2 T2A ON T1.PhoneNumber1 = T2A.PhoneNumber
LEFT JOIN Table2 T2B ON T1.PhoneNumber2 = T2B.PhoneNumber
WHERE
T1.ID = 'FOO';
LEFT JOIN
or JOIN
also return same result. Tested success with PostgreSQL 13.1.1 .
I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.
Basically, when you have something like:
<form onsubmit="return callSomeFunction();"></form>
or
<a href="#" onclick="return callSomeFunction();"></a>`
and callSomeFunction()
returns true, then the form
or a
will submit, otherwise it won't.
Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.
a nicer way
app.filter('capitalize', function() {
return function(token) {
return token.charAt(0).toUpperCase() + token.slice(1);
}
});
Solution:
Instead of using setHeader
method I have used addHeader
.
response.addHeader("Access-Control-Allow-Origin", "*");
*
in above line will allow access to all domains, For allowing access to specific domain only:
response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
For issues related to IE<=9, Please see here.
You can easily increase your VM's RAM by modifying the memory property of config.vm.provider section in your vagrant file.
config.vm.provider "virtualbox" do |vb|
vb.memory = "4096"
end
This allocates about 4GB of RAM to your VM. You can change this according to your requirement. For example, following setting would allocate 2GB of RAM to your VM.
config.vm.provider "virtualbox" do |vb|
vb.memory = "2048"
end
Try removing the config.vm.customize ["modifyvm", :id, "--memory", 1024]
in your file, and adding the above code.
For the network configuration, try modifying the config.vm.network :hostonly, "199.188.44.20"
in your file toconfig.vm.network "private_network", ip: "199.188.44.20"
To make a function available on jQuery objects you add it to the jQuery prototype (fn is a shortcut for prototype in jQuery) like this:
jQuery.fn.myFunction = function() {
// Usually iterate over the items and return for chainability
// 'this' is the elements returns by the selector
return this.each(function() {
// do something to each item matching the selector
}
}
This is usually called a jQuery plugin.
Example - http://jsfiddle.net/VwPrm/
If iframe's source is an external domain, browsers will hide the iframe contents (Same Origin Policy). A workaround is saving the external contents in a file, for example (in PHP):
<?php
$contents = file_get_contents($external_url);
$res = file_put_contents($filename, $contents);
?>
then, get the new file content (string) and parse it to html, for example (in jquery):
$.get(file_url, function(string){
var html = $.parseHTML(string);
var contents = $(html).contents();
},'html');
Powershell version of command for git repo name:
(git config --get remote.origin.url) -replace '.*/' -replace '.git'
you can run this query:-
Delete from TableA
from
TableA a, TableB b
where a.Bid=b.Bid
AND [my filter condition]
a['Names'].str.contains('Mel')
will return an indicator vector of boolean values of size len(BabyDataSet)
Therefore, you can use
mel_count=a['Names'].str.contains('Mel').sum()
if mel_count>0:
print ("There are {m} Mels".format(m=mel_count))
Or any()
, if you don't care how many records match your query
if a['Names'].str.contains('Mel').any():
print ("Mel is there")
This could also happen if you are using CMake. If you have created a new class and you want to instantiate it, at the constructor call you will receive this error -even when the header and the cpp
files are correct- if you have not modified CMakeLists.txt
accordingly.
With CMake, every time you create a new class, before using it the header, the cpp
files and any other compilable files (like Qt ui
files) must be added to CMakeLists.txt
and then re-run cmake .
where CMakeLists.txt
is stored.
For example, in this CMakeLists.txt
file:
cmake_minimum_required(VERSION 2.8.11)
project(yourProject)
file(GLOB ImageFeatureDetector_SRC *.h *.cpp)
### Add your new files here ###
add_executable(yourProject YourNewClass.h YourNewClass.cpp otherNewFile.ui})
target_link_libraries(imagefeaturedetector ${SomeLibs})
If you are using the command file(GLOB yourProject_SRC *.h *.cpp)
then you just need to re-run cmake .
without modifying CMakeLists.txt
.
It happened to me as well. On a newly provisioned Red Hat Linux 7 server.
When I run a PHP page, i.e. info.php, I could see plain text PHP scripts instead of executing them.
I just installed PHP:
[root@localhost ~]# yum install php
And then restarted Apache HTTP Server:
[root@localhost ~]# systemctl restart httpd
The other answers here rely on the user making an initial click (on the image). This is fine for the specifics of the OP detail but not necessarily the question title.
There is an answer here explaining how to do it by firing a click event on the button ( or any element ).
This won't be secure, and it's simple to explain why:
If you hash the password on the client side and use that token instead of the password, then an attacker will be unlikely to find out what the password is.
But, the attacker doesn't need to find out what the password is, because your server isn't expecting the password any more - it's expecting the token. And the attacker does know the token because it's being sent over unencrypted HTTP!
Now, it might be possible to hack together some kind of challenge/response form of encryption which means that the same password will produce a different token each request. However, this will require that the password is stored in a decryptable format on the server, something which isn't ideal, but might be a suitable compromise.
And finally, do you really want to require users to have javascript turned on before they can log into your website?
In any case, SSL is neither an expensive or especially difficult to set up solution any more
"WARNING: The command completed successfully but no settings of '[user id here]' have been modified."
This warning means the setting was already set like what you want it to be. So it didn't change anything for that object.
public static byte[] readResoureStream(String resourcePath) throws IOException {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
InputStream in = CreateBffFile.class.getResourceAsStream(resourcePath);
//Create buffer
byte[] buffer = new byte[4096];
for (;;) {
int nread = in.read(buffer);
if (nread <= 0) {
break;
}
byteArray.write(buffer, 0, nread);
}
return byteArray.toByteArray();
}
Charset charset = StandardCharsets.UTF_8;
String content = new String(FileReader.readResoureStream("/resource/...*.txt"), charset);
String lines[] = content.split("\\n");
// This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
string searchValue=textBoxSearch.Text;
int rowIndex = 1; //this one is depending on the position of cell or column
//string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
bool valueResulet = true;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dataGridView1.Rows[rowIndex].Selected = true;
rowIndex++;
valueResulet = false;
}
}
if (valueResulet != false)
{
MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
return;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
You can try this script in the header of HTML code:
<script>
$.extend( $.mobile , {
ajaxEnabled: false,
hashListeningEnabled: false
});
</script>
Load an image with characters as texture and draw the part of that texture depending on what character you want. You can create that texture using a paint program, hardcode it or use a window component to draw to an image and retrieve that image for an exact copy of system fonts.
No need to use Glut or any other extension, just basic OpenGL operability. It gets the job done, not to mention that its been done like this for decades by professional programmers in very succesfull games and other applications.
This msdn article explains it very well with examples, "A tuple is a data structure that has a specific number and sequence of elements".
Tuples are commonly used in four ways:
To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.
To provide easy access to, and manipulation of, a data set.
To return multiple values from a method without using out parameters (in C#) or
ByRef
parameters (in Visual Basic).To pass multiple values to a method through a single parameter. For example, the
Thread.Start(Object)
method has a single parameter that lets you supply one value to the method that the thread executes at startup time. If you supply aTuple<T1, T2, T3>
object as the method argument, you can supply the thread’s startup routine with three items of data.
You can get this with .BuiltInDocmementProperties
.
For example:
Public Sub PrintDocumentProperties()
Dim oApp As New Excel.Application
Dim oWB As Workbook
Set oWB = ActiveWorkbook
Dim title As String
title = oWB.BuiltinDocumentProperties("Title")
Dim lastauthor As String
lastauthor = oWB.BuiltinDocumentProperties("Last Author")
Debug.Print title
Debug.Print lastauthor
End Sub
See this page for all the fields you can access with this: http://msdn.microsoft.com/en-us/library/bb220896.aspx
If you're trying to do this outside of the client (i.e. with Excel closed and running code from, say, a .NET program), you need to use DSOFile.dll.
For a horizontal ProgressBar, you can use a ColorFilter
, too, like this:
progressBar.getProgressDrawable().setColorFilter(
Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
Note: This modifies the appearance of all progress bars in your app. To only modify one specific progress bar, do this:
Drawable progressDrawable = progressBar.getProgressDrawable().mutate();
progressDrawable.setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
progressBar.setProgressDrawable(progressDrawable);
If progressBar is indeterminate then use getIndeterminateDrawable()
instead of getProgressDrawable()
.
Since Lollipop (API 21) you can set a progress tint:
progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));
All older answers' methods are deprecated by Google (supposedly because of troubles like this), since API 21 you need to use the Camera 2 API:
This class was deprecated in API level 21. We recommend using the new android.hardware.camera2 API for new applications.
In the newer API you have almost complete power over the Android device camera and documentation explicitly advice to
String[] getCameraIdList()
and then use obtained CameraId to open the camera:
void openCamera(String cameraId, CameraDevice.StateCallback callback, Handler handler)
99% of the frontal cameras have id = "1", and the back camera id = "0" according to this:
Non-removable cameras use integers starting at 0 for their identifiers, while removable cameras have a unique identifier for each individual device, even if they are the same model.
However, this means if device situation is rare like just 1-frontal -camera tablet you need to count how many embedded cameras you have, and place the order of the camera by its importance ("0"). So CAMERA_FACING_FRONT == 1 CAMERA_FACING_BACK == 0, which implies that the back camera is more important than frontal.
I don't know about a uniform method to identify the frontal camera on all Android devices. Simply said, the Android OS inside the device can't really find out which camera is exactly where for some reasons: maybe the only camera hardcoded id is an integer representing its importance or maybe on some devices whichever side you turn will be .. "back".
Documentation: https://developer.android.com/reference/android/hardware/camera2/package-summary.html
Explicit Examples: https://github.com/googlesamples/android-Camera2Basic
For the older API (it is not recommended, because it will not work on modern phones newer Android version and transfer is a pain-in-the-arse). Just use the same Integer CameraID (1) to open frontal camera like in this answer:
cam = Camera.open(1);
If you trust OpenCV to do the camera part:
Inside
<org.opencv.android.JavaCameraView
../>
use the following for the frontal camera:
opencv:camera_id="1"
<?php
if (isset($_POST['add'])) {
$nama = $_POST['name'];
$subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";
echo "Name: {$nama} <br />";
echo "Subscribe: {$subscribe}";
echo "<hr />";
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >
<input type="text" name="name" /> <br />
<input type="checkbox" name="subscribe" value="news" /> News <br />
<input type="submit" name="add" value="Save" />
</form>
let documentsURL = try! FileManager().url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:
let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)
NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
I am a beginner in iPhone apps and I still have an issue although I followed the above advices. It looks like POST variables are not received by my server - not sure if it comes from php or objective-c code ...
the objective-c part (coded following Chris' protocol methodo)
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.php"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:@"user_name=%@&password=%@", self.userNameField.text , self.passwordTextField.text];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(@"Response: %@",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
Below the php part :
if (isset($_POST['user_name'],$_POST['password']))
{
// Create connection
$con2=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// retrieve POST vars
$username = $_POST['user_name'];
$password = $_POST['password'];
$sql = "INSERT INTO myTable (user_name, password) VALUES ('$username', '$password')";
$retval = mysqli_query( $sql, $con2 );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysqli_close($con2);
}
}
else
{
echo "No data input in php";
}
I have been stuck the last days on this one.
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
2 GB by default. If the application is large address space aware (linked with /LARGEADDRESSAWARE), it gets 4 GB (not 3 GB, see http://msdn.microsoft.com/en-us/library/aa366778.aspx)
They're still limited to 2 GB since many application depends on the top bit of pointers to be zero.
To align some elements (headerElement) in the center and the last element to the right (headerEnd).
.headerElement {
margin-right: 5%;
margin-left: 5%;
}
.headerEnd{
margin-left: auto;
}
“Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport”(Wiki, 2017)
Example could be the following: you have a web service that accept only ASCII chars. You want to save and then transfer user’s data to some other location (API) but recipient want receive untouched data. Base64 is for that. . . The only downside is that base64 encoding will require around 33% more space than regular strings.
Another Example:: uenc = url encoded = aHR0cDovL2xvYy5tYWdlbnRvLmNvbS9hc2ljcy1tZW4tcy1nZWwta2F5YW5vLXhpaS5odG1s = http://loc.querytip.com/asics-men-s-gel-kayano-xii.html.
As you can see we can’t put char “/” in URL if we want to send last visited URL as parameter because we would break attribute/value rule for “MOD rewrite” – GET parameter.
A full example would be: “http://loc.querytip.com/checkout/cart/add/uenc/http://loc.magento.com/asics-men-s-gel-kayano-xii.html/product/93/”
As Mike way says. Change target BEFORE doing anything in your project that requires a higher target like android:installLocation="auto".
This is a bit old, but I came here because I had the same issue. I'm using JUnit but this time in a Kotlin app with mockk. I'm posting a sample here for reference and comparison with the Java counterpart:
@Test
fun demo() {
// mock a sample function
val aMock: (String) -> (String) = mockk()
// make it return the same as the argument on every invocation
every {
aMock.invoke(any())
} answers {
firstArg()
}
// test it
assertEquals("senko", aMock.invoke("senko"))
assertEquals("senko1", aMock.invoke("senko1"))
assertNotEquals("not a senko", aMock.invoke("senko"))
}
>>> from datetime import datetime
>>> a = datetime.now()
# wait a bit
>>> b = datetime.now()
>>> d = b - a # yields a timedelta object
>>> d.seconds
7
(7 will be whatever amount of time you waited a bit above)
I find datetime.datetime to be fairly useful, so if there's a complicated or awkward scenario that you've encountered, please let us know.
EDIT: Thanks to @WoLpH for pointing out that one is not always necessarily looking to refresh so frequently that the datetimes will be close together. By accounting for the days in the delta, you can handle longer timestamp discrepancies:
>>> a = datetime(2010, 12, 5)
>>> b = datetime(2010, 12, 7)
>>> d = b - a
>>> d.seconds
0
>>> d.days
2
>>> d.seconds + d.days * 86400
172800
In my case, the source and/or old object file(s) were locked (read-only) by a semi-crashed IDE or from a backup cloud service that stopped working properly. Restarting all programs and services that were associated with the folder structure solved the problem.
Config file:
worker_processes 4; # 2 * Number of CPUs
events {
worker_connections 19000; # It's the key to high performance - have a lot of connections available
}
worker_rlimit_nofile 20000; # Each connection needs a filehandle (or 2 if you are proxying)
# Total amount of users you can serve = worker_processes * worker_connections
more info: Optimizing nginx for high traffic loads
Wget 404 error also always happens if you want to download the pages from Wordpress-website by typing
wget -r http://somewebsite.com
If this website is built using Wordpress you'll get such an error:
ERROR 404: Not Found.
There's no way to mirror Wordpress-website because the website content is stored in the database and wget is not able to grab .php files. That's why you get Wget 404 error.
I know it's not this question's case, because Sam only wants to download a single picture, but it can be helpful for others.
The simplest way is to create a VBA macro that wraps that function, like so:
Function UserNameWindows() As String
UserName = Environ("USERNAME")
End Function
Then call it from the cell:
=UserNameWindows()
See this article for more details, and other ways.
I'm in the process of porting a computation-intensive Android app written in Java to iOS6. I'm doing this by porting the non-UI parts from Java to C++, writing the (minimal) UI parts in Obj-C, and wrapping the former in a (small) C interface using the standard C/C++ technique, so that it can be accessed from Obj-C, which is after all a superset of C.
This has been effective so far, and I haven't encountered any gotchas. It seems to be a legitimate approach, since Xcode lets you create C++ classes as well as Obj-C classes, and some of the official sample code does things this way. I haven't had to go outside any officially supported interfaces to do this.
There wouldn't seem to be much to gain from writing my remaining UI code in C++ even if it were possible, in view of the help given to you by the interface builder in Xcode, so my answer would be that you can use C++ for almost all your app, or as much of it as you find appropriate/convenient.
The easiest way to strip all leading 0
s is:
var s = "00test";
s = s.replace(/^0+/, "");
If just stripping a single leading 0
character, as the question implies, you could use
s = s.replace(/^0/, "");
The complete recipe here for quicker reference (note that all the steps are mandatory):
1) when instantiating Twig, pass the debug option
$twig = new Twig_Environment(
$loader, ['debug'=>true, 'cache'=>false, /*other options */]
);
2) add the debug extension
$twig->addExtension(new \Twig_Extension_Debug());
3) Use it like @Hazarapet Tunanyan pointed out
{{ dump(MyVar) }}
or
{{ dump() }}
or
{{ dump(MyObject.MyPropertyName) }}
I've found Tomcat to be rather finicky in that a running process or an open port doesn't necessarily mean it's actually handling requests. I usually try to grab a known page and compare its contents with a precomputed expected value.
If i understand right this is what your looking for.
.form-control { width: 100%; }
See demo on JSFiddle.
I'm on Ubuntu 14.04, with Bash version 4.3.11. However, I still don't have the fun built in string manipulation ${y,,}
This is what I used in my script to force capitalization:
CAPITALIZED=`echo "${y}" | tr '[a-z]' '[A-Z]'`
Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)
Code:
include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf');
$a->decodePDF();
echo $a->output();
class.pdf2text.php
Project Home
pdf2textclass
doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser
The above answer doesn't support observable interpolation (and cost me a lot of time trying to debug). The jsFiddle link in @BrandonTilley comment was the answer that worked for me, which I'll re-post here for preservation:
app.directive('backImg', function(){
return function(scope, element, attrs){
attrs.$observe('backImg', function(value) {
element.css({
'background-image': 'url(' + value +')',
'background-size' : 'cover'
});
});
};
});
Example using controller and template
Controller :
$scope.someID = ...;
/*
The advantage of using directive will also work inside an ng-repeat :
someID can be inside an array of ID's
*/
$scope.arrayOfIDs = [0,1,2,3];
Template :
Use in template like so :
<div back-img="img/service-sliders/{{someID}}/1.jpg"></div>
or like so :
<div ng-repeat="someID in arrayOfIDs" back-img="img/service-sliders/{{someID}}/1.jpg"></div>
All above solutions are correct. But, when we are talking about a normal PHP application, they have to included in every page, that it requires. A way to solve this, is through .htaccess
at root folder.
Just to hide the errors. [Put one of the followling lines in the file]
php_flag display_errors off
Or
php_value display_errors 0
Next, to set the error reporting
php_value error_reporting 30719
If you are wondering how the value 30719
came, E_ALL (32767), E_STRICT (2048) are actually constant that hold numeric value and (32767 - 2048 = 30719
)
If you are using LINUX, you can use pyALSAAUDIO. For windows, we have PyAudio and there is also a library called SoundAnalyse.
I found an example for Linux here:
#!/usr/bin/python
## This is an example of a simple sound capture script.
##
## The script opens an ALSA pcm for sound capture. Set
## various attributes of the capture, and reads in a loop,
## Then prints the volume.
##
## To test it out, run it and shout at your microphone:
import alsaaudio, time, audioop
# Open the device in nonblocking capture mode. The last argument could
# just as well have been zero for blocking mode. Then we could have
# left out the sleep call in the bottom of the loop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)
# Set attributes: Mono, 8000 Hz, 16 bit little endian samples
inp.setchannels(1)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
# The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api.
# For our purposes, it is suficcient to know that reads from the device
# will return this many frames. Each frame being 2 bytes long.
# This means that the reads below will return either 320 bytes of data
# or 0 bytes of data. The latter is possible because we are in nonblocking
# mode.
inp.setperiodsize(160)
while True:
# Read data from device
l,data = inp.read()
if l:
# Return the maximum of the absolute value of all samples in a fragment.
print audioop.max(data, 2)
time.sleep(.001)
Temporary solve this issue by a chrome plugin called CORS. Btw backend server have to send proper header to front end requests.
In many circumstances they are different names for the same thing, but in some contexts they are quite different. So it depends. Terminology is not applied in a totally consistent way across the whole software industry.
For example in the classic sockets API, a non-blocking socket is one that simply returns immediately with a special "would block" error message, whereas a blocking socket would have blocked. You have to use a separate function such as select
or poll
to find out when is a good time to retry.
But asynchronous sockets (as supported by Windows sockets), or the asynchronous IO pattern used in .NET, are more convenient. You call a method to start an operation, and the framework calls you back when it's done. Even here, there are basic differences. Asynchronous Win32 sockets "marshal" their results onto a specific GUI thread by passing Window messages, whereas .NET asynchronous IO is free-threaded (you don't know what thread your callback will be called on).
So they don't always mean the same thing. To distil the socket example, we could say:
Many ways to skin a cat... here's the way I just posted about:
:%s/[A-Z]/\L&/g
Likewise for upper case:
:%s/[a-z]/\U&/g
I prefer this way because I am using this construct (:%s/[pattern]/replace/g
) all the time so it's more natural.
When using merged columns, I got it centered by using PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS instead of PHPExcel_Style_Alignment::HORIZONTAL_CENTER
I'm hoping you are having the same problem that I had... my issue was simple: Make a fixed textarea with locked percentages inside the container (I'm new to CSS/JS/HTML, so bear with me, if I don't get the lingo correct) so that no matter the device it's displaying on, the box filling the container (the table cell) takes up the correct amount of space. Here's how I solved it:
<table width=100%>
<tr class="idbbs">
B.S.:
</tr></br>
<tr>
<textarea id="bsinpt"></textarea>
</tr>
</table>
Then CSS Looks like this...
#bsinpt
{
color: gainsboro;
float: none;
background: black;
text-align: left;
font-family: "Helvetica", "Tahoma", "Verdana", "Arial Black", sans-serif;
font-size: 100%;
position: absolute;
min-height: 60%;
min-width: 88%;
max-height: 60%;
max-width: 88%;
resize: none;
border-top-color: lightsteelblue;
border-top-width: 1px;
border-left-color: lightsteelblue;
border-left-width: 1px;
border-right-color: lightsteelblue;
border-right-width: 1px;
border-bottom-color: lightsteelblue;
border-bottom-width: 1px;
}
Sorry for the sloppy code block here, but I had to show you what's important and I don't know how to insert quoted CSS code on this website. In any case, to ensure you see what I'm talking about, the important CSS is less indented here...
What I then did (as shown here) is very specifically tweak the percentages until I found the ones that worked perfectly to fit display, no matter what device screen is used.
Granted, I think the "resize: none;" is overkill, but better safe than sorry and now the consumers will not have anyway to resize the box, nor will it matter what device they are viewing it from.
It works great.
It appears to me that the simplest way to do this is
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0
try re-install Node.js
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo apt-get install -y build-essential
and update npm
curl -L https://npmjs.com/install.sh | sudo sh
So to put it all together by using malloc()
:
int main(int argc, char** argv) {
typedef struct{
char* firstName;
char* lastName;
int day;
int month;
int year;
}STUDENT;
int numStudents=3;
int x;
STUDENT* students = malloc(numStudents * sizeof *students);
for (x = 0; x < numStudents; x++){
students[x].firstName=(char*)malloc(sizeof(char*));
scanf("%s",students[x].firstName);
students[x].lastName=(char*)malloc(sizeof(char*));
scanf("%s",students[x].lastName);
scanf("%d",&students[x].day);
scanf("%d",&students[x].month);
scanf("%d",&students[x].year);
}
for (x = 0; x < numStudents; x++)
printf("first name: %s, surname: %s, day: %d, month: %d, year: %d\n",students[x].firstName,students[x].lastName,students[x].day,students[x].month,students[x].year);
return (EXIT_SUCCESS);
}
You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:
[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
var value1 = model.SimpleProp1;
var value2 = model.SimpleProp2;
var value3 = model.ComplexProp1.SimpleProp1;
...
... return something ...
}
Another (obviously uglier) way is:
[HttpPost]
public ActionResult SubmitAction()
{
var value1 = Request["SimpleProp1"];
var value2 = Request["SimpleProp2"];
var value3 = Request["ComplexProp1.SimpleProp1"];
...
... return something ...
}
cliff.meyers's original answer that suggested using <env-entry>
will not help when using only System.getProperty()
According to the Tomcat 6.0 docs <env-entry>
is for JNDI. So that means it won't have any effect on System.getProperty()
.
With the <env-entry>
from cliff.meyers's example, the following code
System.getProperty("SMTP_PASSWORD");
will return null, not the value "abc123ftw".
According to the Tomcat 6 docs, to use <env-entry>
you'd have to write code like this to use <env-entry>
:
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our data source
String s = (String)envCtx.lookup("SMTP_PASSWORD");
Caveat: I have not actually tried the example above. But I have tried <env-entry>
with System.getProperty(), and that definitely does not work.
I was getting this exception, fixed it by adding throwIfV1Schema: false
to my DbContext constructor:
public class AppDb : IdentityDbContext<User>
{
public AppDb()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
}
turn on display errors in your ini
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
Why do you use Restrictions.like(...
)?
You should use Restrictions.eq(...)
.
Note you can also use .le
, .lt
, .ge
, .gt
on date objects as comparison operators. LIKE
operator is not appropriate for this case since LIKE
is useful when you want to match results according to partial content of a column.
Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.
For example if you have a name column with some people's full name, you can do where name like 'robert %'
so that you will return all entries with name starting with 'robert '
(%
can replace any character).
In your case you know the full content of the date you're trying to match so you shouldn't use LIKE
but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...)
.
Your date object you got with the code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);
This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.
This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".
If you want to retrieve all entries of your database from a given day, you will have to use the following code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
// Create date 17-04-2011 - 00h00
Date minDate = formatter.parse(myDate);
// Create date 18-04-2011 - 00h00
// -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
Conjunction and = Restrictions.conjunction();
// The order date must be >= 17-04-2011 - 00h00
and.add( Restrictions.ge("orderDate", minDate) );
// And the order date must be < 18-04-2011 - 00h00
and.add( Restrictions.lt("orderDate", maxDate) );
For ExpressJs router:
router.post('/login', async(req, res) => {
return res.send({redirect: '/yoururl'});
})
Client-side:
success: function (response) {
if (response.redirect) {
window.location = response.redirect
}
},
If you're like me, sometimes you want to be able to reference WordPress functions in a page which does not exist in the CMS. This way, it remains backend-specific and cannot be accidentally deleted by the client.
This is actually simple to do just by including the wp-blog-header.php
file using a PHP require()
.
Here's an example that uses a query string to generate Facebook Open Graph (OG) data for any post.
Take the example of a link like http://example.com/yourfilename.php?1
where 1
is the ID of a post we want to generate OG data for:
Now in the contents of yourfilename.php
which, for our convenience, is located in the root WordPress directory:
<?php
require( dirname( __FILE__ ) . '/wp-blog-header.php' );
$uri = $_SERVER['REQUEST_URI'];
$pieces = explode("?", $uri);
$post_id = intval( $pieces[1] );
// og:title
$title = get_the_title($post_id);
// og:description
$post = get_post($post_id);
$descr = $post->post_excerpt;
// og:image
$img_data_array = get_attached_media('image', $post_id);
$img_src = null;
$img_count = 0;
foreach ( $img_data_array as $img_data ) {
if ( $img_count > 0 ) {
break;
} else {
++$img_count;
$img_src = $img_data->guid;
}
} // end og:image
?>
<!DOCTYPE HTML>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=yes" />
<meta property="og:title" content="<?php echo $title; ?>" />
<meta property="og:description" content="<?php echo $descr; ?>" />
<meta property="og:locale" content="en_US" />
<meta property="og:type" content="website" />
<meta property="og:url" content="<?php echo site_url().'/your_redirect_path'.$post_id; ?>" />
<meta property="og:image" content="<?php echo $img_src; ?>" />
<meta property="og:site_name" content="Your Title" />
</html>
There you have it: generated sharing models for any post using the post's actual image, excerpt and title!
We could have created a special template and edited the permalink structure to do this, but since it's only needed for one page and because we don't want the client to delete it from within the CMS, this seemed like the cleaner option.
EDIT 2017: Please note that this approach is now deprecated
For WordPress installations from 2016+ please see How can I add a PHP page to WordPress? for extra parameters to include before outputting your page data to the browser.
It's simple to print an object to console in Javascript. Just use the following syntax:
console.log( object );
or
console.log('object: %O', object );
A relatively unknown method is following which prints an object or array to the console as table:
console.table( object );
I think it is important to say that this kind of logging statement only works inside a browser environment. I used this with Google Chrome. You can watch the output of your console.log calls inside the Developer Console: Open it by right click on any element in the webpage and select 'Inspect'. Select tab 'Console'.
connect to the admin database and run db.serverStatus()
:
> var status = db.serverStatus()
> status.connections
{"current" : 21, "available" : 15979}
>
You can directly get by querying
db.serverStatus().connections
To understand what does MongoDb's db.serverStatus().connections
response mean, read the documentation here.
connections
"connections" : { "current" : <num>, "available" : <num>, "totalCreated" : NumberLong(<num>) },
connections A document that reports on the status of the connections. Use these values to assess the current load and capacity requirements of the server.
connections.current The number of incoming connections from clients to the database server . This number includes the current shell session. Consider the value of connections.available to add more context to this datum.
The value will include all incoming connections including any shell connections or connections from other servers, such as replica set members or mongos instances.
connections.available The number of unused incoming connections available. Consider this value in combination with the value of connections.current to understand the connection load on the database, and the UNIX ulimit Settings document for more information about system thresholds on available connections.
connections.totalCreated Count of all incoming connections created to the server. This number includes connections that have since closed.
Navbars can utilize .navbar-toggler, .navbar-collapse, and .navbar-expand{-sm|-md|-lg|-xl} classes to change when their content collapses behind a button. In combination with other utilities, you can easily choose when to show or hide particular elements.
For navbars that never collapse, add the .navbar-expand class on the navbar. For navbars that always collapse, don’t add any .navbar-expand class.
For example :
<nav class="navbar navbar-expand-lg"></nav>
Mobile menu is showing in large screen.
Reference : https://getbootstrap.com/docs/4.0/components/navbar/
This is my version:
public String convertBytestoString(InputStream inputStream)
{
int bytes;
byte[] buffer = new byte[1024];
bytes = inputStream.read(buffer);
String stringData = new String(buffer,0,bytes);
return stringData;
}
If the jdk.tools is present in the .m2 repository. Still you get the error something like this:
missing artifact: jdk.tools.....c:.../jre/..
In the buildpath->configure build path-->Libraries.Just change JRE system library from JRE to JDK.
In python 2.6 the '%' operator performed a modulus. I don't think they changed it in 3.0.1
The modulo operator tells you the remainder of a division of two numbers.
The aim of using StringBuilder, i.e reducing memory. Is it achieved?
No, not at all. That code is not using StringBuilder
correctly. (I think you've misquoted it, though; surely there aren't quotes around id2
and table
?)
Note that the aim (usually) is to reduce memory churn rather than total memory used, to make life a bit easier on the garbage collector.
Will that take memory equal to using String like below?
No, it'll cause more memory churn than just the straight concat you quoted. (Until/unless the JVM optimizer sees that the explicit StringBuilder
in the code is unnecessary and optimizes it out, if it can.)
If the author of that code wants to use StringBuilder
(there are arguments for, but also against; see note at the end of this answer), better to do it properly (here I'm assuming there aren't actually quotes around id2
and table
):
StringBuilder sb = new StringBuilder(some_appropriate_size);
sb.append("select id1, ");
sb.append(id2);
sb.append(" from ");
sb.append(table);
return sb.toString();
Note that I've listed some_appropriate_size
in the StringBuilder
constructor, so that it starts out with enough capacity for the full content we're going to append. The default size used if you don't specify one is 16 characters, which is usually too small and results in the StringBuilder
having to do reallocations to make itself bigger (IIRC, in the Sun/Oracle JDK, it doubles itself [or more, if it knows it needs more to satisfy a specific append
] each time it runs out of room).
You may have heard that string concatenation will use a StringBuilder
under the covers if compiled with the Sun/Oracle compiler. This is true, it will use one StringBuilder
for the overall expression. But it will use the default constructor, which means in the majority of cases, it will have to do a reallocation. It's easier to read, though. Note that this is not true of a series of concatenations. So for instance, this uses one StringBuilder
:
return "prefix " + variable1 + " middle " + variable2 + " end";
It roughly translates to:
StringBuilder tmp = new StringBuilder(); // Using default 16 character size
tmp.append("prefix ");
tmp.append(variable1);
tmp.append(" middle ");
tmp.append(variable2);
tmp.append(" end");
return tmp.toString();
So that's okay, although the default constructor and subsequent reallocation(s) isn't ideal, the odds are it's good enough — and the concatenation is a lot more readable.
But that's only for a single expression. Multiple StringBuilder
s are used for this:
String s;
s = "prefix ";
s += variable1;
s += " middle ";
s += variable2;
s += " end";
return s;
That ends up becoming something like this:
String s;
StringBuilder tmp;
s = "prefix ";
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable1);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" middle ");
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(variable2);
s = tmp.toString();
tmp = new StringBuilder();
tmp.append(s);
tmp.append(" end");
s = tmp.toString();
return s;
...which is pretty ugly.
It's important to remember, though, that in all but a very few cases it doesn't matter and going with readability (which enhances maintainability) is preferred barring a specific performance issue.
Make sure not to miss the explanation of :host-context
which is directly above ::ng-deep
in the angular guide : https://angular.io/guide/component-styles. I missed it up until now and wish I'd seen it sooner.
::ng-deep
is often necessary when you didn't write the component and don't have access to its source, but :host-context
can be a very useful option when you do.
For example I have a black <h1>
header inside a component I designed, and I want the ability to change it to white when it's displayed on a dark themed background.
If I didn't have access to the source I may have to do this in the css for the parent:
.theme-dark widget-box ::ng-deep h1 { color: white; }
But instead with :host-context
you can do this inside the component.
h1
{
color: black; // default color
:host-context(.theme-dark) &
{
color: white; // color for dark-theme
}
// OR set an attribute 'outside' with [attr.theme]="'dark'"
:host-context([theme='dark']) &
{
color: white; // color for dark-theme
}
}
This will look anywhere in the component chain for .theme-dark
and apply the css to the h1 if found. This is a good alternative to relying too much on ::ng-deep
which while often necessary is somewhat of an anti-pattern.
In this case the &
is replaced by the h1
(that's how sass/scss works) so you can define your 'normal' and themed/alternative css right next to each other which is very handy.
Be careful to get the correct number of :
. For ::ng-deep
there are two and for :host-context
only one.
The JDK_HOME variable should always point to the base dir of the jdk, not the bin dir:
D:\name\name\core java\software\Java\Java_1.6.0_04_win\jdk1.6.0_04
That defined, fix your path to be
C:\Windows\System32;D:\name\name1\Softwares\Maven\apache-maven-3.0.4\bin;C:\Program Files\Notepad++\;%JDK_HOME%\bin
I managed this without adding markup, but instead using li:before
. This obviously has all the limitations of :before
(no old IE support), but it seems to work with IE8, Firefox and Chrome after some very limited testing. The bullet style is also limited by what's in unicode.
li {_x000D_
list-style: none;_x000D_
}_x000D_
li:before {_x000D_
/* For a round bullet */_x000D_
content: '\2022';_x000D_
/* For a square bullet */_x000D_
/*content:'\25A0';*/_x000D_
display: block;_x000D_
position: relative;_x000D_
max-width: 0;_x000D_
max-height: 0;_x000D_
left: -10px;_x000D_
top: 0;_x000D_
color: green;_x000D_
font-size: 20px;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo</li>_x000D_
<li>bar</li>_x000D_
</ul>
_x000D_
this did the trick for me...
string accentedStr;
byte[] tempBytes;
tempBytes = System.Text.Encoding.GetEncoding("ISO-8859-8").GetBytes(accentedStr);
string asciiStr = System.Text.Encoding.UTF8.GetString(tempBytes);
quick&short!
I guess this answer will just be lost in between all the other ones, but anyway, here goes.
I ended up on this question via Google because I wanted to check if a string
was numeric
so that I could just use double.Parse("123")
instead of the TryParse()
method.
Why? Because it's annoying to have to declare an out
variable and check the result of TryParse()
before you know if the parse failed or not. I want to use the ternary operator
to check if the string
is numerical
and then just parse it in the first ternary expression or provide a default value in the second ternary expression.
Like this:
var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;
It's just a lot cleaner than:
var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
//whatever you want to do with doubleValue
}
I made a couple extension methods
for these cases:
public static bool IsParseableAs<TInput>(this string value) {
var type = typeof(TInput);
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new[] { typeof(string), type.MakeByRefType() }, null);
if (tryParseMethod == null) return false;
var arguments = new[] { value, Activator.CreateInstance(type) };
return (bool) tryParseMethod.Invoke(null, arguments);
}
Example:
"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;
Because IsParseableAs()
tries to parse the string as the appropriate type instead of just checking if the string is "numeric" it should be pretty safe. And you can even use it for non numeric types that have a TryParse()
method, like DateTime
.
The method uses reflection and you end up calling the TryParse()
method twice which, of course, isn't as efficient, but not everything has to be fully optimized, sometimes convenience is just more important.
This method can also be used to easily parse a list of numeric strings into a list of double
or some other type with a default value without having to catch any exceptions:
var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);
public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
var type = typeof(TOutput);
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new[] { typeof(string), type.MakeByRefType() }, null);
if (tryParseMethod == null) return defaultValue;
var arguments = new object[] { value, null };
return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
}
This extension method lets you parse a string
as any type
that has a TryParse()
method and it also lets you specify a default value to return if the conversion fails.
This is better than using the ternary operator with the extension method above as it only does the conversion once. It still uses reflection though...
Examples:
"123".ParseAs<int>(10);
"abc".ParseAs<int>(25);
"123,78".ParseAs<double>(10);
"abc".ParseAs<double>(107.4);
"2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
"monday".ParseAs<DateTime>(DateTime.MinValue);
Outputs:
123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00
My situation was a bit different.
JAVA_HOME
was set properly to point to 1.7PATH
was set properly.Still my simple new Maven project was not working. What I noticed was the difference in the logs when I ran mvn clean install
. For my older Maven projects, it showed
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ oldProject---
But for my new project it showed:
[INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ newProject ---
So, I looked at the POM.xml
and noticed this thing in the old project's POM:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
Basically, this plugin tells which compiler version to use for compilation. Just added it to the new project's POM.xml
and things worked.
Hope it is useful to someone.
This is such a common problem, especially in GUI applications, that I'm surprised there isn't a BCL class to do this out of the box. Here's how I do it.
public static class ReflectiveEnumerator
{
static ReflectiveEnumerator() { }
public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>
{
List<T> objects = new List<T>();
foreach (Type type in
Assembly.GetAssembly(typeof(T)).GetTypes()
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
{
objects.Add((T)Activator.CreateInstance(type, constructorArgs));
}
objects.Sort();
return objects;
}
}
A few notes:
Assembly.GetAssembly(typeof(T))
because your base class might be in a different assembly. type.IsClass
and !type.IsAbstract
because it'll throw an exception if you try to instantiate an interface or abstract class.IComparable
so that they can be sorted.Another quick lookup table is available at this github page
Note : This does not consider all the containers such as, unordered_map etc. but is still great to look at. It is just a cleaner version of this
Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait,
and wait short time in every loop.
This will result in something like
max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
if [ -f /tmp/st_new.tmp ]; then
break # call results.sh outside loop
else
(( retry = retry + 1 ))
sleep 1
fi
done
if [ -f /tmp/st_new.tmp ]; then
source ../../results.sh
rm -f /tmp/st_new.tmp
else
echo Something wrong with st_new.sh
fi
git reset --hard commitId
git push <origin> <branch> --force
PS: CommitId refers the one which you want to revert back to
Encapsulation protects to collapse the internal behaviour of object/instance from external entity. So, a control should be provided to confirm that the data which is being supplied is not going to harm the internal system of instance/object to survive its existance.
Good example, Divider is a class which has two instance variable dividend and divisor and a method getDividedValue.
Can you please think, if the divisor is set to 0 then internal system/behaviour (getDivided ) will break.
So, the object internal behaviour could be protected by throwing exception through a method.
Setting locales in terminal resolved the issue for me. Open the terminal and
Check if locale settings are missing
> locale
LANG=
LC_COLLATE="C"
LC_CTYPE="UTF-8"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=
Edit ~/.profile
or ~/.bashrc
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
Run . ~/.profile
or . ~/.bashrc
to read from the file.
Open a new terminal window and check that the locales are properly set
> locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
You want the -u
option for sudo
in this case. From the man
page:
The -u (user) option causes sudo to run the specified command as a user other than root.
If you don't need to actually run it as them, you could move to their home directory with ~<user>
. As in, to move into my home directory you would use cd ~chooban
.
The most simple and shortest way to accomplish this:
/[^\p{L}\d\s@#]/u
[^...]
Match a single character not present in the list below
\p{L}
=> matches any kind of letter from any language
\d
=> matches a digit zero through nine
\s
=> matches any kind of invisible character
@#
=> @
and #
characters
Don't forget to pass the u
(unicode) flag.
If you are concerned about the speed then you could also consider WebGL.
I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:
curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX
This is called modular exponentiation(https://en.wikipedia.org/wiki/Modular_exponentiation).
Let's assume you have the following expression:
19 ^ 3 mod 7
Instead of powering 19 directly you can do the following:
(((19 mod 7) * 19) mod 7) * 19) mod 7
But this can take also a long time due to a lot of sequential multipliations and so you can multiply on squared values:
x mod N -> x ^ 2 mod N -> x ^ 4 mod -> ... x ^ 2 |log y| mod N
Modular exponentiation algorithm makes assumptions that:
x ^ y == (x ^ |y/2|) ^ 2 if y is even
x ^ y == x * ((x ^ |y/2|) ^ 2) if y is odd
And so recursive modular exponentiation algorithm will look like this in java:
/**
* Modular exponentiation algorithm
* @param x Assumption: x >= 0
* @param y Assumption: y >= 0
* @param N Assumption: N > 0
* @return x ^ y mod N
*/
public static long modExp(long x, long y, long N) {
if(y == 0)
return 1 % N;
long z = modExp(x, Math.abs(y/2), N);
if(y % 2 == 0)
return (long) ((Math.pow(z, 2)) % N);
return (long) ((x * Math.pow(z, 2)) % N);
}
Special thanks to @chux for found mistake with incorrect return value in case of y and 0 comparison.
i use this for 3.6+
import subprocess
def execute(cmd):
"""
Purpose : To execute a command and return exit status
Argument : cmd - command to execute
Return : result, exit_code
"""
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(result, error) = process.communicate()
rc = process.wait()
if rc != 0:
print ("Error: failed to execute command: ", cmd)
print (error.rstrip().decode("utf-8"))
return result.rstrip().decode("utf-8"), serror.rstrip().decode("utf-8")
# def
Note: it is invalid to provide percentages directly as <img>
width
or height
attribute unless you're using HTML 4.01 (see current spec, obsolete spec and this answer for more details). That being said, browsers will often tolerate such behaviour to support backwards-compatibility.
Those percentage widths in your 2nd example are actually applying to the container your <img>
is in, and not the image's actual size. Say you have the following markup:
<div style="width: 1000px; height: 600px;">
<img src="#" width="50%" height="50%">
</div>
Your resulting image will be 500px wide and 300px tall.
jQuery Resize
If you're trying to reduce an image to 50% of its width, you can do it with a snippet of jQuery:
$( "img" ).each( function() {
var $img = $( this );
$img.width( $img.width() * .5 );
});
Just make sure you take off any height/width = 50% attributes first.
You can use strtok()
char string[]= "abc/qwe/jkh";
char *array[10];
int i=0;
array[i] = strtok(string,"/");
while(array[i]!=NULL)
{
array[++i] = strtok(NULL,"/");
}
Use
fmt.Println(t.Format("20060102150405"))
as Go uses following constants to format date,refer here
const (
stdLongMonth = "January"
stdMonth = "Jan"
stdNumMonth = "1"
stdZeroMonth = "01"
stdLongWeekDay = "Monday"
stdWeekDay = "Mon"
stdDay = "2"
stdUnderDay = "_2"
stdZeroDay = "02"
stdHour = "15"
stdHour12 = "3"
stdZeroHour12 = "03"
stdMinute = "4"
stdZeroMinute = "04"
stdSecond = "5"
stdZeroSecond = "05"
stdLongYear = "2006"
stdYear = "06"
stdPM = "PM"
stdpm = "pm"
stdTZ = "MST"
stdISO8601TZ = "Z0700" // prints Z for UTC
stdISO8601ColonTZ = "Z07:00" // prints Z for UTC
stdNumTZ = "-0700" // always numeric
stdNumShortTZ = "-07" // always numeric
stdNumColonTZ = "-07:00" // always numeric
)
Use ListObjectsRequest setting Prefix as your key.
.NET code:
public bool Exists(string key)
{
using (Amazon.S3.AmazonS3Client client = (Amazon.S3.AmazonS3Client)Amazon.AWSClientFactory.CreateAmazonS3Client(m_accessKey, m_accessSecret))
{
ListObjectsRequest request = new ListObjectsRequest();
request.BucketName = m_bucketName;
request.Prefix = key;
using (ListObjectsResponse response = client.ListObjects(request))
{
foreach (S3Object o in response.S3Objects)
{
if( o.Key == key )
return true;
}
return false;
}
}
}.
According to others said, you cannot instantiate from abstract class. but it exist 2 way to use it. 1. make another non-abstact class that extends from abstract class. So you can instantiate from new class and use the attributes and methods in abstract class.
public class MyCustomClass extends YourAbstractClass {
/// attributes, methods ,...
}
Your problem..... I think is that your for loop is encompassing all of the if
, else if
stuff - which acts like one statement, like hoang nguyen pointed out.
Change to this. Note the brackets that denote the code block on which the for loop operates and the change of the first else if
to if
.
switch(value){
case 1:
for(int i=0; i<something_in_the_array.length;i++) {
if(whatever_value==(something_in_the_array[i])) {
value=2;
break;
}
}
if(whatever_value==2) {
value=3;
break;
}
else if(whatever_value==3) {
value=4;
break;
}
break;
case 2:
code continues....
You can do it this way using INSTR:
SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;
INSTR returns zero if the substring is not in the string.
Out of interest, why don't you want to use like?
Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)
You may use events to provide your data. Code like that:
app.controller('One', ['$scope', function ($scope) {
$scope.parentmethod=function(){
$scope.$emit('one', res);// res - your data
}
}]);
app.controller('two', ['$scope', function ($scope) {
$scope.$on('updateMiniBasket', function (event, data) {
...
});
}]);
It works well in combination with zero-based indexing and len()
. For example, if you have 10 items in a list x
, they are numbered 0-9. range(len(x))
gives you 0-9.
Of course, people will tell you it's more Pythonic to do for item in x
or for index, item in enumerate(x)
rather than for i in range(len(x))
.
Slicing works that way too: foo[1:4]
is items 1-3 of foo
(keeping in mind that item 1 is actually the second item due to the zero-based indexing). For consistency, they should both work the same way.
I think of it as: "the first number you want, followed by the first number you don't want." If you want 1-10, the first number you don't want is 11, so it's range(1, 11)
.
If it becomes cumbersome in a particular application, it's easy enough to write a little helper function that adds 1 to the ending index and calls range()
.
Method to convert a List<List>
to List
:
listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());
See this example:
public class Example {
public static void main(String[] args) {
List<List<String>> listOfLists = Collections.singletonList(Arrays.asList("a", "b", "v"));
List<String> list = listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());
System.out.println("listOfLists => " + listOfLists);
System.out.println("list => " + list);
}
}
It prints:
listOfLists => [[a, b, c]]
list => [a, b, c]
In Python this can be done using List Comprehension.
list_of_lists = [['Roopa','Roopi','Tabu', 'Soudipta'],[180.0, 1231, 2112, 3112], [130], [158.2], [220.2]]
flatten = [val for sublist in list_of_lists for val in sublist]
print(flatten)
['Roopa', 'Roopi', 'Tabu', 'Soudipta', 180.0, 1231, 2112, 3112, 130, 158.2, 220.2]
If SSH access doesn't work for your EC2 instance, you need to check:
If you're using VPC instance (you've VPC ID and Subnet ID attached to your instance), check:
0.0.0.0/0
as Destination and your Internet Gateway as Target.On Linux, you may also check route info in System Log in Networking of the instance, e.g.:
++++++++++++++++++++++++++++++++++++++Net device info+++++++++++++++++++++++++++++++++++++++
+--------+------+------------------------------+---------------+-------+-------------------+
| Device | Up | Address | Mask | Scope | Hw-Address |
+--------+------+------------------------------+---------------+-------+-------------------+
| lo | True | 127.0.0.1 | 255.0.0.0 | . | . |
| eth0 | True | 172.30.2.226 | 255.255.255.0 | . | 0a:70:f3:2f:82:23 |
+--------+------+------------------------------+---------------+-------+-------------------+
++++++++++++++++++++++++++++Route IPv4 info+++++++++++++++++++++++++++++
+-------+-------------+------------+---------------+-----------+-------+
| Route | Destination | Gateway | Genmask | Interface | Flags |
+-------+-------------+------------+---------------+-----------+-------+
| 0 | 0.0.0.0 | 172.30.2.1 | 0.0.0.0 | eth0 | UG |
| 1 | 10.0.3.0 | 0.0.0.0 | 255.255.255.0 | lxcbr0 | U |
| 2 | 172.30.2.0 | 0.0.0.0 | 255.255.255.0 | eth0 | U |
+-------+-------------+------------+---------------+-----------+-------+
where UG
flags showing you your internet gateway.
For more details, check: Troubleshooting Connecting to Your Instance at Amazon docs.
SELECT
GROUP_CONCAT(DISTINCT (category))
FROM (
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(tableName.categories, ' ', numbers.n), ' ', -1) category
FROM
numbers INNER JOIN tableName
ON LENGTH(tableName.categories)>=LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1
) s;
This will return distinct values like: test1,test2,test4,test3
You can use jquery-disablescroll to solve the problem:
$window.disablescroll();
$window.disablescroll("undo");
Supports handleWheel
, handleScrollbar
, handleKeys
and scrollEventKeys
.
function.prototype.bind() accepts an Object.
It binds the calling function to the passed Object and the returns the same.
When an object is bound to a function, it means you will be able to access the values of that object from within the function using 'this' keyword.
It can also be said as,
function.prototype.bind() is used to provide/change the context of a function.
let powerOfNumber = function(number) {
let product = 1;
for(let i=1; i<= this.power; i++) {
product*=number;
}
return product;
}
let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));
let powerOfThree = powerOfNumber.bind({power:3});
alert(powerOfThree(2));
let powerOfFour = powerOfNumber.bind({power:4});
alert(powerOfFour(2));
_x000D_
Let us try to understand this.
let powerOfNumber = function(number) {
let product = 1;
for (let i = 1; i <= this.power; i++) {
product *= number;
}
return product;
}
Here, in this function, this corresponds to the object bound to the function powerOfNumber. Currently we don't have any function that is bound to this function.
Let us create a function powerOfTwo which will find the second power of a number using the above function.
let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));
Here the object {power : 2} is passed to powerOfNumber function using bind.
The bind function binds this object to the powerOfNumber() and returns the below function to powerOfTwo. Now, powerOfTwo looks like,
let powerOfNumber = function(number) {
let product = 1;
for(let i=1; i<=2; i++) {
product*=number;
}
return product;
}
Hence, powerOfTwo will find the second power.
Feel free to check this out.
This will select all rows where some_col
is NULL
or ''
(empty string)
SELECT * FROM table WHERE some_col IS NULL OR some_col = '';
This code return me GMT offset.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("Z");
String localTime = date.format(currentLocalTime);
It returns the time zone offset like this: +0530
If we use SimpleDateFormat below
DateFormat date = new SimpleDateFormat("z",Locale.getDefault());
String localTime = date.format(currentLocalTime);
It returns the time zone offset like this: GMT+05:30
I use the blow function in my GeneralUtils class, check it may be useful
public String getFieldType(Object o) {
if (o == null) {
return "Unable to identify the class name";
}
return o.getClass().getName();
}
Get yesterday date in javascript
You have to run code and check it output
var today = new Date();_x000D_
var yesterday = new Date(today);_x000D_
_x000D_
yesterday.setDate(today.getDate() - 1);_x000D_
console.log("Original Date : ",yesterday);_x000D_
_x000D_
const monthNames = [_x000D_
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"_x000D_
];_x000D_
var month = today.getMonth() + 1_x000D_
yesterday = yesterday.getDate() + ' ' + monthNames[month] + ' ' + yesterday.getFullYear()_x000D_
_x000D_
console.log("Modify Date : ",yesterday);
_x000D_
SJF are two type - i) non preemptive SJF ii)pre-emptive SJF
I have re-arranged the processes according to Arrival time. here is the non preemptive SJF
A.T= Arrival Time
B.T= Burst Time
C.T= Completion Time
T.T = Turn around Time = C.T - A.T
W.T = Waiting Time = T.T - B.T
Here is the preemptive SJF Note: each process will preempt at time a new process arrives.Then it will compare the burst times and will allocate the process which have shortest burst time. But if two process have same burst time then the process which came first that will be allocated first just like FCFS.
I prefer onKeyUp
since it only fires when the key is released. onKeyDown
, on the other hand, will fire multiple times if for some reason the user presses and holds the key. For example, when listening for "pressing" the Enter
key to make a network request, you don't want that to fire multiple times since it can be expensive.
// handler could be passed as a prop
<input type="text" onKeyUp={handleKeyPress} />
handleKeyPress(e) {
if (e.key === 'Enter') {
// do whatever
}
}
Also, stay away from keyCode
since it will be deprecated some time.
I had this same problem and I'm pretty sure I had a UIView in there at one point. Simply copying the entire table view, deleting it, and pasting it again fixed it for me.
Try to check it's size with sizeof
if 0
no elements.
The LayoutInflater class is used to instantiate the contents of layout XML files into their corresponding View objects.
In other words, it takes an XML file as input and builds the View objects from it.
You can paste the .jar file of the driver in the Java setup instead of adding it to each project that you create. Paste it in C:\Program Files\Java\jre7\lib\ext or wherever you have installed java.
After this you will find that the .jar driver is enlisted in the library folder of your created project(JRE system library) in the IDE. No need to add it repetitively.
fs.mkdir now accepts a { recursive: true }
option like so:
// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
or with a promise:
fs.promises.mkdir('/tmp/a/apple', { recursive: true }).catch(console.error);
You can solve this with a package like mkdirp or fs-extra. If you don't want to install a package, please see Tiago Peres França's answer below.
Simple definitions for overloading and overriding
Overloading (Compile Time Polymorphism):: Functions with same name and different parameters
public class A
{
public void print(int x, int y)
{
Console.WriteLine("Parent Method");
}
}
public class B : A
{
public void child()
{
Console.WriteLine("Child Method");
}
public void print(float x, float y)
{
Console.WriteLine("Overload child method");
}
}
Overriding (Run Time Polymorphism):: Functions in the extended class with same name and same parameters as in the base class, but with different behaviors.
public class A
{
public virtual void print()
{
Console.WriteLine("Parent Method");
}
}
public class B : A
{
public void child()
{
Console.WriteLine("Child Method");
}
public override void print()
{
Console.WriteLine("Overriding child method");
}
}
I came here with the same Error, though one with a different origin.
It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.
An int
type is expected, not a np.float64
Solution: Try to install numpy 1.11.0
sudo pip install -U numpy==1.11.0.
I had the same issue which brought me here.
My Issue : I was using the recommended jquery 1.12.0 version as my jquery script file.
Solution : replaced the jquery script with jquery 2.2.0 version.
That solved it for me.
I think your date data should look like 2013-08-14.
<?php
$yrdata= strtotime('2013-08-14');
echo date('M-Y', $yrdata);
?>
// Output is Aug-2013
They're spelled out pretty well in intellisense. Just type System.Collections. or System.Collections.Generics (preferred) and you'll get a list and short description of what's available.
paulsm4's answer is the correct one. If in onBackPressed()
you just return, it will disable the back button. However, I think a better approach given your use case is to flip the activity logic, i.e. make your home activity the main one, check if the user is signed in there, if not, start the sign in activity. The reason is that if you override the back button in your main activity, most users will be confused when they press back and your app does nothing.
The best way in my eyes is to use the concat()
method provided by the String
class itself.
The useage would, in your case, look like this:
String myConcatedString = cursor.getString(numcol).concat('-').
concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)));
Bash supports all sorts of wildcards and expansions.
Your exact case would be handled by brace expansion, like so:
$ rm -rf abc.log.2012-03-{14,27,28}
The above would expand to a single command with all three arguments, and be equivalent to typing:
$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28
It's important to note that this expansion is done by the shell, before rm
is even loaded.
A connection socket (fd) is presented for local address + local port + peer address + peer port. Process recv/send data via socket abstract. A listening socket (fd) is presented for local address + local listening port. Process can accept new connection via socket.
If you initialize the array with malloc
, use calloc
instead; it will zero your array for free. (Same perf obviously as memset, just less code for you.)
Even more simple, pass the $event
object to ng-click
to access the event properties. As an example:
<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>
Within your clickEvent() = function(obj) {}
function you can access the data
value like this:
var dataValue = obj.target.attributes.data.value;
Which would return exampleData
.
Here's a full jsFiddle.
To call the function you have to add ()
{this.renderIcon()}
[Update]
More recently, there is Amazon AWS ECR (Elastic Container Registry), which provides a Docker image registry to which you can control access by means of the AWS IAM access management service. ECR can also run a CVE (vulnerabilities) check on your image when you push it.
Once you create your ECR, and obtain the "URL" you can push and pull as required, subject to the permissions you create: hence making it private or public as you wish.
Pricing is by amount of data stored, and data transfer costs.
[Original answer]
If you do not want to use the Docker Hub itself, you can host your own Docker repository under Artifactory by JFrog:
https://www.jfrog.com/confluence/display/RTF/Docker+Repositories
which will then run on your own server(s).
Other hosting suppliers are available, eg CoreOS:
http://www.theregister.co.uk/2014/10/30/coreos_enterprise_registry/
which bought quay.io
For WINDOWS (shell) users with Notepad++ (checked with v6.8.3) you can correct the specific file using the option - Edit -> EOL conversion -> Unix/OSX format
And save your file again.
Edit: still works in v7.5.1 (Aug 29 2017)
u can also try from yours design
<div <%=If(True = True, "style='display: none;'", "")%> >True</div>
<div <%=If(True = False, "style='display: none;'", "")%> >False</div>
<div <%=If(Session.Item("NameExist") IsNot Nothing, "style='display: none;'", "")%> >NameExist</div>
<div <%=If(Session.Item("NameNotExist") IsNot Nothing, "style='display: none;'", "")%> >NameNotExist</div>
Output html
<div style='display: none;' > True</div>
<div >False</div>
<div style='display: none;' >NameExist</div>
<div >NameNotExist</div>
And for all input and select:
$("input[required], select[required]").attr("oninvalid", "this.setCustomValidity('Required!')");
$("input[required], select[required]").attr("oninput", "setCustomValidity('')");
KEY
is normally a synonym for INDEX
. The key attribute PRIMARY KEY
can also be specified as just KEY
when given in a column definition. This was implemented for compatibility with other database systems.
column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
...
Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
private string GetClientIpaddress()
{
string ipAddress = string.Empty;
ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipAddress == "" || ipAddress == null)
{
ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
return ipAddress;
}
else
{
return ipAddress;
}
}
In my case I had to reference a C/C++ library using P/Invoke, but I had to ensure that the memory was allocated for the output array first using fixed
:
[DllImport("my_c_func_lib.dll", CharSet = CharSet.Ansi)]
public static extern unsafe int my_c_func(double input1, double input2, double pinput3, double *outData);
public unsafe double[] GetMyUnmanagedCodeValue(double input1, double input2, double input3)
{
double[] outData = new double[24];
fixed (double* returnValue = outData)
{
my_c_func(input1, input2, pinput3, returnValue);
}
return outData;
}
For details please see: https://www.c-sharpcorner.com/article/pointers-in-C-Sharp/
One needs to be somewhat careful, since the Windows batch command:
for /f "delims=" %%a in ('command') do @set theValue=%%a
does not have the same semantics as the Unix shell statement:
theValue=`command`
Consider the case where the command fails, causing an error.
In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.
In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.
To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:
set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a
Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.
Use setInterval
instead of setTimeout
. Though in this case either will be fine but setTimeout
inherently triggers only once setInterval
continues indefinitely.
<script language="javascript">
setInterval(function(){
window.location.reload(1);
}, 30000);
</script>
As recommended by the Tensorflow GPU guide.
# Place tensors on the CPU
with tf.device('/CPU:0'):
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
# Any additional tf code placed in this block will be executed on the CPU