It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
Check out this gist. It has snippets for how to get the sharing count for the following services:
According to the Facebook documentation it's not possible to get all the fans of a page:
Although you can't get a list of all the fans of a Facebook Page, you can find out whether a specific person has liked a Page.
Try these link types actually works for me.
https://www.facebook.com/sharer.php?u=YOUR_URL_HERE
https://twitter.com/intent/tweet?url=YOUR_URL_HERE
https://plus.google.com/share?url=YOUR_URL_HERE
https://www.linkedin.com/shareArticle?mini=true&url=YOUR_URL_HERE
Regardless of what error Oracle SQL Developer may indicate in the syntax highlighting, actually running your alter
statement exactly the way you originally had it works perfectly:
ALTER TABLE TEST_PROJECT2 MODIFY proj_name VARCHAR2(300);
You only need to add parenthesis if you need to alter more than one column at once, such as:
ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(400), proj_desc VARCHAR2(400));
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Enter))
{
SendKeys.Send("{TAB}");
}
return base.ProcessCmdKey(ref msg, keyData);
}
goto the design form and View-> tab(as like picture shows) Order then you ordered all the control[That's it]
Simply fetch the data through this URL:
http://graph.facebook.com/userid_here/picture
Replace userid_here
with id of the user you want to get the photo of. You can also use HTTPS as well.
You can use the PHP's file_get_contents
function to read that URL and process the retrieved data.
Resource:
http://developers.facebook.com/docs/api
Note: In php.ini
, you need to make sure that the OpenSSL extension is enabled to use thefile_get_contents
function of PHP to read that URL.
let viewControllers = navController?.viewControllers
for aViewController in viewControllers! {
if aViewController .isKind(of: (MyClass?.classForCoder)!) {
_ = navController?.popToViewController(aViewController, animated: true)
}
}
You can use the sys.dm_tran_locks
view, which returns information about the currently active lock manager resources.
Try this
SELECT
SessionID = s.Session_id,
resource_type,
DatabaseName = DB_NAME(resource_database_id),
request_mode,
request_type,
login_time,
host_name,
program_name,
client_interface_name,
login_name,
nt_domain,
nt_user_name,
s.status,
last_request_start_time,
last_request_end_time,
s.logical_reads,
s.reads,
request_status,
request_owner_type,
objectid,
dbid,
a.number,
a.encrypted ,
a.blocking_session_id,
a.text
FROM
sys.dm_tran_locks l
JOIN sys.dm_exec_sessions s ON l.request_session_id = s.session_id
LEFT JOIN
(
SELECT *
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle)
) a ON s.session_id = a.session_id
WHERE
s.session_id > 50
In django template
Simply get current url from {{request.path}}
For getting full url with parameters {{request.get_full_path}}
Note:
You must add request
in django TEMPLATE_CONTEXT_PROCESSORS
Just for the sake of completeness you can just take the wanted data type and add brackets with the number of elements like so:
x <- character(10)
As an alternative, since you know the hostname, resolve the database server IP via hostname from the web server.
The answer that was mentioned in this post already several times I have adopted a little bit because I needed to search in only one table too:
(and also made input for the table name a bit more simpler)
ALTER PROC dbo.db_compare_SearchAllTables_sp
(
@SearchStr nvarchar(100),
@TableName nvarchar(256) = ''
)
AS
BEGIN
if PARSENAME(@TableName, 2) is null
set @TableName = 'dbo.' + QUOTENAME(@TableName, '"')
declare @results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @ColumnName nvarchar(128) = '', @SearchStr2 nvarchar(110)
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
IF @TableName <> ''
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' WITH (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
ELSE
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' WITH (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM @results
END
If you use Windows PowerShell, you could type "git" and the press F8. Continue to press F8 to cycle through all your git commands.
Or, if you use cygwin, you could do the same thing with ^R.
With the global configuration that you have defined for the exec-maven-plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<mainClass>org.dhappy.test.NeoTraverse</mainClass>
</configuration>
</plugin>
invoking mvn exec:java
on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse
.
So, to trigger the plugin from the command line, just run:
mvn exec:java
Now, if you want to execute the exec:java
goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase
to which you want to bind the goal in the execution
element:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<id>my-execution</id>
<phase>package</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>org.dhappy.test.NeoTraverse</mainClass>
</configuration>
</plugin>
With this example, your class would be executed during the package
phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.
Try this
<style>
@font-face {
font-family: Roboto Bold Condensed;
src: url(fonts/Roboto_Condensed/RobotoCondensed-Bold.ttf);
}
@font-face {
font-family:Roboto Condensed;
src: url(fonts/Roboto_Condensed/RobotoCondensed-Regular.tff);
}
div1{
font-family:Roboto Bold Condensed;
}
div2{
font-family:Roboto Condensed;
}
</style>
<div id='div1' >This is Sample text</div>
<div id='div2' >This is Sample text</div>
Another poster provided a lookup-table using a byte-wide lookup. In case you want to eke out a bit more performance (at the cost of 32K of memory instead of just 256 lookup entries) here is a solution using a 15-bit lookup table, in C# 7 for .NET.
The interesting part is initializing the table. Since it's a relatively small block that we want for the lifetime of the process, I allocate unmanaged memory for this by using Marshal.AllocHGlobal
. As you can see, for maximum performance, the whole example is written as native:
readonly static byte[] msb_tab_15;
// Initialize a table of 32768 bytes with the bit position (counting from LSB=0)
// of the highest 'set' (non-zero) bit of its corresponding 16-bit index value.
// The table is compressed by half, so use (value >> 1) for indexing.
static MyStaticInit()
{
var p = new byte[0x8000];
for (byte n = 0; n < 16; n++)
for (int c = (1 << n) >> 1, i = 0; i < c; i++)
p[c + i] = n;
msb_tab_15 = p;
}
The table requires one-time initialization via the code above. It is read-only so a single global copy can be shared for concurrent access. With this table you can quickly look up the integer log2, which is what we're looking for here, for all the various integer widths (8, 16, 32, and 64 bits).
Notice that the table entry for 0
, the sole integer for which the notion of 'highest set bit' is undefined, is given the value -1
. This distinction is necessary for proper handling of 0-valued upper words in the code below. Without further ado, here is the code for each of the various integer primitives:
ulong (64-bit) Version
/// <summary> Index of the highest set bit in 'v', or -1 for value '0' </summary>
public static int HighestOne(this ulong v)
{
if ((long)v <= 0)
return (int)((v >> 57) & 0x40) - 1; // handles cases v==0 and MSB==63
int j = /**/ (int)((0xFFFFFFFFU - v /****/) >> 58) & 0x20;
j |= /*****/ (int)((0x0000FFFFU - (v >> j)) >> 59) & 0x10;
return j + msb_tab_15[v >> (j + 1)];
}
uint (32-bit) Version
/// <summary> Index of the highest set bit in 'v', or -1 for value '0' </summary>
public static int HighestOne(uint v)
{
if ((int)v <= 0)
return (int)((v >> 26) & 0x20) - 1; // handles cases v==0 and MSB==31
int j = (int)((0x0000FFFFU - v) >> 27) & 0x10;
return j + msb_tab_15[v >> (j + 1)];
}
Various overloads for the above
public static int HighestOne(long v) => HighestOne((ulong)v);
public static int HighestOne(int v) => HighestOne((uint)v);
public static int HighestOne(ushort v) => msb_tab_15[v >> 1];
public static int HighestOne(short v) => msb_tab_15[(ushort)v >> 1];
public static int HighestOne(char ch) => msb_tab_15[ch >> 1];
public static int HighestOne(sbyte v) => msb_tab_15[(byte)v >> 1];
public static int HighestOne(byte v) => msb_tab_15[v >> 1];
This is a complete, working solution which represents the best performance on .NET 4.7.2 for numerous alternatives that I compared with a specialized performance test harness. Some of these are mentioned below. The test parameters were a uniform density of all 65 bit positions, i.e., 0 ... 31/63 plus value 0
(which produces result -1). The bits below the target index position were filled randomly. The tests were x64 only, release mode, with JIT-optimizations enabled.
That's the end of my formal answer here; what follows are some casual notes and links to source code for alternative test candidates associated with the testing I ran to validate the performance and correctness of the above code.
The version provided above above, coded as Tab16A was a consistent winner over many runs. These various candidates, in active working/scratch form, can be found here, here, and here.
1 candidates.HighestOne_Tab16A 622,496 2 candidates.HighestOne_Tab16C 628,234 3 candidates.HighestOne_Tab8A 649,146 4 candidates.HighestOne_Tab8B 656,847 5 candidates.HighestOne_Tab16B 657,147 6 candidates.HighestOne_Tab16D 659,650 7 _highest_one_bit_UNMANAGED.HighestOne_U 702,900 8 de_Bruijn.IndexOfMSB 709,672 9 _old_2.HighestOne_Old2 715,810 10 _test_A.HighestOne8 757,188 11 _old_1.HighestOne_Old1 757,925 12 _test_A.HighestOne5 (unsafe) 760,387 13 _test_B.HighestOne8 (unsafe) 763,904 14 _test_A.HighestOne3 (unsafe) 766,433 15 _test_A.HighestOne1 (unsafe) 767,321 16 _test_A.HighestOne4 (unsafe) 771,702 17 _test_B.HighestOne2 (unsafe) 772,136 18 _test_B.HighestOne1 (unsafe) 772,527 19 _test_B.HighestOne3 (unsafe) 774,140 20 _test_A.HighestOne7 (unsafe) 774,581 21 _test_B.HighestOne7 (unsafe) 775,463 22 _test_A.HighestOne2 (unsafe) 776,865 23 candidates.HighestOne_NoTab 777,698 24 _test_B.HighestOne6 (unsafe) 779,481 25 _test_A.HighestOne6 (unsafe) 781,553 26 _test_B.HighestOne4 (unsafe) 785,504 27 _test_B.HighestOne5 (unsafe) 789,797 28 _test_A.HighestOne0 (unsafe) 809,566 29 _test_B.HighestOne0 (unsafe) 814,990 30 _highest_one_bit.HighestOne 824,345 30 _bitarray_ext.RtlFindMostSignificantBit 894,069 31 candidates.HighestOne_Naive 898,865
Notable is that the terrible performance of ntdll.dll!RtlFindMostSignificantBit
via P/Invoke:
[DllImport("ntdll.dll"), SuppressUnmanagedCodeSecurity, SecuritySafeCritical]
public static extern int RtlFindMostSignificantBit(ulong ul);
It's really too bad, because here's the entire actual function:
RtlFindMostSignificantBit:
bsr rdx, rcx
mov eax,0FFFFFFFFh
movzx ecx, dl
cmovne eax,ecx
ret
I can't imagine the poor performance originating with these five lines, so the managed/native transition penalties must be to blame. I was also surprised that the testing really favored the 32KB (and 64KB) short
(16-bit) direct-lookup tables over the 128-byte (and 256-byte) byte
(8-bit) lookup tables. I thought the following would be more competitive with the 16-bit lookups, but the latter consistently outperformed this:
public static int HighestOne_Tab8A(ulong v)
{
if ((long)v <= 0)
return (int)((v >> 57) & 64) - 1;
int j;
j = /**/ (int)((0xFFFFFFFFU - v) >> 58) & 32;
j += /**/ (int)((0x0000FFFFU - (v >> j)) >> 59) & 16;
j += /**/ (int)((0x000000FFU - (v >> j)) >> 60) & 8;
return j + msb_tab_8[v >> j];
}
The last thing I'll point out is that I was quite shocked that my deBruijn method didn't fare better. This is the method that I had previously been using pervasively:
const ulong N_bsf64 = 0x07EDD5E59A4E28C2,
N_bsr64 = 0x03F79D71B4CB0A89;
readonly public static sbyte[]
bsf64 =
{
63, 0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3,
61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4,
62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21,
56, 45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5,
},
bsr64 =
{
0, 47, 1, 56, 48, 27, 2, 60, 57, 49, 41, 37, 28, 16, 3, 61,
54, 58, 35, 52, 50, 42, 21, 44, 38, 32, 29, 23, 17, 11, 4, 62,
46, 55, 26, 59, 40, 36, 15, 53, 34, 51, 20, 43, 31, 22, 10, 45,
25, 39, 14, 33, 19, 30, 9, 24, 13, 18, 8, 12, 7, 6, 5, 63,
};
public static int IndexOfLSB(ulong v) =>
v != 0 ? bsf64[((v & (ulong)-(long)v) * N_bsf64) >> 58] : -1;
public static int IndexOfMSB(ulong v)
{
if ((long)v <= 0)
return (int)((v >> 57) & 64) - 1;
v |= v >> 1; v |= v >> 2; v |= v >> 4; // does anybody know a better
v |= v >> 8; v |= v >> 16; v |= v >> 32; // way than these 12 ops?
return bsr64[(v * N_bsr64) >> 58];
}
There's much discussion of how superior and great deBruijn methods at this SO question, and I had tended to agree. My speculation is that, while both the deBruijn and direct lookup table methods (that I found to be fastest) both have to do a table lookup, and both have very minimal branching, only the deBruijn has a 64-bit multiply operation. I only tested the IndexOfMSB
functions here--not the deBruijn IndexOfLSB
--but I expect the latter to fare much better chance since it has so many fewer operations (see above), and I'll likely continue to use it for LSB.
Easy:
SELECT question_id, wm_concat(element_id) as elements
FROM questions
GROUP BY question_id;
Pesonally tested on 10g ;-)
From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
An easier tool to monitor the tracking tags is to use the Chrome extension (probably available, or the equivalent for other browsers) - Google Tag Assistant. This will show what tags are firing, what problems it has found, and even breaks out stuff like eCommerce values for easy reading. Also works with the Google Tag Manager, and can handle multiple sets of tags on the page.
I found this post because I was having the same error in Microsoft Visual C++. (Though it seems it's cause was a little different, than the above posted question.)
I had placed the file, I was trying to include, in the same directory, but it still could not be found.
My include looked like this: #include <ftdi.h>
But When I changed it to this: #include "ftdi.h"
then it found it.
The limit is dependent on both the server and the client used (and if applicable, also the proxy the server or the client is using).
Most web servers have a limit of 8192 bytes (8 KB), which is usually configurable somewhere in the server configuration. As to the client side matter, the HTTP 1.1 specification even warns about this. Here's an extract of chapter 3.2.1:
Note: Servers ought to be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations might not properly support these lengths.
The limit in Internet Explorer and Safari is about 2 KB, in Opera about 4 KB and in Firefox about 8 KB. We may thus assume that 8 KB is the maximum possible length and that 2 KB is a more affordable length to rely on at the server side and that 255 bytes is the safest length to assume that the entire URL will come in.
If the limit is exceeded in either the browser or the server, most will just truncate the characters outside the limit without any warning. Some servers however may send an HTTP 414 error.
If you need to send large data, then better use POST instead of GET. Its limit is much higher, but more dependent on the server used than the client. Usually up to around 2 GB is allowed by the average web server.
This is also configurable somewhere in the server settings. The average server will display a server-specific error/exception when the POST limit is exceeded, usually as an HTTP 500 error.
you use bad character like ? and & and etc ...
edit it to new code
see this links
also you can use urlencode
$val=urlencode('http://google.com/?var=234&key=234')
public class ConcreteClassModel : BaseModel
{
... rest of class
public bool InersectsWith(ConcreteClassModel crm)
{
return !(this.StartDateDT > crm.EndDateDT || this.EndDateDT < crm.StartDateDT);
}
}
[TestClass]
public class ConcreteClassTest
{
[TestMethod]
public void TestConcreteClass_IntersectsWith()
{
var sutPeriod = new ConcreteClassModel() { StartDateDT = new DateTime(2016, 02, 01), EndDateDT = new DateTime(2016, 02, 29) };
var periodBeforeSutPeriod = new ConcreteClassModel() { StartDateDT = new DateTime(2016, 01, 01), EndDateDT = new DateTime(2016, 01, 31) };
var periodWithEndInsideSutPeriod = new ConcreteClassModel() { StartDateDT = new DateTime(2016, 01, 10), EndDateDT = new DateTime(2016, 02, 10) };
var periodSameAsSutPeriod = new ConcreteClassModel() { StartDateDT = new DateTime(2016, 02, 01), EndDateDT = new DateTime(2016, 02, 29) };
var periodWithEndDaySameAsStartDaySutPeriod = new ConcreteClassModel() { StartDateDT = new DateTime(2016, 01, 01), EndDateDT = new DateTime(2016, 02, 01) };
var periodWithStartDaySameAsEndDaySutPeriod = new ConcreteClassModel() { StartDateDT = new DateTime(2016, 02, 29), EndDateDT = new DateTime(2016, 03, 31) };
var periodEnclosingSutPeriod = new ConcreteClassModel() { StartDateDT = new DateTime(2016, 01, 01), EndDateDT = new DateTime(2016, 03, 31) };
var periodWithinSutPeriod = new ConcreteClassModel() { StartDateDT = new DateTime(2016, 02, 010), EndDateDT = new DateTime(2016, 02, 20) };
var periodWithStartInsideSutPeriod = new ConcreteClassModel() { StartDateDT = new DateTime(2016, 02, 10), EndDateDT = new DateTime(2016, 03, 10) };
var periodAfterSutPeriod = new ConcreteClassModel() { StartDateDT = new DateTime(2016, 03, 01), EndDateDT = new DateTime(2016, 03, 31) };
Assert.IsFalse(sutPeriod.InersectsWith(periodBeforeSutPeriod), "sutPeriod.InersectsWith(periodBeforeSutPeriod) should be false");
Assert.IsTrue(sutPeriod.InersectsWith(periodWithEndInsideSutPeriod), "sutPeriod.InersectsWith(periodEndInsideSutPeriod)should be true");
Assert.IsTrue(sutPeriod.InersectsWith(periodSameAsSutPeriod), "sutPeriod.InersectsWith(periodSameAsSutPeriod) should be true");
Assert.IsTrue(sutPeriod.InersectsWith(periodWithEndDaySameAsStartDaySutPeriod), "sutPeriod.InersectsWith(periodWithEndDaySameAsStartDaySutPeriod) should be true");
Assert.IsTrue(sutPeriod.InersectsWith(periodWithStartDaySameAsEndDaySutPeriod), "sutPeriod.InersectsWith(periodWithStartDaySameAsEndDaySutPeriod) should be true");
Assert.IsTrue(sutPeriod.InersectsWith(periodEnclosingSutPeriod), "sutPeriod.InersectsWith(periodEnclosingSutPeriod) should be true");
Assert.IsTrue(sutPeriod.InersectsWith(periodWithinSutPeriod), "sutPeriod.InersectsWith(periodWithinSutPeriod) should be true");
Assert.IsTrue(sutPeriod.InersectsWith(periodWithStartInsideSutPeriod), "sutPeriod.InersectsWith(periodStartInsideSutPeriod) should be true");
Assert.IsFalse(sutPeriod.InersectsWith(periodAfterSutPeriod), "sutPeriod.InersectsWith(periodAfterSutPeriod) should be false");
}
}
Thanks for the above answers which help me code the above for an MVC project.
Note StartDateDT and EndDateDT are dateTime types
I use this function to indent my output (for example to print a tree structure). The indent
is the number of spaces before the string.
void print_with_indent(int indent, char * string)
{
printf("%*s%s", indent, "", string);
}
/*
* Child component
*/
class Child extends React.Component {
render() {
return (
<div id="child">
<h1 ref={(node) => { this.heading = node; }}>
Child
</h1>
</div>
);
}
}
/*
* Parent component
*/
class Parent extends React.Component {
componentDidMount() {
// Access child component refs via parent component instance like this
console.log(this.child.heading.getDOMNode());
}
render() {
return (
<div>
<Child
ref={(node) => { this.child = node; }}
/>
</div>
);
}
}
Most suggestions are assuming that you need to somehow destroy the last 20 commits, which is why it means "rewriting history", but you don't have to.
Just create a new branch from the commit #80 and work on that branch going forward. The other 20 commits will stay on the old orphaned branch.
If you absolutely want your new branch to have the same name, remember that branch are basically just labels. Just rename your old branch to something else, then create the new branch at commit #80 with the name you want.
The best way to remember if rows or columns come first would be writing a comment and mentioning it.
Java does not store a 2D Array as a table with specified rows and columns, it stores it as an array of arrays, like many other answers explain. So you can decide, if the first or second dimension is your row. You just have to read the array depending on that.
So, since I get confused by this all the time myself, I always write a comment that tells me, which dimension of the 2d Array is my row, and which is my column.
Many of the answers here rely on the widely-used mathematical definition [1]:
- Discriminative models directly learn the conditional predictive distribution
p(y|x)
.- Generative models learn the joint distribution
p(x,y)
(or rather,p(x|y)
andp(y)
).
- Predictive distribution
p(y|x)
can be obtained with Bayes' rule.
Although very useful, this narrow definition assumes the supervised setting, and is less handy when examining unsupervised or semi-supervised methods. It also doesn't apply to many contemporary approaches for deep generative modeling. For example, now we have implicit generative models, e.g. Generative Adversarial Networks (GANs), which are sampling-based and don't even explicitly model the probability density p(x)
(instead learning a divergence measure via the discriminator network). But we call them "generative models” since they are used to generate (high-dimensional [10]) samples.
A broader and more fundamental definition [2] seems equally fitting for this general question:
- Discriminative models learn the boundary between classes.
- So they can discriminate between different kinds of data instances.
- Generative models learn the distribution of data.
- So they can generate new data instances.
Even so, this question implies somewhat of a false dichotomy [3]. The generative-discriminative "dichotomy" is in fact a spectrum which you can even smoothly interpolate between [4].
As a consequence, this distinction gets arbitrary and confusing, especially when many popular models do not neatly fall into one or the other [5,6], or are in fact hybrid models (combinations of classically "discriminative" and "generative" models).
Nevertheless it's still a highly useful and common distinction to make. We can list some clear-cut examples of generative and discriminative models, both canonical and recent:
There is also a lot of interesting work deeply examining the generative-discriminative divide [7] and spectrum [4,8], and even transforming discriminative models into generative models [9].
In the end, definitions are constantly evolving, especially in this rapidly growing field :) It's best to take them with a pinch of salt, and maybe even redefine them for yourself and others.
1.Just Disable signing from the properties of your project it will solve issue :)
2.The other method is to purchase the certificate for your product from Digicert or Comodo or any other you want. You can get some free certificates for One pc use.
I realize that this is from over 6 years ago. However, I think there is a solution that nobody here has mentioned that is way easier than regexing
function isAJSON(string) {
try {
JSON.parse(string)
} catch(e) {
if(e instanceof SyntaxError) return false;
};
return true;
}
If you are verifying if a reference of a List or Map value of Object is an instance of a Collection, just create an instance of required List and get its class...
Set<Object> setOfIntegers = new HashSet(Arrays.asList(2, 4, 5));
assetThat(setOfIntegers).instanceOf(new ArrayList<Integer>().getClass());
Set<Object> setOfStrings = new HashSet(Arrays.asList("my", "name", "is"));
assetThat(setOfStrings).instanceOf(new ArrayList<String>().getClass());
People hate on tables for non-tabular data, but what you're asking for is exactly what tables are good at. <table width="100%">
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
String[] split = data.split("\\|",-1);
This is not the actual requirement in all the time. The Drawback of above is show below:
Scenerio 1:
When all data are present:
String data = "5|6|7||8|9|10|";
String[] split = data.split("\\|");
String[] splt = data.split("\\|",-1);
System.out.println(split.length); //output: 7
System.out.println(splt.length); //output: 8
When data is missing:
Scenerio 2: Data Missing
String data = "5|6|7||8|||";
String[] split = data.split("\\|");
String[] splt = data.split("\\|",-1);
System.out.println(split.length); //output: 5
System.out.println(splt.length); //output: 8
Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.
String data = "5|6|7||8|||";
String[] split = data.split("\\|");
String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
System.out.println(split.length); //output: 5
System.out.println(splt.length); //output:7
What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.
The following code snippet is doing it for me (lat and lng are doubles declared above this bit):
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
For all those who came here and did indeed use Date typed Variables, here is the solution I found. It does also apply to TypeScript.
I was facing this error because I tried to compare two dates using the following Method
var res = dat1.getTime() > dat2.getTime(); // or any other comparison operator
However Im sure I used a Date object, because Im using angularjs with typescript, and I got the data from a typed API call.
Im not sure why the error is raised, but I assume that because my Object was created by JSON deserialisation, possibly the getTime()
method was simply not added to the prototype.
In this case, recreating a date-Object based on your dates will fix the issue.
var res = new Date(dat1).getTime() > new Date(dat2).getTime()
I was right about this. Types will be cast to the according type but they wont be instanciated. Hence there will be a string cast to a date, which will obviously result in a runtime exception.
The trick is, if you use interfaces with non primitive only data such as dates or functions, you will need to perform a mapping after your http request.
class Details {
description: string;
date: Date;
score: number;
approved: boolean;
constructor(data: any) {
Object.assign(this, data);
}
}
and to perform the mapping:
public getDetails(id: number): Promise<Details> {
return this.http
.get<Details>(`${this.baseUrl}/api/details/${id}`)
.map(response => new Details(response.json()))
.toPromise();
}
for arrays use:
public getDetails(): Promise<Details[]> {
return this.http
.get<Details>(`${this.baseUrl}/api/details`)
.map(response => {
const array = JSON.parse(response.json()) as any[];
const details = array.map(data => new Details(data));
return details;
})
.toPromise();
}
For credits and further information about this topic follow the link.
Try this:
#!/usr/bin/env python
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
In my case I had a float value expected where xml had a null value so be sure to search for float and int data type in your xsd map
Bear in mind that using WaitForSingleObject
can get you into trouble in this scenario. The following is snipped from a tip on my website:
The problem arises because your application has a window but isn't pumping messages. If the spawned application invokes SendMessage with one of the broadcast targets (HWND_BROADCAST or HWND_TOPMOST), then the SendMessage won't return to the new application until all applications have handled the message - but your app can't handle the message because it isn't pumping messages.... so the new app locks up, so your wait never succeeds.... DEADLOCK.
If you have absolute control over the spawned application, then there are measures you can take, such as using SendMessageTimeout rather than SendMessage (e.g. for DDE initiations, if anybody is still using that). But there are situations which cause implicit SendMessage broadcasts over which you have no control, such as using the SetSysColors API for instance.
The only safe ways round this are:
MsgWaitForMultipleObjects
API.There are multiple problems with yaluna's answer, also property names are case sensitive, Installed
is the correct spelling (INSTALLED
will not work).
The table above should've been this:
Also assuming a full repair & uninstall the actual values of properties could be:
The WiX Expression Syntax documentation says:
In these expressions, you can use property names (remember that they are case sensitive).
The properties are documented at the Windows Installer Guide (e.g. Installed)
EDIT: Small correction to the first table; evidently "Uninstall" can also happen with just REMOVE
being True
.
The same problem exists in Visual Studio, here's how to fix it there:
Go to:
Tools > Options > SQL Server Tools > Transact-SQL Editor > Query Results > Results To Grid
Now click the check box to true: "Include column headers when copying or saving the results"
Mongoose and multiple database in single node.js project
use useDb to solve this issue
example
//product databse
const myDB = mongoose.connection.useDb('product');
module.exports = myDB.model("Snack", snackSchema);
//user databse
const myDB = mongoose.connection.useDb('user');
module.exports = myDB.model("User", userSchema);
What about:
<input type="button" style="width:24px;" value="A"/>
Following are the steps that will definitely work:
netstat -aon | find ":8080" | find "LISTENING"
Ctrl+Shift+Esc
)end process
NOTE : If you are running your program for the first time in Netbeans, it takes some time. So don't worry if it takes time.
This JavaScript snippet works great with jQuery and jQuery Mobile:
$.ajaxSetup({
cache: false,
headers: {
'Cache-Control': 'no-cache'
}
});
Just place it somewhere in your JavaScript code (after jQuery is loaded, and best before you do AJAX requests) and it should help.
I had installed Python via Anaconda.
By starting Visual Studio Code via Anaconda I was able to run Python programs.
However, I couldn't find any shortcut way (hotkey) to directly run .py files.
(Using the latest version as of Feb 21st 2019 with the Python extension which came with Visual Studio Code. Link: Python extension for Visual Studio Code)
The following worked:
The below is similar to what @jdhao did.
This is what I did to get the hotkey:
I made the code look like this:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Run Python File", //this is the label I gave
"type": "shell",
"command": "python",
"args": ["${file}"]
After saving it, the file changed to this:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Run Python File",
"type": "shell",
"command": "python",
"args": [
"${file}"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
Now every time that you press Ctrl + Shift + B, the Python file will automatically run and show you the output :)
I think this is a feature currently missing right now.
I noticed when I was making a guide for the keyboard shortcut differences between it and Sublime.
It's a new editor though, I wouldn't be surprised if they added it back in a new version.
from PIL import Image
import glob #use it if you want to read all of the certain file type in the directory
imgs=[]
for i in range(596,691):
imgs.append("snap"+str(i)+'.png')
print("scanned the image identified with",i)
starting and ending value+1 of the index that identifies different file names
imgs = glob.glob("*.png") #do this if you want to read all files ending with .png
my files were: snap596.png, snap597.png ...... snap690.png
frames = []
for i in imgs:
new_frame = Image.open(i)
frames.append(new_frame)
Save into a GIF file that loops forever
frames[0].save('fire3_PIL.gif', format='GIF',
append_images=frames[1:],
save_all=True,
duration=300, loop=0)
I found flickering issue with imageio and this method fixed it.
Try: sed -n '$=' filename
Also cat is unnecessary: wc -l filename
is enough in your present way.
find the main differences between JWT & OAuth
OAuth 2.0 defines a protocol & JWT defines a token format.
OAuth can use either JWT as a token format or access token which is a bearer token.
OpenID connect mostly use JWT as a token format.
Possible in CSS3: http://www.w3.org/TR/css3-writing-modes/#writing-mode
Why not change the orders of the tags? Your HTML page isn't made out of stone, are they?
The <p> will show up on a new line. Try wrapping all of your links in one single <p> tag:
<p style="text-align:center;"><a href="http//www.google.com">Search</a><a href="Contact Us">Contact Us</a></p>
I would like to echo Jason's response though sometimes you need to naively parse some Html and pull out the text content.
I needed to do this with some Html which had been created by a rich text editor, always fun and games.
In this case you may need to remove the content of some tags as well as just the tags themselves.
In my case and tags were thrown into this mix. Some one may find my (very slightly) less naive implementation a useful starting point.
/// <summary>
/// Removes all html tags from string and leaves only plain text
/// Removes content of <xml></xml> and <style></style> tags as aim to get text content not markup /meta data.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string HtmlStrip(this string input)
{
input = Regex.Replace(input, "<style>(.|\n)*?</style>",string.Empty);
input = Regex.Replace(input, @"<xml>(.|\n)*?</xml>", string.Empty); // remove all <xml></xml> tags and anything inbetween.
return Regex.Replace(input, @"<(.|\n)*?>", string.Empty); // remove any tags but not there content "<p>bob<span> johnson</span></p>" becomes "bob johnson"
}
Anwer is here How to dynamically add a style for text-align using jQuery
To enable the same edmx to access multiple databases and database providers and vise versa I use the following technique:
1) Define a ConnectionManager:
public static class ConnectionManager
{
public static string GetConnectionString(string modelName)
{
var resourceAssembly = Assembly.GetCallingAssembly();
var resources = resourceAssembly.GetManifestResourceNames();
if (!resources.Contains(modelName + ".csdl")
|| !resources.Contains(modelName + ".ssdl")
|| !resources.Contains(modelName + ".msl"))
{
throw new ApplicationException(
"Could not find connection resources required by assembly: "
+ System.Reflection.Assembly.GetCallingAssembly().FullName);
}
var provider = System.Configuration.ConfigurationManager.AppSettings.Get(
"MyModelUnitOfWorkProvider");
var providerConnectionString = System.Configuration.ConfigurationManager.AppSettings.Get(
"MyModelUnitOfWorkConnectionString");
string ssdlText;
using (var ssdlInput = resourceAssembly.GetManifestResourceStream(modelName + ".ssdl"))
{
using (var textReader = new StreamReader(ssdlInput))
{
ssdlText = textReader.ReadToEnd();
}
}
var token = "Provider=\"";
var start = ssdlText.IndexOf(token);
var end = ssdlText.IndexOf('"', start + token.Length);
var oldProvider = ssdlText.Substring(start, end + 1 - start);
ssdlText = ssdlText.Replace(oldProvider, "Provider=\"" + provider + "\"");
var tempDir = Environment.GetEnvironmentVariable("TEMP") + '\\' + resourceAssembly.GetName().Name;
Directory.CreateDirectory(tempDir);
var ssdlOutputPath = tempDir + '\\' + Guid.NewGuid() + ".ssdl";
using (var outputFile = new FileStream(ssdlOutputPath, FileMode.Create))
{
using (var outputStream = new StreamWriter(outputFile))
{
outputStream.Write(ssdlText);
}
}
var eBuilder = new EntityConnectionStringBuilder
{
Provider = provider,
Metadata = "res://*/" + modelName + ".csdl"
+ "|" + ssdlOutputPath
+ "|res://*/" + modelName + ".msl",
ProviderConnectionString = providerConnectionString
};
return eBuilder.ToString();
}
}
2) Modify the T4 that creates your ObjectContext so that it will use the ConnectionManager:
public partial class MyModelUnitOfWork : ObjectContext
{
public const string ContainerName = "MyModelUnitOfWork";
public static readonly string ConnectionString
= ConnectionManager.GetConnectionString("MyModel");
3) Add the following lines to App.Config:
<?xml version="1.0" encoding="utf-8"?> <configuration> <connectionStrings> <add name="MyModelUnitOfWork" connectionString=... /> </connectionStrings> <appSettings> <add key="MyModelUnitOfWorkConnectionString" value="data source=MyPc\SqlExpress;initial catalog=MyDB;integrated security=True;multipleactiveresultsets=True" /> <add key="MyModelUnitOfWorkProvider" value="System.Data.SqlClient" /> </appSettings> </configuration>
The ConnectionManager will replace the ConnectionString and Provider to what ever is in the App.Config.
You can use the same ConnectionManager for all ObjectContexts (so they all read the same settings from App.Config), or edit the T4 so it creates one ConnectionManager for each (in its own namespace), so that each reads separate settings.
Ibrahim's comment on the other answer is the correct way to alter an existing user's home directory.
usermod -d /newhome/username username
usermod
is the command to edit an existing user.
-d
(abbreviation for --home
) will change the user's home directory.
usermod -m -d /newhome/username username
-m
(abbreviation for --move-home
) will move the content from the user's current directory to the new directory.
I disagree on the comment posted by Hogan. Those instructions will work for IBM DB2 Mini, but it's not the case of DB2 Z/OS.
Here is an example:
Exception data: org.apache.ibatis.exceptions.PersistenceException:
The error occurred while setting parameters
SQL: INSERT INTO TABLENAME(ID_, F1_, F2_, F3_, F4_, F5_) VALUES
(?, 1, ?, ?, ?, ?),
(?, 1, ?, ?, ?, ?)
Cause: com.ibm.db2.jcc.am.SqlSyntaxErrorException:
ILLEGAL SYMBOL ",". SOME SYMBOLS THAT MIGHT BE LEGAL ARE: FOR <END-OF-STATEMENT> NOT ATOMIC. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.25.17
So I can confirm that inline comma separated bulk inserts are not working on DB2 Z/OS (maybe you could feed it some props to get it working...)
import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');
Server-side validation won't fire if client-side validation is invalid, the postback is not send.
Don't you have some other validation that doesn't pass?
The client-side validation is not executed because you specified ClientValidationFunction="TextBoxDTownCityClient"
and this will look for a function named TextBoxDTownCityClient
as validation function, but the function name should be
TextBoxDAddress1Client
(as you wrote)
Here are some differences between the two languages:
this
scope for non-static methods, and implicit class scope; JavaScript has implicit global scope.Here are some features that I think are particular strengths of JavaScript:
You can change this in preferences:
DD-MON-RR HH24:MI:SS
into the Date Format field.Here is a screenshot:
drop constraint and recreate it
alter table Persion drop CONSTRAINT <constraint_name>
alter table Persion add primary key (persionId,Pname,PMID)
edit:
you can find the constraint name by using the query below:
select OBJECT_NAME(OBJECT_ID) AS NameofConstraint
FROM sys.objects
where OBJECT_NAME(parent_object_id)='Persion'
and type_desc LIKE '%CONSTRAINT'
You mention that there are date duplicates, but it appears they're quite unique down to the precision of seconds.
Can you clarify what precision of date you start considering dates duplicate - day, hour, minute?
In any case, you'll probably want to floor your datetime field. You didn't indicate which field is preferred when removing duplicates, so this query will prefer the last name in alphabetical order.
SELECT MAX(owner_name),
--floored to the second
dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01') AS StartDate
From MyTable
GROUP BY dateadd(second,datediff(second,'2000-01-01',start_date),'2000-01-01')
They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
There is also read_csv
in Pandas, which is fast and supports non-comma column separators and automatic typing by column:
import pandas as pd
df = pd.read_csv('your_file',sep='\t')
It can be converted to a NumPy array if you prefer that type with:
import numpy as np
arr = np.array(df)
This is by far the easiest and most mature text import approach I've come across.
You cannot show an alert from a controller. There is one way communication from the client to the server.The server can therefore not tell the client to do anything. The client requests and the server gives a response.
You therefore need to use javascript when the response returns to show a messagebox of some sort.
OR
using jquery on the button that calls the controller action
<script>
$(document).ready(function(){
$("#submitButton").on("click",function()
{
alert('Your Message');
});
});
<script>
Javascript can have inheritance, check out the URL below:
http://www.webreference.com/js/column79/
Andrew
import org.apache.commons.codec.binary.Hex;
...
String hexString = Hex.encodeHexString(myString.getBytes(/* charset */));
http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html
You could use a literal eval:
>>> ast.literal_eval('0xdeadbeef')
3735928559
Or just specify the base as argument to int
:
>>> int('deadbeef', 16)
3735928559
A trick that is not well known, if you specify the base 0
to int
, then Python will attempt to determine the base from the string prefix:
>>> int("0xff", 0)
255
>>> int("0o644", 0)
420
>>> int("0b100", 0)
4
>>> int("100", 0)
100
I use GET when I'm retrieving information from a URL and POST when I'm sending information to a URL.
You can specify the shell to be used by the remote host locally.
echo 'echo "Bash version: ${BASH_VERSION}"' | ssh -q localhost bash
And be careful to (single-)quote the variables you wish to be expanded by the remote host; otherwise variable expansion will be done by your local shell!
# example for local / remote variable expansion
{
echo "[[ $- == *i* ]] && echo 'Interactive' || echo 'Not interactive'" |
ssh -q localhost bash
echo '[[ $- == *i* ]] && echo "Interactive" || echo "Not interactive"' |
ssh -q localhost bash
}
So, to check if a certain file exists on the remote host you can do the following:
host='localhost' # localhost as test case
file='~/.bash_history'
if `echo 'test -f '"${file}"' && exit 0 || exit 1' | ssh -q "${host}" sh`; then
#if `echo '[[ -f '"${file}"' ]] && exit 0 || exit 1' | ssh -q "${host}" bash`; then
echo exists
else
echo does not exist
fi
OK, LocalStorage as it's called it's local storage for your browsers, it can save up to 10MB, SessionStorage does the same, but as it's name saying, it's session based and will be deleted after closing your browser, also can save less than LocalStorage, like up to 5MB, but Cookies are very tiny data storing in your browser, that can save up 4KB and can be accessed through server or browser both...
I also created the image below to show the differences at a glance:
Applying same filter in HTML with multiple columns, just example:
variable = (array | filter : {Lookup1Id : subject.Lookup1Id, Lookup2Id : subject.Lookup2Id} : true)
Try this code it is already built in c#
int lastDay = DateTime.DaysInMonth (2014, 2);
and the first day is always 1.
Good Luck!
For this reason better is if you use this data from CSS or JSON file data, and then with this data setting new state with this.state({width: "some value",height:"some value" }); or writing code who use data of width screen data in self work if you wish responsive show images
As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
Replace backup.ab with the path to your file.
Try this
$(function(){
$("input[type='number']").prop('min',1);
$("input[type='number']").prop('max',10);
});
Although not common for getter and setter, the use of these methods can also be used in AOP/proxy pattern uses. eg for auditing variable you can use AOP to audit update of any value. Without getter/setter it's not possible except changing the code everywhere. Personaly I have never used AOP for that, but it shows one more advantage of using getter/setter.
If you have setter and getter as private it will come up in PMD checks.
The answer above is kind of correct, you can't gracefully control how much native memory a java process allocates. It depends on what your application is doing.
That said, depending on platform, you may be able to do use some mechanism, ulimit for example, to limit the size of a java or any other process.
Just don't expect it to fail gracefully if it hits that limit. Native memory allocation failures are much harder to handle than allocation failures on the java heap. There's a fairly good chance the application will crash but depending on how critical it is to the system to keep the process size down that might still suit you.
You're trying to use a dict
as a key to another dict
or in a set
. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:
>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:
>>> key = frozenset(dict_key.items())
Now you may use key
as a key in a dict
or set
:
>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}
Of course you need to repeat the exercise whenever you want to look up something using a dict:
>>> some_dict[dict_key] # Doesn't work
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())] # Works
True
If the dict
you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:
def freeze(d):
if isinstance(d, dict):
return frozenset((key, freeze(value)) for key, value in d.items())
elif isinstance(d, list):
return tuple(freeze(value) for value in d)
return d
I've always used to get a list of enum
values like this:
Array list = Enum.GetValues(typeof (SomeEnum));
The documentation of MySQL says :
CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE privilege for the database. CREATE SCHEMA is a synonym for CREATE DATABASE as of MySQL 5.0.2.
So, it would seem normal that those two instruction do the same.
How do you plan to save last saved position with RecyclerView.State
?
You can always rely on ol' good save state. Extend RecyclerView
and override onSaveInstanceState() and onRestoreInstanceState()
:
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
LayoutManager layoutManager = getLayoutManager();
if(layoutManager != null && layoutManager instanceof LinearLayoutManager){
mScrollPosition = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
}
SavedState newState = new SavedState(superState);
newState.mScrollPosition = mScrollPosition;
return newState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(state);
if(state != null && state instanceof SavedState){
mScrollPosition = ((SavedState) state).mScrollPosition;
LayoutManager layoutManager = getLayoutManager();
if(layoutManager != null){
int count = layoutManager.getItemCount();
if(mScrollPosition != RecyclerView.NO_POSITION && mScrollPosition < count){
layoutManager.scrollToPosition(mScrollPosition);
}
}
}
}
static class SavedState extends android.view.View.BaseSavedState {
public int mScrollPosition;
SavedState(Parcel in) {
super(in);
mScrollPosition = in.readInt();
}
SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(mScrollPosition);
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
It can be retrieved using REST, see Version API :
curl --header "PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK" https://gitlab.example.com/api/v4/version
For authentication see Personal access tokens documentation.
Pickle serializes a single object at a time, and reads back a single object - the pickled data is recorded in sequence on the file.
If you simply do pickle.load
you should be reading the first object serialized into the file (not the last one as you've written).
After unserializing the first object, the file-pointer is at the beggining
of the next object - if you simply call pickle.load
again, it will read that next object - do that until the end of the file.
objects = []
with (open("myfile", "rb")) as openfile:
while True:
try:
objects.append(pickle.load(openfile))
except EOFError:
break
When I run
git branch
, it only shows*master
, not the remaining two branches.
git branch
doesn't list test_branch
, because no such local branch exist in your local repo, yet. When cloning a repo, only one local branch (master
, here) is created and checked out in the resulting clone, irrespective of the number of branches that exist in the remote repo that you cloned from. At this stage, test_branch
only exist in your repo as a remote-tracking branch, not as a local branch.
And when I run
git checkout test-branch
I get the following error [...]
You must be using an "old" version of Git. In more recent versions (from v1.7.0-rc0 onwards),
If
<branch>
is not found but there does exist a tracking branch in exactly one remote (call it<remote>
) with a matching name, treat [git checkout <branch>
] as equivalent to$ git checkout -b <branch> --track <remote>/<branch>
Simply run
git checkout -b test_branch --track origin/test_branch
instead. Or update to a more recent version of Git.
This was a fun question! Another way to handle this for variable length lists is to build a function that takes full advantage of the .format
method and list unpacking. In the following example I don't use any fancy formatting, but that can easily be changed to suit your needs.
list_1 = [1,2,3,4,5,6]
list_2 = [1,2,3,4,5,6,7,8]
# Create a function that can apply formatting to lists of any length:
def ListToFormattedString(alist):
# Create a format spec for each item in the input `alist`.
# E.g., each item will be right-adjusted, field width=3.
format_list = ['{:>3}' for item in alist]
# Now join the format specs into a single string:
# E.g., '{:>3}, {:>3}, {:>3}' if the input list has 3 items.
s = ','.join(format_list)
# Now unpack the input list `alist` into the format string. Done!
return s.format(*alist)
# Example output:
>>>ListToFormattedString(list_1)
' 1, 2, 3, 4, 5, 6'
>>>ListToFormattedString(list_2)
' 1, 2, 3, 4, 5, 6, 7, 8'
The answers seems a bit over complicated. I hope I didn't misunderstand the question.
If you simply want to open a fancy box from a click to an "A" tag. Just set your html to
<a id="my_fancybox" href="#contentdiv">click me</a>
The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:
$('#my_fancybox').fancybox({
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true,
});
This will show a fancybox containing "contentdiv" when your anchor tag is clicked.
Ask Hans suggested, you can use Roslyn to dynamically create classes.
Full source:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace RoslynDemo1
{
class Program
{
static void Main(string[] args)
{
var fields = new List<Field>()
{
new Field("EmployeeID","int"),
new Field("EmployeeName","String"),
new Field("Designation","String")
};
var employeeClass = CreateClass(fields, "Employee");
dynamic employee1 = Activator.CreateInstance(employeeClass);
employee1.EmployeeID = 4213;
employee1.EmployeeName = "Wendy Tailor";
employee1.Designation = "Engineering Manager";
dynamic employee2 = Activator.CreateInstance(employeeClass);
employee2.EmployeeID = 3510;
employee2.EmployeeName = "John Gibson";
employee2.Designation = "Software Engineer";
Console.WriteLine($"{employee1.EmployeeName}");
Console.WriteLine($"{employee2.EmployeeName}");
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
public static Type CreateClass(List<Field> fields, string newClassName, string newNamespace = "Magic")
{
var fieldsCode = fields
.Select(field => $"public {field.FieldType} {field.FieldName};")
.ToString(Environment.NewLine);
var classCode = $@"
using System;
namespace {newNamespace}
{{
public class {newClassName}
{{
public {newClassName}()
{{
}}
{fieldsCode}
}}
}}
".Trim();
classCode = FormatUsingRoslyn(classCode);
var assemblies = new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
};
/*
var assemblies = AppDomain
.CurrentDomain
.GetAssemblies()
.Where(a => !string.IsNullOrEmpty(a.Location))
.Select(a => MetadataReference.CreateFromFile(a.Location))
.ToArray();
*/
var syntaxTree = CSharpSyntaxTree.ParseText(classCode);
var compilation = CSharpCompilation
.Create(newNamespace)
.AddSyntaxTrees(syntaxTree)
.AddReferences(assemblies)
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
//compilation.Emit($"C:\\Temp\\{newNamespace}.dll");
if (result.Success)
{
ms.Seek(0, SeekOrigin.Begin);
Assembly assembly = Assembly.Load(ms.ToArray());
var newTypeFullName = $"{newNamespace}.{newClassName}";
var type = assembly.GetType(newTypeFullName);
return type;
}
else
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
return null;
}
}
}
public static string FormatUsingRoslyn(string csCode)
{
var tree = CSharpSyntaxTree.ParseText(csCode);
var root = tree.GetRoot().NormalizeWhitespace();
var result = root.ToFullString();
return result;
}
}
public class Field
{
public string FieldName;
public string FieldType;
public Field(string fieldName, string fieldType)
{
FieldName = fieldName;
FieldType = fieldType;
}
}
public static class Extensions
{
public static string ToString(this IEnumerable<string> list, string separator)
{
string result = string.Join(separator, list);
return result;
}
}
}
no control over the dialog box, if you had control over the dialog box you could write obtrusive javascript code. (Its is not a good idea to use alert for anything except debugging)
You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to understand the difference between Web application context and root application context .
In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.
The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .
Read the spring reference here for spring mvc .
There are two things
Disable firewall if any or add exception or check if u have correct driver file. Disable any antivirus if any
and also make sure your driver type is mysql.jdbc.driver
.
The /EXCLUDE:
argument expects a file containing a list of excluded files.
So create a file called excludedfileslist.txt
containing:
.cs\
Then a command like this:
xcopy /r /d /i /s /y /exclude:excludedfileslist.txt C:\dev\apan C:\web\apan
Alternatively you could use Robocopy, but would require installing / copying a robocopy.exe
to the machines.
An anonymous comment edit which simply stated "This Solution exclude also css file!"
This is true creating a excludedfileslist.txt
file contain just:
.cs
(note no backslash on the end)
Will also exclude all of the following:
file1.cs
file2.css
dir1.cs\file3.txt
dir2\anyfile.cs.something.txt
Sometimes people don't read or understand the XCOPY command's help, here is an item I would like to highlight:
Using /exclude
- List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.
As the example states it excludes "all files with the .obj extension" but it doesn't state that it also excludes files or directories named file1.obj.tmp
or dir.obj.output\example2.txt
.
There is a way around .css
files being excluded also, change the excludedfileslist.txt
file to contain just:
.cs\
(note the backslash on the end).
Here is a complete test sequence for your reference:
C:\test1>ver
Microsoft Windows [Version 6.1.7601]
C:\test1>md src
C:\test1>md dst
C:\test1>md src\dir1
C:\test1>md src\dir2.cs
C:\test1>echo "file contents" > src\file1.cs
C:\test1>echo "file contents" > src\file2.css
C:\test1>echo "file contents" > src\dir1\file3.txt
C:\test1>echo "file contents" > src\dir1\file4.cs.txt
C:\test1>echo "file contents" > src\dir2.cs\file5.txt
C:\test1>xcopy /r /i /s /y .\src .\dst
.\src\file1.cs
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
.\src\dir2.cs\file5.txt
5 File(s) copied
C:\test1>echo .cs > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\dir1\file3.txt
1 File(s) copied
C:\test1>echo .cs\ > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
3 File(s) copied
This test was completed on a Windows 7 command line and retested on Windows 10 "10.0.14393".
Note that the last example does exclude .\src\dir2.cs\file5.txt
which may or may not be unexpected for you.
Content roots are folders holding your project code while source roots are defined as same too. The only difference i came to understand was that the code in source roots is built before the code in the content root.
Unchecking them wouldn't affect the runtime till the point you're not making separate modules in your package which are manually connected to Django. That means if any of your files do not hold the 'from django import...' or any of the function isn't called via django, unchecking these 2 options will result in a malfunction.
Update - the problem only arises when using Virtual Environmanet, and only when controlling the project via the provided terminal. Cause the terminal still works via the default system pyhtonpath and not the virtual env. while the python django control panel works fine.
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
Use java.util.Date
class instead of Timestamp.
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
This will get you the current date in the format specified.
In EditPlus you do this from the
Document ? File Format (CR/LF) ? Change File Format...
menu and then choose the Unix / Mac OS X
radio button.
For Python 2.6 and later if you are dealing with bytes then a bytearray
is the most obvious choice:
>>> str(bytearray([17, 24, 121, 1, 12, 222, 34, 76]))
'\x11\x18y\x01\x0c\xde"L'
To me this is even more direct than Alex Martelli's answer - still no string manipulation or len
call but now you don't even need to import anything!
Do offline rendering to a texture and evaluate the texture's data. You can find related code by googling for "render to texture" opengl Then use glReadPixels to read the output into an array and perform assertions on it (since looking through such a huge array in the debugger is usually not really useful).
Also you might want to disable clamping to output values that are not between 0 and 1, which is only supported for floating point textures.
I personally was bothered by the problem of properly debugging shaders for a while. There does not seem to be a good way - If anyone finds a good (and not outdated/deprecated) debugger, please let me know.
Adding one more approach :
value = $(this).val().toLowerCase();
$("#product-search-result tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
Is it also possible to access the management port in a similar way, e.g.:
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {
@LocalServerPort
int randomServerPort;
@LocalManagementPort
int randomManagementPort;
This is what i did for rendering html files. And it solved the errors. Install consolidate and mustache by executing the below command in your project folder.
$ sudo npm install consolidate mustache --save
And make the following changes to your app.js file
var engine = require('consolidate');
app.set('views', __dirname + '/views');
app.engine('html', engine.mustache);
app.set('view engine', 'html');
And now html pages will be rendered properly.
I had the same problem, but i solved it from Java Control Panel-->Security-->SecurityLevel:MEDIUM. Just so, no Manage certificates, imports ,exports etc..
Sorry but they are only in Unicode. :(
Big ones:
U+25B2
(Black up-pointing triangle ?)U+25BC
(Black down-pointing triangle ?)U+25C0
(Black left-pointing triangle ?)U+25B6
(Black right-pointing triangle ?)Big white ones:
U+25B3
(White up-pointing triangle ?)U+25BD
(White down-pointing triangle ?)U+25C1
(White left-pointing triangle ?)U+25B7
(White right-pointing triangle ?)There is also some smalller triangles:
U+25B4
(Black up-pointing small triangle ?)U+25C2
(Black left-pointing small triangle ?)U+25BE
(Black down-pointing small triangle ?)U+25B8
(Black right-pointing small triangle ?)Also some white ones:
U+25C3
(White left-pointing small triangle ?)U+25BF
(White down-pointing small triangle ?)U+25B9
(White right-pointing small triangle ?)U+25B5
(White up-pointing small triangle ?)There are also some "pointy" triangles. You can read more here in Wikipedia:
http://en.wikipedia.org/wiki/Geometric_Shapes
But unfortunately, they are all Unicode instead of ASCII.
If you still want to use ASCII, then you can use an image file for it of just use ^
and v
. (Just like the Google Maps in the mobile version this was referring to the ancient mobile Google Maps)
As others also suggested, you can also create triangles with HTML, either with CSS borders or SVG shapes or even JavaScript canvases.
div{
width: 0px;
height: 0px;
border-top: 10px solid black;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-bottom: none;
}
<svg width="16" height="10">
<polygon points="0,0 16,0 8,10"/>
</svg>
var ctx = document.querySelector("canvas").getContext("2d");
// do not use with() outside of this demo!
with(ctx){
beginPath();
moveTo(0,0);
lineTo(16,0);
lineTo(8,10);
fill();
endPath();
}
Since string is a reference type and the default value for reference type is null.
I found that my problem related to the actual registration of the DLL.
I see good answers have already been given, but I thought it might be nice to just give a way to perform mean filtering in MATLAB using no special functions or toolboxes. This is also very good for understanding exactly how the process works as you are required to explicitly set the convolution kernel. The mean filter kernel is fortunately very easy:
I = imread(...)
kernel = ones(3, 3) / 9; % 3x3 mean kernel
J = conv2(I, kernel, 'same'); % Convolve keeping size of I
Note that for colour images you would have to apply this to each of the channels in the image.
When FIND
returns #VALUE!
, it is an error, not a string, so you can't compare FIND(...)
with "#VALUE!"
, you need to check if FIND
returns an error with ISERROR
. Also FIND
can work on multiple characters.
So a simplified and working version of your formula would be:
=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))
Or, to remove the double negations:
=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")
FLAnimatedImage is a performant open source animated GIF engine for iOS:
It's a well-tested component that I wrote to power all GIFs in Flipboard.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="20dp" > <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:shadowColor="#000" android:shadowDx="0" android:shadowDy="0" android:shadowRadius="50" android:text="Text Shadow Example1" android:textColor="#FBFBFB" android:textSize="28dp" android:textStyle="bold" /> <TextView android:id="@+id/textview2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Text Shadow Example2" android:textColor="#FBFBFB" android:textSize="28dp" android:textStyle="bold" /> </LinearLayout>
In the above XML layout code, the textview1 is given with Shadow effect in the layout. below are the configuration items are
android:shadowDx – specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right
android:shadowDy – it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.
android:shadowRadius – specifies how much the shadow should be blurred at the edges. Provide a small value if shadow needs to be prominent. android:shadowColor – specifies the shadow color
Shadow Effect on Android TextView pragmatically
Use below code snippet to get the shadow effect on the second TextView pragmatically.
TextView textv = (TextView) findViewById(R.id.textview2); textv.setShadowLayer(30, 0, 0, Color.RED);
Output :
C:\Program Files (x86)\
change to C:\PROGRA~2\
. C:\Program Files\
, change the path to C:\PROGRA~1\
.Another variant of Steve Mallorys answer, I specifically needed excel to run off and do stuff while waiting and 1 second was too long.
'Wait for the specified number of milliseconds while processing the message pump
'This allows excel to catch up on background operations
Sub WaitFor(milliseconds As Single)
Dim finish As Single
Dim days As Integer
'Timer is the number of seconds since midnight (as a single)
finish = Timer + (milliseconds / 1000)
'If we are near midnight (or specify a very long time!) then finish could be
'greater than the maximum possible value of timer. Bring it down to sensible
'levels and count the number of midnights
While finish >= 86400
finish = finish - 86400
days = days + 1
Wend
Dim lastTime As Single
lastTime = Timer
'When we are on the correct day and the time is after the finish we can leave
While days >= 0 And Timer < finish
DoEvents
'Timer should be always increasing except when it rolls over midnight
'if it shrunk we've gone back in time or we're on a new day
If Timer < lastTime Then
days = days - 1
End If
lastTime = Timer
Wend
End Sub
To make all 3: Model, Controller & Migration Schema of table
write in your console: php artisan make:model NameOfYourModel -mcr
For me it worked using flexbox, which is in my opinion the cleanest solution.
Add a css class around the parent div / element with :
.parent {
display: flex;
}
and for the button use:
.button {
justify-content: center;
}
You should use a parent div, otherwise the button doesn't 'know' what the middle of the page / element is.
If this is not working, try :
#wrapper {
display:flex;
justify-content: center;
}
The short answer is the iPhone supports H.264 video, High profile and AAC audio, in container formats .mov
, .mp4
, or MPEG Segment .ts
. MPEG Segment files are used for HTTP Live Streaming.
.mp4
container..ts
container files (see App Store Review Guidelines rule 2.5.7).On the iPhone, H.264 is the only game in town. [1]
There are several different feature tiers or "profiles" available in H.264. All modern iPhones (3GS and above) support the High profile. These profiles are basically three different levels of algorithm "tricks" used to compress the video. More tricks give better compression, but require more CPU or dedicated hardware to decode. This is a table that lists the differences between the different profiles.
[1] Interestingly, Apple's own Facetime uses the newer H.265 (HEVC) video codec. However right now (August 2017) there is no Apple-provided library that gives access to a HEVC codec to developers. This is expected to change at some point.
In talking about what video format the iPhone supports, a distinction should be made between what the hardware can support, and what the (much lower) limits are for playback when streaming over a network.
The only data given about hardware video support by Apple about the current generation of iPhones (SE, 6S, 6S Plus, 7, 7 Plus) is that they support
4K [3840x2160] video recording at 30 fps
1080p [1920x1080] HD video recording at 30 fps or 60 fps.
Obviously the phone can play back what it can record, so we can guess that 3840x2160 at 30 fps and 1920x1080 at 60 fps represent design limits of the phone. In addition, the screen size on the 6S Plus and 7 Plus is 1920x1080. So if you're interested in playback on the phone, it doesn't make sense to send over more pixels then the screen can draw.
However, streaming video is a different matter. Since networks are slow and video is huge, it's typical to use lower resolutions, bitrates, and frame rates than the device's theoretical maximum.
The most detailed document giving recommendations for streaming is TN2224 Best Practices for Creating and Deploying HTTP Live Streaming Media for Apple Devices. Figure 3 in that document gives a table of recommended streaming parameters:
As you can see, Apple recommends the relatively low resolution of 768x432 as the highest recommended resolution for streaming over a cellular network. Of course this is just a recommendation and YMMV.
The question is about video, but that video generally has one or more audio tracks with it. The iPhone supports a few audio formats, but the most modern and by far most widely used is AAC. The iPhone 7 / 7 Plus, 6S Plus / 6S, SE all support AAC bitrates of 8 to 320 Kbps.
The audio and video tracks go inside a container. The purpose of the container is to combine (interleave) the different tracks together, to store metadata, and to support seeking. The iPhone supports
The .mov
and .mp4
file formats are closely related (.mp4
is in fact based on .mov
), however .mp4
is an ISO standard that has much wider support.
As noted above, you have to use MPEG-TS for videos longer than 10 minutes.
The tabularx
package gives you
X
, all X
columns will grow to fill up the total width.For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
By using the :last-child selector?
Do you have a specific scenario in mind you need assistance with?
** If you are looking for screen details for all kind of major devices **
While @tymeJV gave a correct answer, the way to do this to be inline with angular would be:
ng-click="hidePrefs()"
and then in your controller:
$scope.hidePrefs = function() {
$scope.prefs = false;
}
For recent SQL:
select * from v$sql
For history:
select * from dba_hist_sqltext
You have set #slider
as absolute
, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content
div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.
You can read about CSS positioning here
If you set both to relative
, the divs will be one after the other, as shown here:
#slider {
position:relative;
left:0;
height:400px;
border-style:solid;
border-width:5px;
}
#slider img {
width:100%;
}
#content {
position:relative;
}
#content #text {
position:relative;
width:950px;
height:215px;
color:red;
}
return $picName = time().'.'.$request->file->extension();
The time()
function will make the image unique then the .$request->file->extension()
gets the image extension for you.
You can use this it works well with Laravel 6 and above.
This error can be thrown when you import a different library for @Id than Javax.persistance.Id ; You might need to pay attention this case too
In my case I had
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;
import org.springframework.data.annotation.Id;
@Entity
public class Status {
@Id
@GeneratedValue
private int id;
when I change the code like this, it got worked
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;
import javax.persistence.Id;
@Entity
public class Status {
@Id
@GeneratedValue
private int id;
I don't have idea why it is happening but there 3 trivial attempts to make:
Use android:textAllCaps="false"
in your layout-v21
Programmatically change the transformation method of the button. mButton.setTransformationMethod(null);
Check your style for Allcaps
Note: public void setAllCaps(boolean allCaps)
, android:textAllCaps
are available from API version 14.
in .mjs files we for now don't have __dirname
hence
res.sendFile('index.html', { root: '.' })
There are many possible pitfalls for writing micro-benchmarks in Java.
First: You have to calculate with all sorts of events that take time more or less random: Garbage collection, caching effects (of OS for files and of CPU for memory), IO etc.
Second: You cannot trust the accuracy of the measured times for very short intervals.
Third: The JVM optimizes your code while executing. So different runs in the same JVM-instance will become faster and faster.
My recommendations: Make your benchmark run some seconds, that is more reliable than a runtime over milliseconds. Warm up the JVM (means running the benchmark at least once without measuring, that the JVM can run optimizations). And run your benchmark multiple times (maybe 5 times) and take the median-value. Run every micro-benchmark in a new JVM-instance (call for every benchmark new Java) otherwise optimization effects of the JVM can influence later running tests. Don't execute things, that aren't executed in the warmup-phase (as this could trigger class-load and recompilation).
Not a complete solution, but may help to compile a shortlist on Linux.
grep --include='*.py' -rhPo '^\s*(from|import)\s+\w+' . | sed -r 's/\s*(import|from)\s+//' | sort -u > requirements.txt
If you start to do something like this, then I would say it starts to get a bit strange and you're better off moving it to a seperate method that returns
a result upon the matchedCondition.
boolean matched = false;
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(matchedCondition) {
matched = true;
break;
}
}
if(matched) {
break;
}
}
To elaborate on how to clean up the above code, you can refactor, moving the code to a function that returns
instead of using breaks
. This is in general, better dealing with complex/messy breaks
.
public boolean matches()
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(matchedCondition) {
return true;
}
}
}
return false;
}
However for something simple like my below example. By all means use break
!
for(int i = 0; i < 10; i++) {
if(wereDoneHere()) { // we're done, break.
break;
}
}
And changing the conditions, in the above case i
, and j
's value, you would just make the code really hard to read. Also there could be a case where the upper limits (10 in the example) are variables so then it would be even harder to guess what value to set it to in order to exit the loop. You could of course just set i
and j
to Integer.MAX_VALUE, but I think you can see this starts to get messy very quickly. :)
If you want to kill -9 based on a string (you might want to try kill first) you can do something like this:
ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}'
This will show you what you're about to kill (very, very important) and just pipe it to sh
when the time comes to execute:
ps axf | grep <process name> | grep -v grep | awk '{print "kill -9 " $1}' | sh
You basically have two options:
Use PATCH
(but note that you have to define your own media type that specifies what will happen exactly)
Use POST
to a sub resource and return 303 See Other with the Location header pointing to the main resource. The intention of the 303 is to tell the client: "I have performed your POST and the effect was that some other resource was updated. See Location header for which resource that was." POST/303 is intended for iterative additions to a resources to build up the state of some main resource and it is a perfect fit for partial updates.
To append to an array, just use the +=
operator.
$Target += $TargetObject
Also, you need to declare $Target = @()
before your loop because otherwise, it will empty the array every loop.
You want to add the IN()
clause to your WHERE
SELECT *
FROM `Buses`
WHERE `BusID` IN (Id1, ID2, ID3,.... put your ids here)
If you have a list of Ids stored in a table you can also do this:
SELECT *
FROM `Buses`
WHERE `BusID` IN (SELECT Id FROM table)
If you wants display anchors in your own choice of colors than you should define the color in anchor tag property in CSS like this:-
a { text-decoration: none; color:red; }
a:visited { text-decoration: none; }
a:hover { text-decoration: none; }
a:focus { text-decoration: none; }
a:hover, a:active { text-decoration: none; }
see the demo:- http://jsfiddle.net/zSWbD/7/
The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:
git push origin master
Which will create this new master branch for you. Little things like this are very confusing with git.
If this didn't fix your issue then it's probably a gitolite-related issue:
Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:
repo phonegap
RW+ = myusername otherusername
repo gitolite-admin
RW+ = myusername
Please make sure you're setting your conf file correctly.
Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.
Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.
Yet another subtle pitfall, in case you need AllowOverride All
:
Somewhere deep in the fs tree, an old .htaccess
having
Options Indexes
instead of
Options +Indexes
was all it took to nonchalantly disable the FollowSymLinks
set in the server config, and cause a mysterious 403 here.
client.py
import socket
s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
str = raw_input("S: ")
s.send(str.encode());
if(str == "Bye" or str == "bye"):
break
print "N:",s.recv(1024).decode()
s.close()
server.py
import socket
s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
rcvdData = c.recv(1024).decode()
print "S:",rcvdData
sendData = raw_input("N: ")
c.send(sendData.encode())
if(sendData == "Bye" or sendData == "bye"):
break
c.close()
This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.
I don't know if I'm supposed to answer an old question, but as this post appears first on Google searches, I hoped that you would forgive me adding my solution & my 2c here.
Being lazy, I couldn't believe that the solution for this question would be a LOOP, so I searched a bit more and came back with filter function:
var myArray = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
var myValue = 80;
function BiggerThan(inArray) {
return inArray > myValue;
}
var arrBiggerElements = myArray.filter(BiggerThan);
var nextElement = Math.min.apply(null, arrBiggerElements);
alert(nextElement);
That's all !
I upload expansion code to show photo by android camera on html as normal on some img tag with right rotaion, especially for img tag whose width is wider than height. I know this code is ugly but you don't need to install any other packages. (I used above code to obtain exif rotation value, Thank you.)
function getOrientation(file, callback) {
var reader = new FileReader();
reader.onload = function(e) {
var view = new DataView(e.target.result);
if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
var length = view.byteLength, offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112)
return callback(view.getUint16(offset + (i * 12) + 8, little));
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
return callback(-1);
};
reader.readAsArrayBuffer(file);
}
var isChanged = false;
function rotate(elem, orientation) {
if (isIPhone()) return;
var degree = 0;
switch (orientation) {
case 1:
degree = 0;
break;
case 2:
degree = 0;
break;
case 3:
degree = 180;
break;
case 4:
degree = 180;
break;
case 5:
degree = 90;
break;
case 6:
degree = 90;
break;
case 7:
degree = 270;
break;
case 8:
degree = 270;
break;
}
$(elem).css('transform', 'rotate('+ degree +'deg)')
if(degree == 90 || degree == 270) {
if (!isChanged) {
changeWidthAndHeight(elem)
isChanged = true
}
} else if ($(elem).css('height') > $(elem).css('width')) {
if (!isChanged) {
changeWidthAndHeightWithOutMargin(elem)
isChanged = true
} else if(degree == 180 || degree == 0) {
changeWidthAndHeightWithOutMargin(elem)
if (!isChanged)
isChanged = true
else
isChanged = false
}
}
}
function changeWidthAndHeight(elem){
var e = $(elem)
var width = e.css('width')
var height = e.css('height')
e.css('width', height)
e.css('height', width)
e.css('margin-top', ((getPxInt(height) - getPxInt(width))/2).toString() + 'px')
e.css('margin-left', ((getPxInt(width) - getPxInt(height))/2).toString() + 'px')
}
function changeWidthAndHeightWithOutMargin(elem){
var e = $(elem)
var width = e.css('width')
var height = e.css('height')
e.css('width', height)
e.css('height', width)
e.css('margin-top', '0')
e.css('margin-left', '0')
}
function getPxInt(pxValue) {
return parseInt(pxValue.trim("px"))
}
function isIPhone(){
return (
(navigator.platform.indexOf("iPhone") != -1) ||
(navigator.platform.indexOf("iPod") != -1)
);
}
and then use such as
$("#banner-img").change(function () {
var reader = new FileReader();
getOrientation(this.files[0], function(orientation) {
rotate($('#banner-img-preview'), orientation, 1)
});
reader.onload = function (e) {
$('#banner-img-preview').attr('src', e.target.result)
$('#banner-img-preview').css('display', 'inherit')
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
});
This code returns an object with all properties that have a different value and also values of both objects. Useful to logging the difference.
var allkeys = _.union(_.keys(obj1), _.keys(obj2));
var difference = _.reduce(allkeys, function (result, key) {
if ( !_.isEqual(obj1[key], obj2[key]) ) {
result[key] = {obj1: obj1[key], obj2: obj2[key]}
}
return result;
}, {});
A free and open source password manager that keeps all of your passwords safe in one place is "KeePass" and alternative to Windows Credential Manager.
here's another way
import numpy as np
set(np.concatenate(df.values))
If you are using microsoft query, you can add "?" to your query...
select name from user where id= ?
that will popup a small window asking for the cell/data/etc when you go back to excel.
In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.
Use Meta-b / Meta-f to move backward/forward by a word respectively.
In OSX, Meta translates as ESC, which sucks.
But alternatively, you can open terminal preferences -> settings -> profile -> keyboard and check "use option as meta key"
HTTPS using Jersey client has two different version if you are using java 6 ,7 and 8 then
SSLContext sc = SSLContext.getInstance("SSL");
If using java 8 then
SSLContext sc = SSLContext.getInstance("TLSv1");
System.setProperty("https.protocols", "TLSv1");
Please find working code
POM
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>WebserviceJersey2Spring</groupId>
<artifactId>WebserviceJersey2Spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<jersey.version>2.16</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Jersey -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
</dependency>
<!-- Jersey + Spring -->
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-context</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-beans</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-core</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>spring-web</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
<exclusion>
<artifactId>jersey-server</artifactId>
<groupId>org.glassfish.jersey.core</groupId>
</exclusion>
<exclusion>
<artifactId>
jersey-container-servlet-core
</artifactId>
<groupId>org.glassfish.jersey.containers</groupId>
</exclusion>
<exclusion>
<artifactId>hk2</artifactId>
<groupId>org.glassfish.hk2</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
JAVA CLASS
package com.example.client;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.springframework.http.HttpStatus;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
public class JerseyClientGet {
public static void main(String[] args) {
String username = "username";
String password = "p@ssword";
String input = "{\"userId\":\"12345\",\"name \":\"Viquar\",\"surname\":\"Khan\",\"Email\":\"[email protected]\"}";
try {
//SSLContext sc = SSLContext.getInstance("SSL");//Java 6
SSLContext sc = SSLContext.getInstance("TLSv1");//Java 8
System.setProperty("https.protocols", "TLSv1");//Java 8
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
Client client = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
HttpAuthenticationFeature feature = HttpAuthenticationFeature.universalBuilder()
.credentialsForBasic(username, password).credentials(username, password).build();
client.register(feature);
//PUT request, if need uncomment it
//final Response response = client
//.target("https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations")
//.request().put(Entity.entity(input, MediaType.APPLICATION_JSON), Response.class);
//GET Request
final Response response = client
.target("https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations")
.request().get();
if (response.getStatus() != HttpStatus.OK.value()) { throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus()); }
String output = response.readEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
HELPER CLASS
package com.example.client;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class InsecureHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
Helper class
package com.example.client;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class InsecureTrustManager implements X509TrustManager {
/**
* {@inheritDoc}
*/
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
// Everyone is trusted!
}
/**
* {@inheritDoc}
*/
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
// Everyone is trusted!
}
/**
* {@inheritDoc}
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
Once you start running application will get Certificate error ,download certificate from browser and add into
C:\java-8\jdk1_8_0\jre\lib\security
Add into cacerts , you will get details in following links.
Few useful link to understand error
http://www.9threes.com/2015/01/restful-java-client-with-jersey-client.html
http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html
I have tested following code for get and post method with SSL and basic Authentication here you can skip SSL Certificate , you can directly copy three class and add jar into java project and run.
package com.rest.client;
import java.io.IOException;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.glassfish.jersey.filter.LoggingFilter;
import com.rest.dto.EarUnearmarkCollateralInput;
public class RestClientTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
//
sslRestClientGETReport();
//
sslRestClientPostEarmark();
//
sslRestClientGETRankColl();
//
} catch (KeyManagementException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
//
private static WebTarget target = null;
private static String userName = "username";
private static String passWord = "password";
//
public static void sslRestClientGETReport() throws KeyManagementException, IOException, NoSuchAlgorithmException {
//
//
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
//
Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
//
String baseUrl = "https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations/report";
c.register(HttpAuthenticationFeature.basic(userName, passWord));
target = c.target(baseUrl);
target.register(new LoggingFilter());
String responseMsg = target.request().get(String.class);
System.out.println("-------------------------------------------------------");
System.out.println(responseMsg);
System.out.println("-------------------------------------------------------");
//
}
public static void sslRestClientGET() throws KeyManagementException, IOException, NoSuchAlgorithmException {
//Query param Search={JSON}
//
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
//
Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
//
String baseUrl = "https://localhost:7002/VaquarKhanWeb";
//
c.register(HttpAuthenticationFeature.basic(userName, passWord));
target = c.target(baseUrl);
target = target.path("employee/api/v1/informations/employee/data").queryParam("search","%7B\"name\":\"vaquar\",\"surname\":\"khan\",\"age\":\"30\",\"type\":\"admin\""%7D");
target.register(new LoggingFilter());
String responseMsg = target.request().get(String.class);
System.out.println("-------------------------------------------------------");
System.out.println(responseMsg);
System.out.println("-------------------------------------------------------");
//
}
//TOD need to fix
public static void sslRestClientPost() throws KeyManagementException, IOException, NoSuchAlgorithmException {
//
//
Employee employee = new Employee("vaquar", "khan", "30", "E");
//
SSLContext sc = SSLContext.getInstance("SSL");
TrustManager[] trustAllCerts = { new InsecureTrustManager() };
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
//
Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
//
String baseUrl = "https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations/employee";
c.register(HttpAuthenticationFeature.basic(userName, passWord));
target = c.target(baseUrl);
target.register(new LoggingFilter());
//
Response response = target.request().put(Entity.json(employee));
String output = response.readEntity(String.class);
//
System.out.println("-------------------------------------------------------");
System.out.println(output);
System.out.println("-------------------------------------------------------");
}
}
Jars
repository/javax/ws/rs/javax.ws.rs-api/2.0/javax.ws.rs-api-2.0.jar"
repository/org/glassfish/jersey/core/jersey-client/2.6/jersey-client-2.6.jar"
repository/org/glassfish/jersey/core/jersey-common/2.6/jersey-common-2.6.jar"
repository/org/glassfish/hk2/hk2-api/2.2.0/hk2-api-2.2.0.jar"
repository/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.6/jersey-guava-2.6.jar"
repository/org/glassfish/hk2/hk2-locator/2.2.0/hk2-locator-2.2.0.jar"
repository/org/glassfish/hk2/hk2-utils/2.2.0/hk2-utils-2.2.0.jar"
repository/org/javassist/javassist/3.15.0-GA/javassist-3.15.0-GA.jar"
repository/org/glassfish/hk2/external/javax.inject/2.2.0/javax.inject-2.2.0.jar"
repository/javax/annotation/javax.annotation-api/1.2/javax.annotation-api-1.2.jar"
genson-1.3.jar"
This is re-post for insert code also. This example included: - One object list - Each object hast child list. Ex:
var list1 = {
name: "Role A",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
I'll 3 list like above and i'll add to a one object list
newArr.push(list1);
newArr.push(list2);
newArr.push(list3);
Then i'll do how to show checkbox with multiple group:
$scope.toggleAll = function(item) {
var toogleStatus = !item.name_selected;
console.log(toogleStatus);
angular.forEach(item, function() {
angular.forEach(item.subs, function(sub) {
sub.selected = toogleStatus;
});
});
};
$scope.optionToggled = function(item, subs) {
item.name_selected = subs.every(function(itm) {
return itm.selected;
})
$scope.txtRet = item.name_selected;
}
HTML:
<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
<div>
<ul>
<input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)"><span>{{item.name}}</span>
<div>
<li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
<input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
</li>
</div>
</ul>
</div>
<span>{{txtRet}}</span>
</li>
Fiddle: example
After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:
public void MyAddUpdateMethod()
{
using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//do my first add update statement
}
//removed the method call from the first sql server using statement
bool DoesRecordExist = this.SelectStatementCall(id)
}
}
public bool SelectStatementCall(System.Guid id)
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//create parameters
}
}
You can use:
start "windowTitle" fullPath/file.exe
Note: the first set of quotes must be there but you don't have to put anything in them, e.g.:
start "" fullPath/file.exe
PrintStream out = System.out;
out.println( "hello" );
So after looking (and using) of the other answers, seems they all handling ColorDrawable
and PaintDrawable
badly. (Especially on lollipop) seemed that Shader
s were tweaked so solid blocks of colors were not handled correctly.
I am using the following code now:
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
// We ask for the bounds if they have been set as they would be most
// correct, then we check we are > 0
final int width = !drawable.getBounds().isEmpty() ?
drawable.getBounds().width() : drawable.getIntrinsicWidth();
final int height = !drawable.getBounds().isEmpty() ?
drawable.getBounds().height() : drawable.getIntrinsicHeight();
// Now we check we are > 0
final Bitmap bitmap = Bitmap.createBitmap(width <= 0 ? 1 : width, height <= 0 ? 1 : height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
Unlike the others, if you call setBounds
on the Drawable
before asking to turn it into a bitmap, it will draw the bitmap at the correct size!
RogerB over at CodeProject has one of the slickest solutions to this answer, and he did that back in '04, and it's still bangin'
Basically, you go here to his project and download the CS file. In case that link ever dies, I've got a backup gist here. Add the CS file to your project, or copy/paste the code somewhere if you'd rather do that.
Then, all you'd have to do is switch
DialogResult result = MessageBox.Show("Text","Title", MessageBoxButtons.CHOICE)
to
DialogResult result = MessageBoxEx.Show("Text","Title", MessageBoxButtons.CHOICE, timer_ms)
And you're good to go.
You can use each()
$('#id-submit').click(function () {
$(":input").each(function(){
this.value = this.value.toUpperCase();
});
});
try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}
It seems that the trend in Android now is to use a Constraint layout. Although it is simple enough to center a view using a RelativeLayout
(as other answers have shown), the ConstraintLayout
is more powerful than the RelativeLayout
for more complex layouts. So it is worth learning how do do now.
To center a view, just drag the handles to all four sides of the parent.
**podria ser algo asi en react y electron**
xslToJson = workbook => {
//var data = [];
var sheet_name_list = workbook.SheetNames[0];
return XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list], {
raw: false,
dateNF: "DD-MMM-YYYY",
header:1,
defval: ""
});
};
handleFile = (file /*:File*/) => {
/* Boilerplate to set up FileReader */
const reader = new FileReader();
const rABS = !!reader.readAsBinaryString;
reader.onload = e => {
/* Parse data */
const bstr = e.target.result;
const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
/* Get first worksheet */
let arr = this.xslToJson(wb);
console.log("arr ", arr)
var dataNueva = []
arr.forEach(data => {
console.log("data renaes ", data)
})
// this.setState({ DataEESSsend: dataNueva })
console.log("dataNueva ", dataNueva)
};
if (rABS) reader.readAsBinaryString(file);
else reader.readAsArrayBuffer(file);
};
handleChange = e => {
const files = e.target.files;
if (files && files[0]) {
this.handleFile(files[0]);
}
};
I believe the problem with "go to" packages is that they would work diferently for each language.
If you use Javascript js-hyperclick and hyperclick (since code-links is deprecated) may do what you need.
Use symbols-view
package which let your search and jump to functions declaration but just of current opened file. Unfortunately, I don't know of any other language's equivalent.
There is also another package which could be useful for go-to in Python: python-tools
As of May 2016, recent version of Atom now support "Go-To" natively. At the GitHub repo for this module you get a list of the following keys:
symbols-view:toggle-file-symbols
to Show all symbols in current filesymbols-view:toggle-project-symbols
to Show all symbols in the projectsymbols-view:go-to-declaration
to Jump to the symbol under the cursor symbols-view:return-from-declaration
to Return from the jumpI now only have one thing missing with Atom for this: mouse click bindings. There's an open issue on Github if anyone want to follow that feature.
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
INSERT INTO def (field_1, field_2, field3)
VALUES
('$field_1', (SELECT id_user from user_table where name = 'jhon'), '$field3')
A lot of these answers overly complicated and also missing how to use variables. This is how you would do it more simply on standard Linux system (as previously mentioned the date command would have to be adjusted for Mac Users) :
Sample script:
#!/bin/bash
orig="Apr 28 07:50:01"
epoch=$(date -d "${orig}" +"%s")
epoch_to_date=$(date -d @$epoch +%Y%m%d_%H%M%S)
echo "RESULTS:"
echo "original = $orig"
echo "epoch conv = $epoch"
echo "epoch to human readable time stamp = $epoch_to_date"
Results in :
RESULTS:
original = Apr 28 07:50:01
epoch conv = 1524916201
epoch to human readable time stamp = 20180428_075001
Or as a function :
# -- Converts from human to epoch or epoch to human, specifically "Apr 28 07:50:01" human.
# typeset now=$(date +"%s")
# typeset now_human_date=$(convert_cron_time "human" "$now")
function convert_cron_time() {
case "${1,,}" in
epoch)
# human to epoch (eg. "Apr 28 07:50:01" to 1524916201)
echo $(date -d "${2}" +"%s")
;;
human)
# epoch to human (eg. 1524916201 to "Apr 28 07:50:01")
echo $(date -d "@${2}" +"%b %d %H:%M:%S")
;;
esac
}
Application Server:
Application server maintains the application logic and
serves the web pages in response to user request.
That means application server can do both application logic maintanence and web page serving.
Web Server:
Web server just serves the web pages and it cannot enforce any application logic.
Final conclusion is: Application server also contains the web server.
For further Reference : http://www.javaworld.com/javaqa/2002-08/01-qa-0823-appvswebserver.html
This is another way to shuffle the data.frame
using package dplyr
:
row-wise:
df2 <- slice(df1, sample(1:n()))
or
df2 <- sample_frac(df1, 1L)
column-wise:
df2 <- select(df1, one_of(sample(names(df1))))
//Client
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
String hostname = "localhost";
int port = 6789;
// declaration section:
// clientSocket: our client socket
// os: output stream
// is: input stream
Socket clientSocket = null;
DataOutputStream os = null;
BufferedReader is = null;
// Initialization section:
// Try to open a socket on the given port
// Try to open input and output streams
try {
clientSocket = new Socket(hostname, port);
os = new DataOutputStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + hostname);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + hostname);
}
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on the given port
if (clientSocket == null || os == null || is == null) {
System.err.println( "Something is wrong. One variable is null." );
return;
}
try {
while ( true ) {
System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String keyboardInput = br.readLine();
os.writeBytes( keyboardInput + "\n" );
int n = Integer.parseInt( keyboardInput );
if ( n == 0 || n == -1 ) {
break;
}
String responseLine = is.readLine();
System.out.println("Server returns its square as: " + responseLine);
}
// clean up:
// close the output stream
// close the input stream
// close the socket
os.close();
is.close();
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
//Server
import java.io.*;
import java.net.*;
public class Server1 {
public static void main(String args[]) {
int port = 6789;
Server1 server = new Server1( port );
server.startServer();
}
// declare a server socket and a client socket for the server
ServerSocket echoServer = null;
Socket clientSocket = null;
int port;
public Server1( int port ) {
this.port = port;
}
public void stopServer() {
System.out.println( "Server cleaning up." );
System.exit(0);
}
public void startServer() {
// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(port);
}
catch (IOException e) {
System.out.println(e);
}
System.out.println( "Waiting for connections. Only one connection is allowed." );
// Create a socket object from the ServerSocket to listen and accept connections.
// Use Server1Connection to process the connection.
while ( true ) {
try {
clientSocket = echoServer.accept();
Server1Connection oneconnection = new Server1Connection(clientSocket, this);
oneconnection.run();
}
catch (IOException e) {
System.out.println(e);
}
}
}
}
class Server1Connection {
BufferedReader is;
PrintStream os;
Socket clientSocket;
Server1 server;
public Server1Connection(Socket clientSocket, Server1 server) {
this.clientSocket = clientSocket;
this.server = server;
System.out.println( "Connection established with: " + clientSocket );
try {
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
}
public void run() {
String line;
try {
boolean serverStop = false;
while (true) {
line = is.readLine();
System.out.println( "Received " + line );
int n = Integer.parseInt(line);
if ( n == -1 ) {
serverStop = true;
break;
}
if ( n == 0 ) break;
os.println("" + n*n );
}
System.out.println( "Connection closed." );
is.close();
os.close();
clientSocket.close();
if ( serverStop ) server.stopServer();
} catch (IOException e) {
System.out.println(e);
}
}
}
Yes, it can throw an exception and you can declare that in the signature of the constructor too as shown in the example below:
public class ConstructorTest
{
public ConstructorTest() throws InterruptedException
{
System.out.println("Preparing object....");
Thread.sleep(1000);
System.out.println("Object ready");
}
public static void main(String ... args)
{
try
{
ConstructorTest test = new ConstructorTest();
}
catch (InterruptedException e)
{
System.out.println("Got interrupted...");
}
}
}
Followed this.
I have solved it with adding some key in info.plist. The steps I followed are:
Opened my Projects info.plist
file
Added a Key called NSAppTransportSecurity
as a Dictionary
.
NSAllowsArbitraryLoads
as Boolean
and set its value to YES
as like following image.
Clean the Project and Now Everything is Running fine as like before.
Ref Link.
see 15.22.2 of the JLS. For boolean operands, the &
operator is boolean, not bitwise. The only difference between &&
and &
for boolean operands is that for &&
it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).
So in your case, if b
is a primitive, a = a && b
, a = a & b
, and a &= b
all do the same thing.
Your format string is wrong. Change it to
insert = DateTime.ParseExact(line[i], "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);
Unlike in some laguages, empty
is not a keyword in Python. Python lists are constructed form the ground up, so if element i
has a value, then element i-1
has a value, for all i > 0
.
To do an equality check, you usually use either the ==
comparison operator.
>>> my_list = ["asdf", 0, 42, '', None, True, "LOLOL"]
>>> my_list[0] == "asdf"
True
>>> my_list[4] is None
True
>>> my_list[2] == "the universe"
False
>>> my_list[3]
""
>>> my_list[3] == ""
True
Here's a link to the strip
method: your comment indicates to me that you may have some strange file parsing error going on, so make sure you're stripping off newlines and extraneous whitespace before you expect an empty line.
Try data.table's :=
operator :
DT = as.data.table(df)
DT[b==0, est := (a-5)/2.533]
It's fast and short. See these linked questions for more information on :=
:
When should I use the :=
operator in data.table
If you need to see the output of an existing program that extensively used printf w/o changing the code (or with minimal changes) you can redefine printf as follows and add it to the common header (stdafx.h).
int print_log(const char* format, ...)
{
static char s_printf_buf[1024];
va_list args;
va_start(args, format);
_vsnprintf(s_printf_buf, sizeof(s_printf_buf), format, args);
va_end(args);
OutputDebugStringA(s_printf_buf);
return 0;
}
#define printf(format, ...) \
print_log(format, __VA_ARGS__)
This worked for me (I'm using VS Code):
for:
This is just\na simple sentence
Use:
This .+ sentence
Assuming you’ve literally got two date objects, you can subtract one from the other and query the resulting timedelta
object for the number of days:
>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7
And it works with datetimes too — I think it rounds down to the nearest day:
>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
EDIT: As pointed out by users, don't use MQ, use commit --amend
. This answer is mostly of historic interest now.
As others have mentioned the MQ extension is much more suited for this task, and you don't run the risk of destroying your work. To do this:
Enable the MQ extension, by adding something like this to your hgrc:
[extensions]
mq =
Update to the changeset you want to edit, typically tip:
hg up $rev
Import the current changeset into the queue:
hg qimport -r .
Refresh the patch, and edit the commit message:
hg qrefresh -e
Finish all applied patches (one, in this case) and store them as regular changesets:
hg qfinish -a
I'm not familiar with TortoiseHg, but the commands should be similar to those above. I also believe it's worth mentioning that editing history is risky; you should only do it if you're absolutely certain that the changeset hasn't been pushed to or pulled from anywhere else.
You can use Hibernate Dialect API for Database independence as follow
class SequenceValueGetter {
private SessionFactory sessionFactory;
// For Hibernate 3
public Long getId(final String sequenceName) {
final List<Long> ids = new ArrayList<Long>(1);
sessionFactory.getCurrentSession().doWork(new Work() {
public void execute(Connection connection) throws SQLException {
DialectResolver dialectResolver = new StandardDialectResolver();
Dialect dialect = dialectResolver.resolveDialect(connection.getMetaData());
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement( dialect.getSequenceNextValString(sequenceName));
resultSet = preparedStatement.executeQuery();
resultSet.next();
ids.add(resultSet.getLong(1));
}catch (SQLException e) {
throw e;
} finally {
if(preparedStatement != null) {
preparedStatement.close();
}
if(resultSet != null) {
resultSet.close();
}
}
}
});
return ids.get(0);
}
// For Hibernate 4
public Long getID(final String sequenceName) {
ReturningWork<Long> maxReturningWork = new ReturningWork<Long>() {
@Override
public Long execute(Connection connection) throws SQLException {
DialectResolver dialectResolver = new StandardDialectResolver();
Dialect dialect = dialectResolver.resolveDialect(connection.getMetaData());
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement( dialect.getSequenceNextValString(sequenceName));
resultSet = preparedStatement.executeQuery();
resultSet.next();
return resultSet.getLong(1);
}catch (SQLException e) {
throw e;
} finally {
if(preparedStatement != null) {
preparedStatement.close();
}
if(resultSet != null) {
resultSet.close();
}
}
}
};
Long maxRecord = sessionFactory.getCurrentSession().doReturningWork(maxReturningWork);
return maxRecord;
}
}
To expand on what has been provided for automatically exporting data as csv to a network share via SQL Server Agent.
(1) Enable the xp_cmdshell procedure:
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO
(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database. Done through user mapping
(3) Give log on as batch job: Navigate to Local Security Policy -> Local Policies -> User Rights Assignment. Add user to "Log on as a batch job"
(4) Give read/write permissions to network folder for domain\user
(5) Grant EXEC permission on the xp_cmdshell stored procedure:
GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]
(6) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account
EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'password_for_domain_user'
(7) If the sp_xp_cmdshell_proxy_account command doesn't work, manually create it
create credential ##xp_cmdshell_proxy_account## with identity = 'Domain\DomainUser', secret = 'password'
(8) Enable SQL Server Agent. Open SQL Server Configuration Manager, navigate to SQL Server Services, enable SQL Server Agent.
(9) Create automated job. Open SSMS, select SQL Server Agent, then right-click jobs and click "New Job".
(10) Select "Owner" as your created user. Select "Steps", make "type" = T-SQL. Fill out command field similar to below. Set delimiter as ','
EXEC master..xp_cmdshell 'SQLCMD -q "select * from master" -o file.csv -s ","
(11) Fill out schedules accordingly.
If, like me, what you usually want is to overwrite the contents of the working directory with that of the stashed files, and you still get a conflict, then what you want is to resolve the conflict using git checkout --theirs -- .
from the root.
After that, you can git reset
to bring all the changes from the index to the working directory, since apparently in case of conflict the changes to non-conflicted files stay in the index.
You may also want to run git stash drop [<stash name>]
afterwards, to get rid of the stash, because git stash pop
doesn't delete it in case of conflicts.
In C++ projects past, I have used PCRE with good success. It's very complete and well-tested since it's used in many high profile projects. And I see that Google has contributed a set of C++ wrappers for PCRE recently, too.
Actually a bit surprised not many mentioned about google/benchmark , while it is a bit cumbersome to pin the specific area of code, specially if the code base is a little big one, however I found this really helpful when used in combination with callgrind
IMHO identifying the piece that is causing bottleneck is the key here. I'd however try and answer the following questions first and choose tool based on that
valgrind
with the combination of callrind
and kcachegrind
should provide a decent estimation on the points above and once it's established that there are issues with some section of code, I'd suggest do a micro bench mark google benchmark
is a good place to start.
Of course, never fails. Found the solution about a minute after posting the above question... solution for those that may have had the same issue:
ContextWrapper.getFilesDir()
Found here.
self
is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main()
, you first have to instantiate an object of your class and call the function on the object.
Further, your function setavalue
should be in __init___
, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name
class ;)
class Name:
def __init__(self):
self.myname = "harry"
def printaname(self):
print "Name", self.myname
def main(self):
self.printaname()
if __name__ == "__main__":
objName = Name()
objName.main()
Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.
You could always make a unique index, which causes MongoDB to reject a conflicting save. Consider the following done using the mongodb shell:
> db.getCollection("test").insert ({a:1, b:2, c:3})
> db.getCollection("test").find()
{ "_id" : ObjectId("50c8e35adde18a44f284e7ac"), "a" : 1, "b" : 2, "c" : 3 }
> db.getCollection("test").ensureIndex ({"a" : 1}, {unique: true})
> db.getCollection("test").insert({a:2, b:12, c:13}) # This works
> db.getCollection("test").insert({a:1, b:12, c:13}) # This fails
E11000 duplicate key error index: foo.test.$a_1 dup key: { : 1.0 }
DATEDIFF(hour, start_date, end_date)
will give you the number of hour boundaries crossed between start_date
and end_date
.
If you need the number of fractional hours, you can use DATEDIFF
at a higher resolution and divide the result:
DATEDIFF(second, start_date, end_date) / 3600.0
The documentation for DATEDIFF
is available on MSDN:
http://msdn.microsoft.com/en-us/library/ms189794%28SQL.105%29.aspx
you need to call the function like this
$this->assign()
instead of just assign()
Beginning each new line with two white spaces will avoid the auto-remove perpetrated by Outlook.
var lineString = " line 1\r\n";
linestring += " line 2";
Will correctly display:
line 1
line 2
It's a little clumsy feeling to use, but it does the job without a lot of extra effort being spent on it.
Try
td.description {_x000D_
line-height: 15px_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
Set the line-height value to the desired value.
I used the svn2git script and works like a charm.
You can find it via:
$(yourEl).tabs({
activate: function(event, ui) {
console.log(ui.newPanel.index());
}
});
If you render the Recaptcha on a callback
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
using an empty DIV as a placeholder
<div id='html_element'></div>
then you can specify an optional function call on a successful CAPTCHA response
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : 'your_site_key',
'callback' : correctCaptcha
});
};
The recaptcha response will then be sent to the 'correctCaptcha' function.
var correctCaptcha = function(response) {
alert(response);
};
All of this was from the Google API notes :
I'm a bit unsure why you would want to do this. Normally you would send the g-recaptcha-response field along with your Private key to safely validate server-side. Unless you wanted to disable the submit button until the recaptcha was sucessful or such - in which case the above should work.
Hope this helps.
Paul
This is not exactly what author asked, but still, it is very simple and works exactly as expected.
Rectangle does the job:
<StackPanel Grid.Column="2" Orientation="Horizontal">
<Button >Next</Button>
<Button >Prev</Button>
<Rectangle VerticalAlignment="Stretch" Width="1" Margin="2" Stroke="Black" />
<Button>Filter all</Button>
</StackPanel>
Paste it into your web page, just before the closing
</head>
tag.One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the
<head>
section, and we recommend placing the snippet at the bottom of the<head>
section for best performance
Fast and easy with HAVING:
SELECT * FROM tblpm n
FROM tblpm GROUP BY control_number
HAVING date_updated=MAX(date_updated);
In the context of HAVING
, MAX
finds the max of each group. Only the latest entry in each group will satisfy date_updated=max(date_updated)
. If there's a tie for latest within a group, both will pass the HAVING
filter, but GROUP BY
means that only one will appear in the returned table.
Example here.
Pasted below:
This is about how to launch android application from the adb shell.
Command: am
Look for invoking path in AndroidManifest.xml
Browser app::
# am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity
Starting: Intent { action=android.intent.action.MAIN comp={com.android.browser/com.android.browser.BrowserActivity} }
Warning: Activity not started, its current task has been brought to the front
Settings app::
# am start -a android.intent.action.MAIN -n com.android.settings/.Settings
Starting: Intent { action=android.intent.action.MAIN comp={com.android.settings/com.android.settings.Settings} }
Shorter option to extract the second word in a sentence:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('THIS IS A TEST', ' ', 2), ' ', -1) as FoundText
It's better to have a proper JSON format instead of directly using the one converted from XML.
[
{
"number": "2013-W45",
"days": [
{
"dow": "1",
"templateDay": "Monday",
"jobs": [
{
"name": "Wakeup",
"jobs": [
{
"name": "prepare breakfast",
}
]
},
{
"name": "work 9-5",
}
]
},
{
"dow": "2",
"templateDay": "Tuesday",
"jobs": [
{
"name": "Wakeup",
"jobs": [
{
"name": "prepare breakfast",
}
]
}
]
}
]
}
]
This will make things much easier and easy to loop through.
Now you can write the loop as -
<div ng-repeat="week in myData">
<div ng-repeat="day in week.days">
{{day.dow}} - {{day.templateDay}}
<b>Jobs:</b><br/>
<ul>
<li ng-repeat="job in day.jobs">
{{job.name}}
</li>
</ul>
</div>
</div>
Even if modern browsers support WebSockets now, I think there is no need to throw SocketIO away and it still has its place in any nowadays project. It's easy to understand, and personally, I learned how WebSockets work thanks to SocketIO.
As said in this topic, there's a plenty of integration libraries for Angular, React, etc. and definition types for TypeScript and other programming languages.
The other point I would add to the differences between Socket.io and WebSockets is that clustering with Socket.io is not a big deal. Socket.io offers Adapters that can be used to link it with Redis to enhance scalability. You have ioredis and socket.io-redis for example.
Yes I know, SocketCluster exists, but that's off-topic.
Yes, you can use find_elements_by_
to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html
Example HTML:
<ul class="bar">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
You can use the find_elements_by_
like so:
parentElement = driver.find_element_by_class_name("bar")
elementList = parentElement.find_elements_by_tag_name("li")
If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.
PostGIS_Lib_Version();
- returns the version number of the PostGIS library.
http://postgis.refractions.net/docs/PostGIS_Lib_Version.html
An example under Linux (Fedora 16) shows that memory is freed when R is closed:
$ free -m
total used free shared buffers cached
Mem: 3829 2854 974 0 344 1440
-/+ buffers/cache: 1069 2759
Swap: 4095 85 4010
2854 megabytes is used. Next I open an R session and create a large matrix of random numbers:
m = matrix(runif(10e7), 10000, 1000)
when the matrix is created, 3714 MB is used:
$ free -m
total used free shared buffers cached
Mem: 3829 3714 115 0 344 1442
-/+ buffers/cache: 1927 1902
Swap: 4095 85 4010
After closing the R session, I nicely get back the memory I used (2856 MB free):
$ free -m
total used free shared buffers cached
Mem: 3829 2856 972 0 344 1442
-/+ buffers/cache: 1069 2759
Swap: 4095 85 4010
Ofcourse you use Windows, but you could repeat this excercise in Windows and report how the available memory develops before and after you create this large dataset in R.