The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
See dtmFRM.js. If you are familiar with C#'s custom date and time format string, this library should do the exact same thing.
DEMO:
var format = new dtmFRM();
var now = new Date().getTime();
$('#s2').append(format.ToString(now,"This month is : MMMM") + "</br>");
$('#s2').append(format.ToString(now,"Year is : y or yyyy or yy") + "</br>");
$('#s2').append(format.ToString(now,"mm/yyyy/dd") + "</br>");
$('#s2').append(format.ToString(now,"dddd, MM yyyy ") + "</br>");
$('#s2').append(format.ToString(now,"Time is : hh:mm:ss ampm") + "</br>");
$('#s2').append(format.ToString(now,"HH:mm") + "</br>");
$('#s2').append(format.ToString(now,"[ddd,MMM,d,dddd]") + "</br></br>");
now = '11/11/2011 10:15:12' ;
$('#s2').append(format.ToString(now,"MM/dd/yyyy hh:mm:ss ampm") + "</br></br>");
now = '40/23/2012'
$('#s2').append(format.ToString(now,"Year is : y or yyyy or yy") + "</br></br>");
sometimes mysql_upgrade -u root -p --force
is not realy enough,
please refer to this question : Table 'performance_schema.session_variables' doesn't exist
according to it:
cd [installation_path]\eds-binaries\dbserver\mysql5711x86x160420141510\bin
mysql_upgrade -u root -p --force
exec is shelling to the operating system, and unless the OS has some special way of knowing how to execute a file, then it's going to default to treating it as a shell script or similar. In this case, it has no idea how to run your php file. If this script absolutely has to be executed from a shell, then either execute php passing the filename as a parameter, e.g
exec ('/usr/local/bin/php -f /opt/lampp/htdocs/.../name.php)') ;
or use the punct at the top of your php script
#!/usr/local/bin/php
<?php ... ?>
Just an update of James' answer.
Isn't this the normal way to free the memory associated with an object?
Yes. It is the normal way to free memory. But new/delete operator always leads to memory leak problem.
Since c++17 already removed auto_ptr auto_ptr. I suggest shared_ptr or unique_ptr to handle the memory problems.
void test()
{
std::shared_ptr<Object1> obj1(new Object1);
} // The object is automatically deleted when the scope ends or reference counting reduces to 0.
One very simple way to make a method asynchronous is to use Task.Yield() method. As MSDN states:
You can use await Task.Yield(); in an asynchronous method to force the method to complete asynchronously.
Insert it at beginning of your method and it will then return immediately to the caller and complete the rest of the method on another thread.
private async Task<DateTime> CountToAsync(int num = 1000)
{
await Task.Yield();
for (int i = 0; i < num; i++)
{
Console.WriteLine("#{0}", i);
}
return DateTime.Now;
}
After trying all these solutions without success the one that fixed my problem was simply changing the Graphics configuration for the virtual device from Auto to Software (tried hardware first without success)
I just found this out by trying to see if my event was attached....
if you do :
item.onclick
it will return "null"
but if you do:
item.hasOwnProperty('onclick')
then it is "TRUE"
so I think that when you use "addEventListener" to add event handlers, the only way to access it is through "hasOwnProperty". I wish I knew why or how but alas, after researching, I haven't found an explanation.
Maybe you want to use CSS "clip-path" (Works with transparency and background)
"clip-path" reference: https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path
Generator: http://bennettfeely.com/clippy/
Example:
/* With percent */_x000D_
.element-percent {_x000D_
background: red;_x000D_
width: 150px;_x000D_
height: 48px;_x000D_
display: inline-block;_x000D_
_x000D_
clip-path: polygon(0 0, 100% 0%, 75% 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With pixel */_x000D_
.element-pixel {_x000D_
background: blue;_x000D_
width: 150px;_x000D_
height: 48px;_x000D_
display: inline-block;_x000D_
_x000D_
clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With background */_x000D_
.element-background {_x000D_
background: url(https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260) no-repeat center/cover;_x000D_
width: 150px;_x000D_
height: 48px;_x000D_
display: inline-block;_x000D_
_x000D_
clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}
_x000D_
<div class="element-percent"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-pixel"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-background"></div>
_x000D_
From http://www.oreillynet.com/linux/cmd/cmd.csp?path=g/gcc
The > character does not redirect the standard error. It's useful when you want to save legitimate output without mucking up a file with error messages. But what if the error messages are what you want to save? This is quite common during troubleshooting. The solution is to use a greater-than sign followed by an ampersand. (This construct works in almost every modern UNIX shell.) It redirects both the standard output and the standard error. For instance:
$ gcc invinitjig.c >& error-msg
Have a look there, if this helps: another forum
The RIGHT and WRONG way to set Python 3 as default on a Mac
In this article author discuss three ways of setting default python:
All these ways are working. You decide which is better.
You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run
ALTER USER <user> quota unlimited on <tablespace name>;
or
ALTER USER <user> quota 100M on <tablespace name>;
as a DBA user (depending on how much space you need / want to grant).
WebSockets is protocol that relies on TCP streamed connection. Although WebSockets is Message based protocol.
If you want to implement your own protocol then I recommend to use latest and stable specification (for 18/04/12) RFC 6455. This specification contains all necessary information regarding handshake and framing. As well most of description on scenarios of behaving from browser side as well as from server side. It is highly recommended to follow what recommendations tells regarding server side during implementing of your code.
In few words, I would describe working with WebSockets like this:
Create server Socket (System.Net.Sockets) bind it to specific port, and keep listening with asynchronous accepting of connections. Something like that:
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080)); serverSocket.Listen(128); serverSocket.BeginAccept(null, 0, OnAccept, null);
You should have accepting function "OnAccept" that will implement handshake. In future it has to be in another thread if system is meant to handle huge amount of connections per second.
private void OnAccept(IAsyncResult result) { try { Socket client = null; if (serverSocket != null && serverSocket.IsBound) { client = serverSocket.EndAccept(result); } if (client != null) { /* Handshaking and managing ClientSocket */ } } catch(SocketException exception) { } finally { if (serverSocket != null && serverSocket.IsBound) { serverSocket.BeginAccept(null, 0, OnAccept, null); } } }
After connection established, you have to do handshake. Based on specification 1.3 Opening Handshake, after connection established you will receive basic HTTP request with some information. Example:
GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13
This example is based on version of protocol 13. Bear in mind that older versions have some differences but mostly latest versions are cross-compatible. Different browsers may send you some additional data. For example Browser and OS details, cache and others.
Based on provided handshake details, you have to generate answer lines, they are mostly same, but will contain Accpet-Key, that is based on provided Sec-WebSocket-Key. In specification 1.3 it is described clearly how to generate response key. Here is my function I've been using for V13:
static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private string AcceptKey(ref string key) { string longKey = key + guid; SHA1 sha1 = SHA1CryptoServiceProvider.Create(); byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey)); return Convert.ToBase64String(hashBytes); }
Handshake answer looks like that:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
But accept key have to be the generated one based on provided key from client and method AcceptKey I provided before. As well, make sure after last character of accept key you put two new lines "\r\n\r\n".
Implementing own WebSockets protocol definitely have some benefits and great experience you get as well as control over protocol it self. But you have to spend some time doing it, and make sure that implementation is highly reliable.
In same time you might have a look in ready to use solutions that google (again) have enough.
Query 1: SELECT * FROM yourtable WHERE id > 0 ORDER BY id LIMIT 500
Query 2: SELECT * FROM tbl LIMIT 0,500;
Query 1 run faster with small or medium records, if number of records equal 5,000 or higher, the result are similar.
Result for 500 records:
Query1 take 9.9999904632568 milliseconds
Query2 take 19.999980926514 milliseconds
Result for 8,000 records:
Query1 take 129.99987602234 milliseconds
Query2 take 160.00008583069 milliseconds
An extended version of @krzysztof answer with the ability to work on time that has space or not between time and modifier.
const convertTime12to24 = (time12h) => {
const [fullMatch, time, modifier] = time12h.match(/(\d?\d:\d\d)\s*(\w{2})/i);
let [hours, minutes] = time.split(':');
if (hours === '12') {
hours = '00';
}
if (modifier === 'PM') {
hours = parseInt(hours, 10) + 12;
}
return `${hours}:${minutes}`;
}
console.log(convertTime12to24('01:02 PM'));
console.log(convertTime12to24('05:06 PM'));
console.log(convertTime12to24('12:00 PM'));
console.log(convertTime12to24('12:00 AM'));
You can write:
python
import keras
keras.__version__
I experienced this today. The value in Config was the updated one but the application would return the older value, stop and starting the solution did nothing.
So I cleared the .Net Temp folder.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
It shouldn't create bugs but to be safe close your solution down first. Clear the Temporary ASP.NET Files then load up your solution.
My issue was sorted.
You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.
Sub dedupe_abcd()
Dim icol As Long
With Sheets("Sheet1") '<-set this worksheet reference properly!
icol = Application.Match("abcd", .Rows(1), 0)
With .Cells(1, 1).CurrentRegion
.RemoveDuplicates Columns:=icol, Header:=xlYes
End With
End With
End Sub
Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.
They may be unpopular, but I am a fan of Arrays in game projects. - Iteration speed can be important in some cases, foreach on an Array has significantly less overhead if you are not doing much per element - Adding and removing is not that hard with helper functions - Its slower, but in cases where you only build it once it may not matter - In most cases, less extra memory is wasted (only really significant with Arrays of structs) - Slightly less garbage and pointers and pointer chasing
That being said, I use List far more often than Arrays in practice, but they each have their place.
It would be nice if List where a built in type so that they could optimize out the wrapper and enumeration overhead.
Spring Boot do a lot of automatically things to us but when we use the annotation @SpringBootTest
we think that everything will be automatically solved by Spring boot.
There are a lot of documentation, but the minimal is to choose one engine (@RunWith(SpringRunner.class)
) and indicate the class that will be used create the context to load the configuration (resources/applicationl.properties
).
In a simple way you need the engine and the context:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyClassTest .class)
public class MyClassTest {
@Value("${my.property}")
private String myProperty;
@Test
public void checkMyProperty(){
Assert.assertNotNull(my.property);
}
}
Of course, if you look the Spring Boot documentation you will find thousands os ways to do that.
You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub
First post :)
For the OP, kristof's solution will work, unless there are issues with massive data and transaction log balloon issues on big deletes. Also, even with tlog storage to spare, since deletes write to the tlog, the operation can take a VERY long time for tables with hundreds of millions of rows.
I use a series of cursors to truncate and reload large copies of one of our huge production databases frequently. The solution engineered accounts for multiple schemas, multiple foreign key columns, and best of all can be sproc'd out for use in SSIS.
It involves creation of three staging tables (real tables) to house the DROP, CREATE, and CHECK FK scripts, creation and insertion of those scripts into the tables, and then looping over the tables and executing them. The attached script is four parts: 1.) creation and storage of the scripts in the three staging (real) tables, 2.) execution of the drop FK scripts via a cursor one by one, 3.) Using sp_MSforeachtable to truncate all the tables in the database other than our three staging tables and 4.) execution of the create FK and check FK scripts at the end of your ETL SSIS package.
Run the script creation portion in an Execute SQL task in SSIS. Run the "execute Drop FK Scripts" portion in a second Execute SQL task. Put the truncation script in a third Execute SQL task, then perform whatever other ETL processes you need to do prior to attaching the CREATE and CHECK scripts in a final Execute SQL task (or two if desired) at the end of your control flow.
Storage of the scripts in real tables has proven invaluable when the re-application of the foreign keys fails as you can select * from sync_CreateFK, copy/paste into your query window, run them one at a time, and fix the data issues once you find ones that failed/are still failing to re-apply.
Do not re-run the script again if it fails without making sure that you re-apply all of the foreign keys/checks prior to doing so, or you will most likely lose some creation and check fk scripting as our staging tables are dropped and recreated prior to the creation of the scripts to execute.
----------------------------------------------------------------------------
1)
/*
Author: Denmach
DateCreated: 2014-04-23
Purpose: Generates SQL statements to DROP, ADD, and CHECK existing constraints for a
database. Stores scripts in tables on target database for execution. Executes
those stored scripts via independent cursors.
DateModified:
ModifiedBy
Comments: This will eliminate deletes and the T-log ballooning associated with it.
*/
DECLARE @schema_name SYSNAME;
DECLARE @table_name SYSNAME;
DECLARE @constraint_name SYSNAME;
DECLARE @constraint_object_id INT;
DECLARE @referenced_object_name SYSNAME;
DECLARE @is_disabled BIT;
DECLARE @is_not_for_replication BIT;
DECLARE @is_not_trusted BIT;
DECLARE @delete_referential_action TINYINT;
DECLARE @update_referential_action TINYINT;
DECLARE @tsql NVARCHAR(4000);
DECLARE @tsql2 NVARCHAR(4000);
DECLARE @fkCol SYSNAME;
DECLARE @pkCol SYSNAME;
DECLARE @col1 BIT;
DECLARE @action CHAR(6);
DECLARE @referenced_schema_name SYSNAME;
--------------------------------Generate scripts to drop all foreign keys in a database --------------------------------
IF OBJECT_ID('dbo.sync_dropFK') IS NOT NULL
DROP TABLE sync_dropFK
CREATE TABLE sync_dropFK
(
ID INT IDENTITY (1,1) NOT NULL
, Script NVARCHAR(4000)
)
DECLARE FKcursor CURSOR FOR
SELECT
OBJECT_SCHEMA_NAME(parent_object_id)
, OBJECT_NAME(parent_object_id)
, name
FROM
sys.foreign_keys WITH (NOLOCK)
ORDER BY
1,2;
OPEN FKcursor;
FETCH NEXT FROM FKcursor INTO
@schema_name
, @table_name
, @constraint_name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @tsql = 'ALTER TABLE '
+ QUOTENAME(@schema_name)
+ '.'
+ QUOTENAME(@table_name)
+ ' DROP CONSTRAINT '
+ QUOTENAME(@constraint_name)
+ ';';
--PRINT @tsql;
INSERT sync_dropFK (
Script
)
VALUES (
@tsql
)
FETCH NEXT FROM FKcursor INTO
@schema_name
, @table_name
, @constraint_name
;
END;
CLOSE FKcursor;
DEALLOCATE FKcursor;
---------------Generate scripts to create all existing foreign keys in a database --------------------------------
----------------------------------------------------------------------------------------------------------
IF OBJECT_ID('dbo.sync_createFK') IS NOT NULL
DROP TABLE sync_createFK
CREATE TABLE sync_createFK
(
ID INT IDENTITY (1,1) NOT NULL
, Script NVARCHAR(4000)
)
IF OBJECT_ID('dbo.sync_createCHECK') IS NOT NULL
DROP TABLE sync_createCHECK
CREATE TABLE sync_createCHECK
(
ID INT IDENTITY (1,1) NOT NULL
, Script NVARCHAR(4000)
)
DECLARE FKcursor CURSOR FOR
SELECT
OBJECT_SCHEMA_NAME(parent_object_id)
, OBJECT_NAME(parent_object_id)
, name
, OBJECT_NAME(referenced_object_id)
, OBJECT_ID
, is_disabled
, is_not_for_replication
, is_not_trusted
, delete_referential_action
, update_referential_action
, OBJECT_SCHEMA_NAME(referenced_object_id)
FROM
sys.foreign_keys WITH (NOLOCK)
ORDER BY
1,2;
OPEN FKcursor;
FETCH NEXT FROM FKcursor INTO
@schema_name
, @table_name
, @constraint_name
, @referenced_object_name
, @constraint_object_id
, @is_disabled
, @is_not_for_replication
, @is_not_trusted
, @delete_referential_action
, @update_referential_action
, @referenced_schema_name;
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN
SET @tsql = 'ALTER TABLE '
+ QUOTENAME(@schema_name)
+ '.'
+ QUOTENAME(@table_name)
+ CASE
@is_not_trusted
WHEN 0 THEN ' WITH CHECK '
ELSE ' WITH NOCHECK '
END
+ ' ADD CONSTRAINT '
+ QUOTENAME(@constraint_name)
+ ' FOREIGN KEY (';
SET @tsql2 = '';
DECLARE ColumnCursor CURSOR FOR
SELECT
COL_NAME(fk.parent_object_id
, fkc.parent_column_id)
, COL_NAME(fk.referenced_object_id
, fkc.referenced_column_id)
FROM
sys.foreign_keys fk WITH (NOLOCK)
INNER JOIN sys.foreign_key_columns fkc WITH (NOLOCK) ON fk.[object_id] = fkc.constraint_object_id
WHERE
fkc.constraint_object_id = @constraint_object_id
ORDER BY
fkc.constraint_column_id;
OPEN ColumnCursor;
SET @col1 = 1;
FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@col1 = 1)
SET @col1 = 0;
ELSE
BEGIN
SET @tsql = @tsql + ',';
SET @tsql2 = @tsql2 + ',';
END;
SET @tsql = @tsql + QUOTENAME(@fkCol);
SET @tsql2 = @tsql2 + QUOTENAME(@pkCol);
--PRINT '@tsql = ' + @tsql
--PRINT '@tsql2 = ' + @tsql2
FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;
--PRINT 'FK Column ' + @fkCol
--PRINT 'PK Column ' + @pkCol
END;
CLOSE ColumnCursor;
DEALLOCATE ColumnCursor;
SET @tsql = @tsql + ' ) REFERENCES '
+ QUOTENAME(@referenced_schema_name)
+ '.'
+ QUOTENAME(@referenced_object_name)
+ ' ('
+ @tsql2 + ')';
SET @tsql = @tsql
+ ' ON UPDATE '
+
CASE @update_referential_action
WHEN 0 THEN 'NO ACTION '
WHEN 1 THEN 'CASCADE '
WHEN 2 THEN 'SET NULL '
ELSE 'SET DEFAULT '
END
+ ' ON DELETE '
+
CASE @delete_referential_action
WHEN 0 THEN 'NO ACTION '
WHEN 1 THEN 'CASCADE '
WHEN 2 THEN 'SET NULL '
ELSE 'SET DEFAULT '
END
+
CASE @is_not_for_replication
WHEN 1 THEN ' NOT FOR REPLICATION '
ELSE ''
END
+ ';';
END;
-- PRINT @tsql
INSERT sync_createFK
(
Script
)
VALUES (
@tsql
)
-------------------Generate CHECK CONSTRAINT scripts for a database ------------------------------
----------------------------------------------------------------------------------------------------------
BEGIN
SET @tsql = 'ALTER TABLE '
+ QUOTENAME(@schema_name)
+ '.'
+ QUOTENAME(@table_name)
+
CASE @is_disabled
WHEN 0 THEN ' CHECK '
ELSE ' NOCHECK '
END
+ 'CONSTRAINT '
+ QUOTENAME(@constraint_name)
+ ';';
--PRINT @tsql;
INSERT sync_createCHECK
(
Script
)
VALUES (
@tsql
)
END;
FETCH NEXT FROM FKcursor INTO
@schema_name
, @table_name
, @constraint_name
, @referenced_object_name
, @constraint_object_id
, @is_disabled
, @is_not_for_replication
, @is_not_trusted
, @delete_referential_action
, @update_referential_action
, @referenced_schema_name;
END;
CLOSE FKcursor;
DEALLOCATE FKcursor;
--SELECT * FROM sync_DropFK
--SELECT * FROM sync_CreateFK
--SELECT * FROM sync_CreateCHECK
---------------------------------------------------------------------------
2.)
-----------------------------------------------------------------------------------------------------------------
----------------------------execute Drop FK Scripts --------------------------------------------------
DECLARE @scriptD NVARCHAR(4000)
DECLARE DropFKCursor CURSOR FOR
SELECT Script
FROM sync_dropFK WITH (NOLOCK)
OPEN DropFKCursor
FETCH NEXT FROM DropFKCursor
INTO @scriptD
WHILE @@FETCH_STATUS = 0
BEGIN
--PRINT @scriptD
EXEC (@scriptD)
FETCH NEXT FROM DropFKCursor
INTO @scriptD
END
CLOSE DropFKCursor
DEALLOCATE DropFKCursor
--------------------------------------------------------------------------------
3.)
------------------------------------------------------------------------------------------------------------------
----------------------------Truncate all tables in the database other than our staging tables --------------------
------------------------------------------------------------------------------------------------------------------
EXEC sp_MSforeachtable 'IF OBJECT_ID(''?'') NOT IN
(
ISNULL(OBJECT_ID(''dbo.sync_createCHECK''),0),
ISNULL(OBJECT_ID(''dbo.sync_createFK''),0),
ISNULL(OBJECT_ID(''dbo.sync_dropFK''),0)
)
BEGIN TRY
TRUNCATE TABLE ?
END TRY
BEGIN CATCH
PRINT ''Truncation failed on''+ ? +''
END CATCH;'
GO
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
----------------------------execute Create FK Scripts and CHECK CONSTRAINT Scripts---------------
----------------------------tack me at the end of the ETL in a SQL task-------------------------
-------------------------------------------------------------------------------------------------
DECLARE @scriptC NVARCHAR(4000)
DECLARE CreateFKCursor CURSOR FOR
SELECT Script
FROM sync_createFK WITH (NOLOCK)
OPEN CreateFKCursor
FETCH NEXT FROM CreateFKCursor
INTO @scriptC
WHILE @@FETCH_STATUS = 0
BEGIN
--PRINT @scriptC
EXEC (@scriptC)
FETCH NEXT FROM CreateFKCursor
INTO @scriptC
END
CLOSE CreateFKCursor
DEALLOCATE CreateFKCursor
-------------------------------------------------------------------------------------------------
DECLARE @scriptCh NVARCHAR(4000)
DECLARE CreateCHECKCursor CURSOR FOR
SELECT Script
FROM sync_createCHECK WITH (NOLOCK)
OPEN CreateCHECKCursor
FETCH NEXT FROM CreateCHECKCursor
INTO @scriptCh
WHILE @@FETCH_STATUS = 0
BEGIN
--PRINT @scriptCh
EXEC (@scriptCh)
FETCH NEXT FROM CreateCHECKCursor
INTO @scriptCh
END
CLOSE CreateCHECKCursor
DEALLOCATE CreateCHECKCursor
If you have
@Transactional // Spring Transactional
class MyDao extends Dao {
}
and super-class
class Dao {
public void save(Entity entity) { getEntityManager().merge(entity); }
}
and you call
@Autowired MyDao myDao;
myDao.save(entity);
you won't get a Spring TransactionInterceptor (that gives you a transaction).
This is what you need to do:
@Transactional
class MyDao extends Dao {
public void save(Entity entity) { super.save(entity); }
}
Unbelievable but true.
import java.util.*;
class Maxmin
{
public static void main(String args[])
{
int[] arr = new int[10];
Scanner in = new Scanner(System.in);
int i, min=0, max=0;
for(i=0; i<=arr.length; i++)
{
System.out.print("Enter any number: ");
arr[i] = in.nextInt();
}
min = arr[0];
for(i=0; i<=9; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
if(arr[i] < min)
{
min = arr[i];
}
}
System.out.println("Maximum is: " + max);
System.out.println("Minimum is: " + min);
}
}
typeof myObj.prop2 === 'function';
will let you know if the function is defined.
if(typeof myObj.prop2 === 'function') {
alert("It's a function");
} else if (typeof myObj.prop2 === 'undefined') {
alert("It's undefined");
} else {
alert("It's neither undefined nor a function. It's a " + typeof myObj.prop2);
}
<a href="javascript:alert('Hello!');">Clicky</a>
EDIT, years later: NO! Don't ever do this! I was young and stupid!
Edit, again: A couple people have asked why you shouldn't do this. There's a couple reasons:
Presentation: HTML should focus on presentation. Putting JS in an HREF means that your HTML is now, kinda, dealing with business logic.
Security: Javascript in your HTML like that violates Content Security Policy (CSP). Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware. Read more here.
Accessibility: Anchor tags are for linking to other documents/pages/resources. If your link doesn't go anywhere, it should be a button. This makes it a lot easier for screen readers, braille terminals, etc, to determine what's going on, and give visually impaired users useful information.
You can also use COALESCE ( expression [ ,...n ] ) - returns first non-null like:
SELECT COALESCE(MAX(X),0) AS MaxX
FROM tbl
WHERE XID = 1
If you're okay with loosing array keys, you may flatten a multi-dimensional array using a recursive closure as a callback that utilizes array_values(), making sure that this callback is a parameter for array_walk(), as follows.
<?php
$array = [1,2,3,[5,6,7]];
$nu_array = null;
$callback = function ( $item ) use(&$callback, &$nu_array) {
if (!is_array($item)) {
$nu_array[] = $item;
}
else
if ( is_array( $item ) ) {
foreach( array_values($item) as $v) {
if ( !(is_array($v))) {
$nu_array[] = $v;
}
else
{
$callback( $v );
continue;
}
}
}
};
array_walk($array, $callback);
print_r($nu_array);
The one drawback of the preceding example is that it involves writing far more code than the following solution which uses array_walk_recursive() along with a simplified callback:
<?php
$array = [1,2,3,[5,6,7]];
$nu_array = [];
array_walk_recursive($array, function ( $item ) use(&$nu_array )
{
$nu_array[] = $item;
}
);
print_r($nu_array);
See live code
This example seems preferable to the previous one, hiding the details about how values are extracted from a multidimensional array. Surely, iteration occurs, but whether it entails recursion or control structure(s), you'll only know from perusing array.c. Since functional programming focuses on input and output rather than the minutiae of obtaining a result, surely one can remain unconcerned about how behind-the-scenes iteration occurs, that is until a perspective employer poses such a question.
SELECT c1, c2, c3, ... INTO @v1, @v2, @v3,... FROM table_name WHERE condition;
It is a Generic Type Parameter.
A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.
For example:
public T[] Reverse<T>(T[] array)
{
var result = new T[array.Length];
int j=0;
for(int i=array.Length - 1; i>= 0; i--)
{
result[j] = array[i];
j++;
}
return result;
}
reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.
So, to reverse an array of strings:
string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);
Will produce a string array in result
of { "5", "4", "3", "2", "1" }
This has the same effect as if you had called an ordinary (non-generic) method that looks like this:
public string[] Reverse(string[] array)
{
var result = new string[array.Length];
int j=0;
for(int i=array.Length - 1; i >= 0; i--)
{
result[j] = array[i];
j++;
}
return result;
}
The compiler sees that array
contains strings, so it returns an array of strings. Type string
is substituted for the T
type parameter.
Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>
, the T
is a placeholder for an arbitrary type; it means that SampleCollection
can represent a collection of objects, the type of which you specify when you create the collection.
So:
var collection = new SampleCollection<string>();
creates a collection that can hold strings. The Reverse
method illustrated above, in a somewhat different form, can be used to reverse the collection's members.
think works
Criteria criteria = getSession().createCriteria(clazz);
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"),
Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"),
Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));
Probably you've found how to do it, but you can call
ListView.setItemsCanFocus(true)
and now your buttons will catch focus
In the Xcode 6.2, this also works
let appDelegate = UIApplication.sharedApplication().delegate! as AppDelegate
let aVariable = appDelegate.someVariable
You may use requests
library to find if website is up i.e. status code
as 200
import requests
url = "https://www.google.com"
page = requests.get(url)
print (page.status_code)
>> 200
const arr = Array.from({ length: 10 }).fill(0)
_x000D_
"Only conventions? Or is there more behind the underscore prefix?"
Apart from privacy conventions, I also wanted to help bring awareness that the underscore prefix is also used for arguments that are dependent on independent arguments, specifically in URI anchor maps. Dependent keys always point to a map.
Example ( from https://github.com/mmikowski/urianchor ) :
$.uriAnchor.setAnchor({
page : 'profile',
_page : {
uname : 'wendy',
online : 'today'
}
});
The URI anchor on the browser search field is changed to:
\#!page=profile:uname,wendy|online,today
This is a convention used to drive an application state based on hash changes.
You can hide a JPanel by calling setVisible(false)
. For example:
public static void main(String args[]){
JFrame f = new JFrame();
f.setLayout(new BorderLayout());
final JPanel p = new JPanel();
p.add(new JLabel("A Panel"));
f.add(p, BorderLayout.CENTER);
//create a button which will hide the panel when clicked.
JButton b = new JButton("HIDE");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
p.setVisible(false);
}
});
f.add(b,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
module.js:
const foo = function(<params>) { ... }
const bar = function(<params>) { ... }
//export modules
module.exports = {
foo,
bar
}
main.js:
// import modules
var { foo, bar } = require('module');
// pass your parameters
var f1 = foo(<params>);
var f2 = bar(<params>);
WebAPI 2 now has a package for CORS which can be installed using :
Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebServic
Once this is installed, follow this for the code :http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Apply 100%
width and height to your image:
<div style="height:42px;width:42px">
<img src="http://someimage.jpg" style="width:100%; height:100%">
</div>
This way it will same size of its parent.
I also received this error when the service stopped. Here's another path to start your service...
Note: As Kenan stated, if your services Startup Type is not set to Automatic, then you probably want to double click on the service and set it to Automatic.
Neither the question nor the answers really fit my simple way of thinking about it. I'm a consultant and have synchronized these definitions with a number of Dev teams and DevOps people, but am curious about how it matches with the industry at large:
Basically I think of the agile practice of continuous delivery like a continuum:
Not continuous (everything manual) 0% ----> 100% Continuous Delivery of Value (everything automated)
Steps towards continuous delivery:
Zero. Nothing is automated when devs check in code... You're lucky if they have compiled, run, or performed any testing prior to check-in.
Continuous Build: automated build on every check-in, which is the first step, but does nothing to prove functional integration of new code.
Continuous Integration (CI): automated build and execution of at least unit tests to prove integration of new code with existing code, but preferably integration tests (end-to-end).
Continuous Deployment (CD): automated deployment when code passes CI at least into a test environment, preferably into higher environments when quality is proven either via CI or by marking a lower environment as PASSED after manual testing. I.E., testing may be manual in some cases, but promoting to next environment is automatic.
Continuous Delivery: automated publication and release of the system into production. This is CD into production plus any other configuration changes like setup for A/B testing, notification to users of new features, notifying support of new version and change notes, etc.
EDIT: I would like to point out that there's a difference between the concept of "continuous delivery" as referenced in the first principle of the Agile Manifesto (http://agilemanifesto.org/principles.html) and the practice of Continuous Delivery, as seems to be referenced by the context of the question. The principle of continuous delivery is that of striving to reduce the Inventory waste as described in Lean thinking (http://www.miconleansixsigma.com/8-wastes.html). The practice of Continuous Delivery (CD) by agile teams has emerged in the many years since the Agile Manifesto was written in 2001. This agile practice directly addresses the principle, although they are different things and apparently easily confused.
The answer is in the current spec:
The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.
Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.
Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element.
The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.
Reference:
Also see:
It looks like there's been a lot of confusion about this element's purpose, but the one thing that's agreed upon is that it is not a generic wrapper, like <div>
is. It should be used for semantic purposes, and not a CSS or JavaScript hook (although it certainly can be styled or "scripted").
A better example, from my understanding, might look something like this:
<div id="content">
<article>
<h2>How to use the section tag</h2>
<section id="disclaimer">
<h3>Disclaimer</h3>
<p>Don't take my word for it...</p>
</section>
<section id="examples">
<h3>Examples</h3>
<p>But here's how I would do it...</p>
</section>
<section id="closing_notes">
<h3>Closing Notes</h3>
<p>Well that was fun. I wonder if the spec will change next week?</p>
</section>
</article>
</div>
Note that <div>
, being completely non-semantic, can be used anywhere in the document that the HTML spec allows it, but is not necessary.
Adding 'random' numbers to URLs seems inelegant and expensive to me. It also spoils the URL of the pages, which can look like index.html?t=1614333283241
and btw users will have dozens of URLs cached for only one use.
I think this kind of things is what .htaccess
files are meant to solve at the server side, between your functional code an the users.
I copy/paste this code from here that allows filtering by file extension to force the browser not to cache them. If you want to return to normal behavior, just delete or comment it.
Create or edit an .htaccess
file on every folder you want to prevent caching, then paste this code changing file extensions to your needs, or even to match one individual file.
If the file already exists on your host be cautious modifying what's in it.
(kudos to the link)
# DISABLE CACHING
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
<FilesMatch "\.(css|flv|gif|htm|html|ico|jpe|jpeg|jpg|js|mp3|mp4|png|pdf|swf|txt)$">
<IfModule mod_expires.c>
ExpiresActive Off
</IfModule>
<IfModule mod_headers.c>
FileETag None
Header unset ETag
Header unset Pragma
Header unset Cache-Control
Header unset Last-Modified
Header set Pragma "no-cache"
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Expires "jue, 1 Jan 1970 00:00:00 GMT"
</IfModule>
</FilesMatch>
To be relative to the root directory, just start the URI with a /
<link type="text/css" rel="stylesheet" href="/style.css" />
<script src="/script.js" type="text/javascript"></script>
Copy because it was disallowed to improve answer. Thanks SO
string test = "Hello World";
for(auto& c : test)
{
c = tolower(c);
}
Explanation:
for(auto& c : test)
is a range-based for loop of the kind
for (
range_declaration
:
range_expression
)
loop_statement
:
range_declaration
: auto& c
Here the auto specifier is used for for automatic type deduction. So the type gets deducted from the variables initializer.
range_expression
: test
The range in this case are the characters of string test
.
The characters of the string test
are available as a reference inside the for loop through identifier c
.
I assume from db
that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);
Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).
For a trivial example of the type of thing you can do:
select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };
You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...
Yes, it is absolutely no problem. You could even have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.
In fact, i have such a setup myself.
You can set your cookie value containing expiry and get your expiry from cookie value.
// set
$expiry = time()+3600;
setcookie("mycookie", "mycookievalue|$expiry", $expiry);
// get
if (isset($_COOKIE["mycookie"])) {
list($value, $expiry) = explode("|", $_COOKIE["mycookie"]);
}
// Remember, some two-way encryption would be more secure in this case. See: https://github.com/qeremy/Cryptee
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
check
System.getProperty("sun.jnu.encoding")
it seems to be the same encoding as the one used in your system's command line.
What about something like this:
First resample the data frame into 1D intervals. This takes the mean of the values for all duplicate days. Use the fill_method
option to fill in missing date values. Next, pass the resampled frame into pd.rolling_mean
with a window of 3 and min_periods=1 :
pd.rolling_mean(df.resample("1D", fill_method="ffill"), window=3, min_periods=1)
favorable unfavorable other
enddate
2012-10-25 0.495000 0.485000 0.025000
2012-10-26 0.527500 0.442500 0.032500
2012-10-27 0.521667 0.451667 0.028333
2012-10-28 0.515833 0.450000 0.035833
2012-10-29 0.488333 0.476667 0.038333
2012-10-30 0.495000 0.470000 0.038333
2012-10-31 0.512500 0.460000 0.029167
2012-11-01 0.516667 0.456667 0.026667
2012-11-02 0.503333 0.463333 0.033333
2012-11-03 0.490000 0.463333 0.046667
2012-11-04 0.494000 0.456000 0.043333
2012-11-05 0.500667 0.452667 0.036667
2012-11-06 0.507333 0.456000 0.023333
2012-11-07 0.510000 0.443333 0.013333
UPDATE: As Ben points out in the comments, with pandas 0.18.0 the syntax has changed. With the new syntax this would be:
df.resample("1d").sum().fillna(0).rolling(window=3, min_periods=1).mean()
You can use for helper column also VLOOKUP
. I tested and looks little bit faster than COUNTIF
.
If you are using header and data are starting in cell A2
, then in any cell in row use this formula and copy in all other cells in the same column:
=IFERROR(IF(VLOOKUP(A2;$A$1:A1;1;0)=A2;0;1);1)
Find that dll on your PC, and copy it into the same directory your executable is in.
You can create a function:
CREATE FUNCTION dbo.[Check_existance_of_carriage_return_line_feed]
(
@String VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
BEGIN
DECLARE @RETURN_BOOLEAN INT
;WITH N1 (n) AS (SELECT 1 UNION ALL SELECT 1),
N2 (n) AS (SELECT 1 FROM N1 AS X, N1 AS Y),
N3 (n) AS (SELECT 1 FROM N2 AS X, N2 AS Y),
N4 (n) AS (SELECT ROW_NUMBER() OVER(ORDER BY X.n)
FROM N3 AS X, N3 AS Y)
SELECT @RETURN_BOOLEAN =COUNT(*)
FROM N4 Nums
WHERE Nums.n<=LEN(@String) AND ASCII(SUBSTRING(@String,Nums.n,1))
IN (13,10)
RETURN (CASE WHEN @RETURN_BOOLEAN >0 THEN 'TRUE' ELSE 'FALSE' END)
END
GO
Then you can simple run a query like this:
SELECT column_name, dbo.[Check_existance_of_carriage_return_line_feed] (column_name)
AS [Boolean]
FROM [table_name]
Günter's answer is great (question is asking for dynamic class attribute) but I thought I would add just for completeness...
If you're looking for a quick and clean way to add one or more static classes to the host element of your component (i.e., for theme-styling purposes) you can just do:
@Component({
selector: 'my-component',
template: 'app-element',
host: {'class': 'someClass1'}
})
export class App implements OnInit {
...
}
And if you use a class on the entry tag, Angular will merge the classes, i.e.,
<my-component class="someClass2">
I have both someClass1 & someClass2 applied to me
</my-component>
We can also remove it using match
var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);
During the download of wamp server from wampserver website you get a warning..
WARNING : Vous devez avoir installé Visual Studio 2012 : VC 11 vcredist_x64/86.exe Visual Studio 2012 VC 11 vcredist_x64/86.exe : http://www.microsoft.com/en-us/download/details.aspx?id=30679
So if you install the vcredist_xxx.exe it will be ok
The simplest way to fill the shape with the Radius is:
XML:
<TextView
android:id="@+id/textView"
android:background="@drawable/test"
android:layout_height="45dp"
android:layout_width="100dp"
android:text="Moderate"/>
Java:
(textView.getBackground()).setColorFilter(Color.parseColor("#FFDE03"), PorterDuff.Mode.SRC_IN);
Some plugins require one to run as an Administrator
and will not load unless one has those credentials active in the shell.
A lot of C projects end up implementing a vector-like API. Dynamic arrays are such a common need, that it's nice to abstract away the memory management as much as possible. A typical C implementation might look something like:
typedef struct dynamic_array_struct
{
int* data;
size_t capacity; /* total capacity */
size_t size; /* number of elements in vector */
} vector;
Then they would have various API function calls which operate on the vector
:
int vector_init(vector* v, size_t init_capacity)
{
v->data = malloc(init_capacity * sizeof(int));
if (!v->data) return -1;
v->size = 0;
v->capacity = init_capacity;
return 0; /* success */
}
Then of course, you need functions for push_back
, insert
, resize
, etc, which would call realloc
if size
exceeds capacity
.
vector_resize(vector* v, size_t new_size);
vector_push_back(vector* v, int element);
Usually, when a reallocation is needed, capacity
is doubled to avoid reallocating all the time. This is usually the same strategy employed internally by std::vector
, except typically std::vector
won't call realloc
because of C++ object construction/destruction. Rather, std::vector
might allocate a new buffer, and then copy construct/move construct the objects (using placement new
) into the new buffer.
An actual vector implementation in C might use void*
pointers as elements rather than int
, so the code is more generic. Anyway, this sort of thing is implemented in a lot of C projects. See http://codingrecipes.com/implementation-of-a-vector-data-structure-in-c for an example vector implementation in C.
BufferedReader
can't wrap an InputStream
directly. It wraps another Reader
. In this case you'd want to do something like:
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
you could probably use the gzip -t option to test the files integrity
http://linux.about.com/od/commands/l/blcmdl1_gzip.htm
To test the gzip file is not corrupt:
gunzip -t file.tar.gz
To test the tar file inside is not corrupt:
gunzip -c file.tar.gz | tar -t > /dev/null
As part of the backup you could probably just run the latter command and check the value of $? afterwards for a 0 (success) value. If either the tar or the gzip has an issue, $? will have a non zero value.
Hey guys this is a good way of link w/ image and has lot of props in case you want to css attribute for example replace "alt" or "title" etc.....also including a logical restriction (?)
<%= link_to image_tag("#{request.ssl? ? @image_domain_secure : @image_domain}/images/linkImage.png", {:alt=>"Alt title", :title=>"Link title"}) , "http://www.site.com"%>
Hope this helps!
Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters
Special Parameters
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is,"$*"
is equivalent to"$1c$2c..."
, wherec
is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is,"$@"
is equivalent to"$1"
"$2"
... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters,"$@"
and$@
expand to nothing (i.e., they are removed).
Video tag supports only video formats (like mp4 etc). Youtube does not expose its raw video files - it only exposes the unique id of the video. Since that id does not correspond to the actual file, video tag cannot be used.
If you do get hold of the actual source file using one of the youtube download sites or soft wares, you will be able to use the video tag. But even then, the url of the actual source will cease to work after a set time. So your video also will work only till then.
In Android Studio 3.3 it is here:
According to the answer https://stackoverflow.com/a/49576954/2914140 in Android Studio 3.1 it is here:
This command is moved to File > Sync Project with Gradle Files
.
Get a shell of your running container and change the root pass.
docker exec -it <MyContainer> bash
root@MyContainer:/# passwd
Enter new UNIX password:
Retype new UNIX password:
I'd suggest using such extension method:
public static class DataColumnCollectionExtensions
{
public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
{
return source.Cast<DataColumn>();
}
}
And therefore:
string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();
You may also implement one more extension method for DataTable
class to reduce code:
public static class DataTableExtensions
{
public static IEnumerable<DataColumn> GetColumns(this DataTable source)
{
return source.Columns.AsEnumerable();
}
}
And use it as follows:
string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();
I'd use request for this:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:
var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
if (!error && response.statusCode == 200) {
var csv = body;
// Continue with your processing here.
}
});
etc.
Is it as optional functionality.
If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.
If you will provide restore mechanism then your purchase manager will see restored transaction.
If app should distinguish this options then you should provide functionality for restoring previously purchased products.
I have seen this error occur when the plugins that are needed are not specifically mentioned in the pom. So
mvn clean install
will give the exception if this is not added:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
Likewise,
mvn clean install deploy
will fail on the same exception if something like this is not added:
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.1</version>
<executions>
<execution>
<id>default-deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
It makes sense, but a clearer error message would be welcome
I would just not add it in the first place:
var sb = new StringBuilder();
bool first = true;
foreach (var foo in items) {
if (first)
first = false;
else
sb.Append('&');
// for example:
var escapedValue = System.Web.HttpUtility.UrlEncode(foo);
sb.Append(key).Append('=').Append(escapedValue);
}
var s = sb.ToString();
The folks from sqlite.org have taken over the development of the ADO.NET provider:
From their homepage:
This is a fork of the popular ADO.NET 4.0 adaptor for SQLite known as System.Data.SQLite. The originator of System.Data.SQLite, Robert Simpson, is aware of this fork, has expressed his approval, and has commit privileges on the new Fossil repository. The SQLite development team intends to maintain System.Data.SQLite moving forward.
Historical versions, as well as the original support forums, may still be found at http://sqlite.phxsoftware.com, though there have been no updates to this version since April of 2010.
The complete list of features can be found at on their wiki. Highlights include
Released DLLs can be downloaded directly from the site.
Due to my low reputation I couldn't comment on Derek ????'s answer. I've tried that code as it is and it didn't work well. There are three issues on Derek ????'s code.
The first is that the time to async send the request and change its property 'status' is slower than to execute the next expression - if(request.status === "404"). So the request.status will eventually, due to internet band, remain on status 0 (zero), and it won't achieve the code right below if. To fix that is easy: change 'true' to 'false' on method open of the ajax request. This will cause a brief (or not so) block on your code (due to synchronous call), but will change the status of the request before reaching the test on if.
The second is that the status is an integer. Using '===' javascript comparison operator you're trying to compare if the left side object is identical to one on the right side. To make this work there are two ways:
The third is that the object XMLHttpRequest only works on newer browsers (Firefox, Chrome and IE7+). If you want that snippet to work on all browsers you have to do in the way W3Schools suggests: w3schools ajax
The code that really worked for me was:
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'http://www.mozilla.org', false);
request.send(); // there will be a 'pause' here until the response to come.
// the object request will be actually modified
if (request.status === 404) {
alert("The page you are trying to reach is not available.");
}
This answer will help in case, If you are working with Data Bases then mostly take the help of try-catch block statement, which will help and guide you with your code. Here i am showing you that how to insert some values in Data Base with a Button Click Event.
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data source= C:\Users\pir fahim shah\Documents\TravelAgency.accdb";
try
{
conn.Open();
String ticketno=textBox1.Text.ToString();
String Purchaseprice=textBox2.Text.ToString();
String sellprice=textBox3.Text.ToString();
String my_querry = "INSERT INTO Table1(TicketNo,Sellprice,Purchaseprice)VALUES('"+ticketno+"','"+sellprice+"','"+Purchaseprice+"')";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to"+ex.Message);
}
finally
{
conn.Close();
}
To convert the private key from PKCS#1 to PKCS#8 with openssl:
# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key
That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.
You can use scalar multiplication to modify each element in your vector.
> r <- 0:10
> r <- r * 2
> r
[1] 0 2 4 6 8 10 12 14 16 18 20
or
> r <- 0:10 * 2
> r
[1] 0 2 4 6 8 10 12 14 16 18 20
I've come across this problem on Typescript Version 3.8.3.
Intellisense is the best thing we could have but for me, the auto-import feature doesn't seem to work either. I've tried installing an extension even though auto-import didn't work. I've rechecked all the settings related to extensions. Finally, the auto-import feature started working when I clear the cache, from
C:\Users\username\AppData\Roaming\Code\Cache
& reload the VSCode
Note: AppData can only be visible in username if you select, Show (Hidden Items) from (View) Menu.
In some cases, we may end up thinking there is an import related error, while in actuality, unknowingly we might be coding using deprecated features or APIs in angular.
For example: if you're trying to code something like this
constructor (http: Http) {
//...}
Where Http is already deprecated and replaced with HttpClient in the newer version, so we may end up thinking an error related to this might be related to the auto-import error. For more information, you can refer Deprecated APIs and Features
Other answers did a great job of explaining differences between interfaces and traits. I will focus on a useful real world example, in particular one which demonstrates that traits can use instance variables - allowing you add behavior to a class with minimal boilerplate code.
Again, like mentioned by others, traits pair well with interfaces, allowing the interface to specify the behavior contract, and the trait to fulfill the implementation.
Adding event publish / subscribe capabilities to a class can be a common scenario in some code bases. There's 3 common solutions:
use
the trait, aka import it, to gain the capabilities.How well does each work?
#1 Doesn't work well. It would, until the day you realize you can't extend the base class because you're already extending something else. I won't show an example of this because it should be obvious how limiting it is to use inheritance like this.
#2 & #3 both work well. I'll show an example which highlights some differences.
First, some code that will be the same between both examples:
An interface
interface Observable {
function addEventListener($eventName, callable $listener);
function removeEventListener($eventName, callable $listener);
function removeAllEventListeners($eventName);
}
And some code to demonstrate usage:
$auction = new Auction();
// Add a listener, so we know when we get a bid.
$auction->addEventListener('bid', function($bidderName, $bidAmount){
echo "Got a bid of $bidAmount from $bidderName\n";
});
// Mock some bids.
foreach (['Moe', 'Curly', 'Larry'] as $name) {
$auction->addBid($name, rand());
}
Ok, now lets show how the implementation of the Auction
class will differ when using traits.
First, here's how #2 (using composition) would look like:
class EventEmitter {
private $eventListenersByName = [];
function addEventListener($eventName, callable $listener) {
$this->eventListenersByName[$eventName][] = $listener;
}
function removeEventListener($eventName, callable $listener) {
$this->eventListenersByName[$eventName] = array_filter($this->eventListenersByName[$eventName], function($existingListener) use ($listener) {
return $existingListener === $listener;
});
}
function removeAllEventListeners($eventName) {
$this->eventListenersByName[$eventName] = [];
}
function triggerEvent($eventName, array $eventArgs) {
foreach ($this->eventListenersByName[$eventName] as $listener) {
call_user_func_array($listener, $eventArgs);
}
}
}
class Auction implements Observable {
private $eventEmitter;
public function __construct() {
$this->eventEmitter = new EventEmitter();
}
function addBid($bidderName, $bidAmount) {
$this->eventEmitter->triggerEvent('bid', [$bidderName, $bidAmount]);
}
function addEventListener($eventName, callable $listener) {
$this->eventEmitter->addEventListener($eventName, $listener);
}
function removeEventListener($eventName, callable $listener) {
$this->eventEmitter->removeEventListener($eventName, $listener);
}
function removeAllEventListeners($eventName) {
$this->eventEmitter->removeAllEventListeners($eventName);
}
}
Here's how #3 (traits) would look like:
trait EventEmitterTrait {
private $eventListenersByName = [];
function addEventListener($eventName, callable $listener) {
$this->eventListenersByName[$eventName][] = $listener;
}
function removeEventListener($eventName, callable $listener) {
$this->eventListenersByName[$eventName] = array_filter($this->eventListenersByName[$eventName], function($existingListener) use ($listener) {
return $existingListener === $listener;
});
}
function removeAllEventListeners($eventName) {
$this->eventListenersByName[$eventName] = [];
}
protected function triggerEvent($eventName, array $eventArgs) {
foreach ($this->eventListenersByName[$eventName] as $listener) {
call_user_func_array($listener, $eventArgs);
}
}
}
class Auction implements Observable {
use EventEmitterTrait;
function addBid($bidderName, $bidAmount) {
$this->triggerEvent('bid', [$bidderName, $bidAmount]);
}
}
Note that the code inside the EventEmitterTrait
is exactly the same as what's inside the EventEmitter
class except the trait declares the triggerEvent()
method as protected. So, the only difference you need to look at is the implementation of the Auction
class.
And the difference is large. When using composition, we get a great solution, allowing us to reuse our EventEmitter
by as many classes as we like. But, the main drawback is the we have a lot of boilerplate code that we need to write and maintain because for each method defined in the Observable
interface, we need to implement it and write boring boilerplate code that just forwards the arguments onto the corresponding method in our composed the EventEmitter
object. Using the trait in this example lets us avoid that, helping us reduce boilerplate code and improve maintainability.
However, there may be times where you don't want your Auction
class to implement the full Observable
interface - maybe you only want to expose 1 or 2 methods, or maybe even none at all so that you can define your own method signatures. In such a case, you might still prefer the composition method.
But, the trait is very compelling in most scenarios, especially if the interface has lots of methods, which causes you to write lots of boilerplate.
* You could actually kinda do both - define the EventEmitter
class in case you ever want to use it compositionally, and define the EventEmitterTrait
trait too, using the EventEmitter
class implementation inside the trait :)
Your xpath is just a little off:
count(//Property/long[text()=$parPropId])
Edit: Cerebrus quite rightly points out that the code in your OP (using the implicit value of a node) is absolutely fine for your purposes. In fact, since it's quite likely you want to work with the "Property" node rather than the "long" node, it's probably superior to ask for //Property[long=$parPropId]
than the text() xpath, though you could make a case for the latter on readability grounds.
What can I say, I'm a bit tired today :)
Extract all gz files in current directory and its subdirectories:
find . -name "*.gz" | xargs gunzip
If you're dealing with a Java character array (such as password characters that you read from the console), you can convert it to a JRuby string with the following Ruby code:
# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"
jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}
# .. do something with 'password' variable ..
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"
See also "https://stackoverflow.com/a/27628738/4390019" and "https://stackoverflow.com/a/27628756/4390019"
This is the solution that I've came up with:
<form name = "form1" id = "form1" action = "#" method = "post">
<select name = "DropDownList1" id = "DropDownList1">
<?php
$arr = array('Yes', 'No', 'Fine' ); // create array so looping is easier
for( $i = 1; $i <= 3; $i++ ) // loop starts at first value and ends at last value
{
$selected = ''; // keep selected at nothing
if( isset( $_POST['go'] ) ) // check if form was submitted
{
if( $_POST['DropDownList1'] == $i ) // if the value of the dropdownlist is equal to the looped variable
{
$selected = 'selected = "selected"'; // if is equal, set selected = "selected"
}
}
// note: if value is not equal, selected stays defaulted to nothing as explained earlier
echo '<option value = "' . $i . '"' . $selected . '>' . $arr[$i] . '</option>'; // echo the option element to the page using the $selected variable
}
?>
</select> <!-- finish the form in html -->
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
</form>
The code I have works as long as the values are integers in some numeric order ( ascending or descending ). What it does is starts the dropdownlist in html, and adds each option element in php code. It will not work if you have random values though, i.e: 1, 4, 2, 7, 6. Each value must be unique.
for Swift 3.0 add image on leftside of textField
textField.leftView = UIImageView(image: "small-calendar")
textField.leftView?.frame = CGRect(x: 0, y: 5, width: 20 , height:20)
textField.leftViewMode = .always
You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.
Theres no shorthand way in vue 2.
Jeff's method seems already deprecated in vue 2.
Heres another way u can achieve your goal.
var app = new Vue({_x000D_
el:'#app',_x000D_
methods: { _x000D_
showMyDiv() {_x000D_
console.log(this.$refs.myDiv);_x000D_
}_x000D_
}_x000D_
_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id='app'>_x000D_
<div id="myDiv" ref="myDiv"></div>_x000D_
<button v-on:click="showMyDiv" >Show My Div</button>_x000D_
</div>
_x000D_
Python sequence slice addresses can be written as a[start:end:step] and any of start, stop or end can be dropped. a[::3]
is every third element of the sequence.
version with editable input:
<form>
<input type="range" name="amountRange" min="0" max="20" value="0" oninput="this.form.amountInput.value=this.value" />
<input type="number" name="amountInput" min="0" max="20" value="0" oninput="this.form.amountRange.value=this.value" />
</form>
After clone, for me push wasn't working.
Solution: Where repo is cloned open .git folder and config file.
For remote origin url set value:
[remote "origin"]
url = file:///C:/Documentation/git_server/kurmisoftware
using _.some
from lodash: https://lodash.com/docs/4.17.11#some
const array1AndArray2NotEqual =
_.some(array1, (a1, idx) => a1.key1 !== array2[idx].key1
|| a1.key2 !== array2[idx].key2
|| a1.key3 !== array2[idx].key3);
Option #1
As recommended here, this site provides a convenient, up-to-date one liner.
This doesn't overwrite the base version of PHP on your system, but instead installs it cleanly in /usr/local/php5.
Option #2
My preferred method is to just install via Homebrew.
In case of spring boot is being used , just config this :
aplication.yml
logging:
level:
org.hibernate.SQL: DEBUG
org.hibernate.type: TRACE
aplication.properties
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
and nothing more.
Your log will be something like this:
2020-12-07 | DEBUG | o.h.SQL:127 - insert into Employee (id, name, title, id) values (?, ?, ?, ?)
2020-12-07 | TRACE | o.h.t.d.s.BasicBinder:64 - binding parameter [1] as [VARCHAR] - [001]
2020-12-07 | TRACE | o.h.t.d.s.BasicBinder:64 - binding parameter [2] as [VARCHAR] - [John Smith]
2020-12-07 | TRACE | o.h.t.d.s.BasicBinder:52 - binding parameter [3] as [VARCHAR] - [null]
2020-12-07 | TRACE | o.h.t.d.s.BasicBinder:64 - binding parameter [4] as [BIGINT] - [1]
HTH
This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp()
and getClassName()
will work. You should also do something with the possible IOException
that can be thrown when using any of the java.io.*
classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id
is of type String
- I don't know as your code doesn't explicitly define it. If it is something else like an int
, you should probably cast it to a String
before using it in the fileName as I have done here.
Also, I replaced your append
calls with concat
or +
as I saw appropriate.
public void writeFile(String value){
String PATH = "/remote/dir/server/";
String directoryName = PATH.concat(this.getClassName());
String fileName = id + getTimeStamp() + ".txt";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
File file = new File(directoryName + "/" + fileName);
try{
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
}
catch (IOException e){
e.printStackTrace();
System.exit(-1);
}
}
You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the /
in the filenames. For full portability, you should probably use something like File.separator to construct your paths.
Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir()
call will return true
if it created a directory, and false
if it didn't, including the case when the directory already existed.
Please note that there is a mistake in the url provided in this answer:
For a PUT mapping request: the url should be as follows:
http://localhost:9200/name_of_index/_mappings/document_type
and NOT
Here's the correct code. If you're using zybooks this will answer all the problems.
for (int i = 0; i<passCode.length(); i++)
{
char letter = passCode.charAt(i);
if (letter == ' ' )
{
System.out.println("Space at " + i);
}
}
You might be interested in the calc
approach:
font-size: calc(4vw + 4vh + 2vmin);
done. Tweak values till matches your taste.
I had a similar situation: I needed to purge postgresql 9.1 on a debian wheezy ( I had previously migrated from 8.4 and I was getting errors ).
What I did:
First, I deleted config and database
$ sudo pg_dropcluster --stop 9.1 main
Then removed postgresql
$ sudo apt-get remove --purge postgresql postgresql-9.1
and then reinstalled
$ sudo apt-get install postgresql postgresql-9.1
In my case I noticed /etc/postgresql/9.1 was empty, and running service postgresql start
returned nothing
So, after more googling I got to this command:
$ sudo pg_createcluster 9.1 main
With that I could start the server, but now I was getting log-related errors. After more searching, I ended up changing permissions to the /var/log/postgresql directory
$ sudo chown root.postgres /var/log/postgresql
$ sudo chmod g+wx /var/log/postgresql
That fixed the issue, Hope this helps
using (FileStream fs = File.Create(path))
{
}
Will create or overwrite a file.
<div style='position:absolute; left:50%; top:50%; transform: translate(-50%, -50%)'>
This text is centered.
</div>
This will center all the objects inside div with position type static or relative.
Here is something that might help. Use the root privileges. if you have .bin then simply add the execution permission to the bin file.
chmod a+x jdk*.bin
next step is to run the .bin file which is simply
./jdk*.bin in the location you want to install.
you are done.
Try to use:
mvn clean package install
This command should install your artifacts in you local maven repo.
PS: I see that this is an old question, but it may be helpful for somebody in the future.
std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K
and V
.
Also bear in mind that std::sort
requires a strict weak ordeing comparison, and <=
does not satisfy that. You would need, for example, a less-than comparison <
for K
and V
. With that in place, all you need is
std::vector<pair<K,V>> items;
std::sort(items.begin(), items.end());
If you really need to provide your own comparison function, then you need something along the lines of
template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
{
return lhs.first < rhs.first;
}
<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>
This code you can write in Aspx. If you want this in some js.file, you have two ways:
Use the function Contains
from the strings package.
import (
"strings"
)
strings.Contains("something", "some") // true
public double distance(Double latitude, Double longitude, double e, double f) {
double d2r = Math.PI / 180;
double dlong = (longitude - f) * d2r;
double dlat = (latitude - e) * d2r;
double a = Math.pow(Math.sin(dlat / 2.0), 2) + Math.cos(e * d2r)
* Math.cos(latitude * d2r) * Math.pow(Math.sin(dlong / 2.0), 2)
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = 6367 * c;
return d;
}
The angle between each of your points is going to be 2Pi/x
so you can say that for points n= 0 to x-1
the angle from a defined 0 point is 2nPi/x
.
Assuming your first point is at (r,0)
(where r is the distance from the centre point) then the positions relative to the central point will be:
rCos(2nPi/x),rSin(2nPi/x)
I found out that my back-up project worked well if I precompile without bundle update
. Maybe something went wrong with gem updated but I don't know which gem has an error.
Nothing against the other answers, but I found the brief explanation in the docs more easily understandable than the examples in them:
func append
func append(slice []Type, elems ...Type) []Type
The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:slice = append(slice, elem1, elem2) slice = append(slice, anotherSlice...)
As a special case, it is legal to append a string to a byte slice, like this:
slice = append([]byte("hello "), "world"...)
for i, row in df.iterrows():
if <something>:
df.at[i, 'ifor'] = x
else:
df.at[i, 'ifor'] = y
The mappedBy
attribute is referencing customer
while the property is mCustomer
, hence the error message. So either change your mapping into:
/** The collection of stores. */
@OneToMany(mappedBy = "mCustomer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<Store> stores;
Or change the entity property into customer
(which is what I would do).
The mappedBy reference indicates "Go look over on the bean property named 'customer' on the thing I have a collection of to find the configuration."
You are trying to execute an asynchronous function
in a synchronous way, which is unfortunately not possible in Javascript
.
As you guessed correctly, the roomId=results
.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.
Look at this article, it talks about .insert and not .find
, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html
Queue<String> qe=new LinkedList<String>();
qe.add("b");
qe.add("a");
qe.add("c");
Since Queue
is an interface, you can't create an instance of it as you illustrated
For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});
Keep in mind that you'll need a timeout on your JSONP request to catch failures.
This can be done for a normal subview
inside a larger UIView
, but it doesn't work automatically for headerViews
. The height of a headerView
is determined by what's returned by tableView:heightForHeaderInSection:
so you have to calculate the height
based on the height
of the UILabel
plus space for the UIButton
and any padding
you need. You need to do something like this:
-(CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
NSString *s = self.headeString[indexPath.section];
CGSize size = [s sizeWithFont:[UIFont systemFontOfSize:17]
constrainedToSize:CGSizeMake(281, CGFLOAT_MAX)
lineBreakMode:NSLineBreakByWordWrapping];
return size.height + 60;
}
Here headerString
is whatever string you want to populate the UILabel
, and the 281 number is the width
of the UILabel
(as setup in Interface Builder
)
You might wanna try return new String(byteout.toByteArray(Charset.forName("UTF-8")))
A short answer is to add the following options when the JVM is started.
JAVA_OPTS=" $JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8080"
One reason to use the body in a delete request is for optimistic concurrency control.
You read version 1 of a record.
GET /some-resource/1
200 OK { id:1, status:"unimportant", version:1 }
Your colleague reads version 1 of the record.
GET /some-resource/1
200 OK { id:1, status:"unimportant", version:1 }
Your colleague changes the record and updates the database, which updates the version to 2:
PUT /some-resource/1 { id:1, status:"important", version:1 }
200 OK { id:1, status:"important", version:2 }
You try to delete the record:
DELETE /some-resource/1 { id:1, version:1 }
409 Conflict
You should get an optimistic lock exception. Re-read the record, see that it's important, and maybe not delete it.
Another reason to use it is to delete multiple records at a time (for example, a grid with row-selection check-boxes).
DELETE /messages
[{id:1, version:2},
{id:99, version:3}]
204 No Content
Notice that each message has its own version. Maybe you can specify multiple versions using multiple headers, but by George, this is simpler and much more convenient.
This works in Tomcat (7.0.52) and Spring MVC (4.05), possibly w earlier versions too:
@RestController
public class TestController {
@RequestMapping(value="/echo-delete", method = RequestMethod.DELETE)
SomeBean echoDelete(@RequestBody SomeBean someBean) {
return someBean;
}
}
Update: You can now just right click
Right click > Save as in the Console panel to save the logged messages to a file.
Original Answer:
You can use this devtools snippet shown below to create a console.save method. It creates a FileBlob from the input, and then automatically downloads it.
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
Source: http://bgrins.github.io/devtools-snippets/#console-save
This is something I do, (but usually with the MySQLi class).
$link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass");
mysql_select_db($MYSQL_db, $link);
// RUN REALLY LONG QUERY HERE
// Reconnect if needed
if( !mysql_ping($link) ) $link = mysql_connect("$MYSQL_Host","$MYSQL_User","$MYSQL_Pass", true);
// RUN ANOTHER QUERY
I had the very same issue. The answer is that you are doing it right already. It is the problem of MS Excel. Try opening the file with another editor and you will notice that your encoding was successful already. To make MS Excel happy, move from UTF-8 to UTF-16. This should work:
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel_tab, encoding="utf-16", **kwds):
# Redirect output to a queue
self.queue = StringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
# Force BOM
if encoding=="utf-16":
import codecs
f.write(codecs.BOM_UTF16)
self.encoding = encoding
def writerow(self, row):
# Modified from original: now using unicode(s) to deal with e.g. ints
self.writer.writerow([unicode(s).encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = data.encode(self.encoding)
# strip BOM
if self.encoding == "utf-16":
data = data[2:]
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
After Laravel 5.5 you can use now() function to get the current date and time.
In blade file, you can write like this to print date.
{{ now()->toDateTimeString('Y-m-d') }}
Not sure if this answers your question or not. Sorry if not
To get the error reported from the mysql database about your query you need to use your connection object as the focus.
so:
echo $mysqliDatabaseConnection->error
would echo the error being sent from mysql about your query.
Hope that helps
When I'm in a C mood, I usually use zip and list comprehensions for scanf-like behavior. Like this:
input = '1 3.0 false hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,strtobool,str),input.split())]
print (a, b, c, d)
Note that for more complex format strings, you do need to use regular expressions:
import re
input = '1:3.0 false,hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,strtobool,str),re.search('^(\d+):([\d.]+) (\w+),(\w+)$',input).groups())]
print (a, b, c, d)
Note also that you need conversion functions for all types you want to convert. For example, above I used something like:
strtobool = lambda s: {'true': True, 'false': False}[s]
This is totally covered by the other answers, but I'll make it explicit. An object may have class attributes and static and dynamic instance attributes.
class foo:
classy = 1
@property
def dyno(self):
return 1
def __init__(self):
self.stasis = 2
def fx(self):
return 3
stasis
is static, dyno
is dynamic (cf. property decorator) and classy
is a class attribute. If we simply do __dict__
or vars
we will only get the static one.
o = foo()
print(o.__dict__) #{'stasis': 2}
print(vars(o)) #{'stasis': 2}
So if we want the others __dict__
will get everything (and more).
This includes magic methods and attributes and normal bound methods. So lets avoid those:
d = {k: getattr(o, k, '') for k in o.__dir__() if k[:2] != '__' and type(getattr(o, k, '')).__name__ != 'method'}
print(d) #{'stasis': 2, 'classy': 1, 'dyno': 1}
The type
called with a property decorated method (a dynamic attribute) will give you the type of the returned value, not method
. To prove this let's json stringify it:
import json
print(json.dumps(d)) #{"stasis": 2, "classy": 1, "dyno": 1}
Had it been a method it would have crashed.
TL;DR. try calling extravar = lambda o: {k: getattr(o, k, '') for k in o.__dir__() if k[:2] != '__' and type(getattr(o, k, '')).__name__ != 'method'}
for all three, but not methods nor magic.
I believe you need to specify "Option Infer On" for this to work.
Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.
Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.
Opinion incoming:
Also, you mention that you've got "Option Explicit Off". Please don't do this.
Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":
Dim X as Integer
Y = 3
This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.
x = [i for i in x if len(i)==2]
For me the Web API was Rails and client side Angular used with Restangular and FileSaver.js
Web API
module Api
module V1
class DownloadsController < BaseController
def show
@download = Download.find(params[:id])
send_data @download.blob_data
end
end
end
end
HTML
<a ng-click="download('foo')">download presentation</a>
Angular controller
$scope.download = function(type) {
return Download.get(type);
};
Angular Service
'use strict';
app.service('Download', function Download(Restangular) {
this.get = function(id) {
return Restangular.one('api/v1/downloads', id).withHttpConfig({responseType: 'arraybuffer'}).get().then(function(data){
console.log(data)
var blob = new Blob([data], {
type: "application/pdf"
});
//saveAs provided by FileSaver.js
saveAs(blob, id + '.pdf');
})
}
});
Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.
STATISTICS - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop a "Plan" of attack for how it will do the query, for example the type of method it will use to match keys between tables using a hash or looking through the entire set. You can call Update Statistics on the entire database or just certain tables or indexes. This slows down the query from one run to another because when statistics are out of date, its likely the query plan is not optimal for the newly inserted or changed data for the same query (explained more later below). It may not be proper to Update Statistics immediately on a Production database as there will be some overhead, slow down and lag depending on the amount of data to sample. You can also choose to use a Full Scan or Sampling to update Statistics. If you look at the Query Plan, you can then also view the statistics on the Indexes in use such using the command DBCC SHOW_STATISTICS (tablename, indexname). This will show you the distribution and ranges of the keys that the query plan is using to base its approach on.
PARAMETER SNIFFING - The query plan that is cached is not optimal for the particular parameters you are passing in, even though the query itself has not changed. For example, if you pass in a parameter which only retrieves 10 out of 1,000,000 rows, then the query plan created may use a Hash Join, however if the parameter you pass in will use 750,000 of the 1,000,000 rows, the plan created may be an index scan or table scan. In such a situation you can tell the SQL statement to use the option OPTION (RECOMPILE) or an SP to use WITH RECOMPILE. To tell the Engine this is a "Single Use Plan" and not to use a Cached Plan which likely does not apply. There is no rule on how to make this decision, it depends on knowing the way the query will be used by users.
INDEXES - Its possible that the query haven't changed, but a change elsewhere such as the removal of a very useful index has slowed down the query.
ROWS CHANGED - The rows you are querying drastically changes from call to call. Usually statistics are automatically updated in these cases. However if you are building dynamic SQL or calling SQL within a tight loop, there is a possibility you are using an outdated Query Plan based on the wrong drastic number of rows or statistics. Again in this case OPTION (RECOMPILE) is useful.
THE LOGIC Its the Logic, your query is no longer efficient, it was fine for a small number of rows, but no longer scales. This usually involves more indepth analysis of the Query Plan. For example, you can no longer do things in bulk, but have to Chunk things and do smaller Commits, or your Cross Product was fine for a smaller set but now takes up CPU and Memory as it scales larger, this may also be true for using DISTINCT, you are calling a function for every row, your key matches don't use an index because of CASTING type conversion or NULLS or functions... Too many possibilities here.
In general when you write a query, you should have some mental picture of roughly how certain data is distributed within your table. A column for example, can have an evenly distributed number of different values, or it can be skewed, 80% of the time have a specific set of values, whether the distribution will varying frequently over time or be fairly static. This will give you a better idea of how to build an efficient query. But also when debugging query performance have a basis for building a hypothesis as to why it is slow or inefficient.
You can use the following example:
<table id="purches">
<thead>
<tr>
<th>ID</th>
<th>Transaction Date</th>
<th>Category</th>
<th>Transaction Amount</th>
<th>Offer</th>
</tr>
</thead>
<!-- <tr th:each="person: ${list}" >
<td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
</tr>
-->
<tbody id="feedback">
</tbody>
</table>
JavaScript file:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
// var json = "<h4>Ajax Response</h4><pre>" + JSON.stringify(data, null, 4) + "</pre>";
// $('#feedback').html(json);
//
console.log("SUCCESS: ", data);
//$("#btn-search").prop("disabled", false);
for (var i = 0; i < data.length; i++) {
//$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
$('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');
alert(data[i].accountNumber)
}
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR: ", e);
$("#btn-search").prop("disabled", false);
}
});
Wow! Mean this that you must learn a different programming language just to send two keys to the keyboard? There are simpler ways for you to achieve the same thing. :-)
The Batch file below is an example that start another program (cmd.exe in this case), send a command to it and then send an Up Arrow key, that cause to recover the last executed command. The Batch file is simple enough to be understand with no problems, so you may modify it to fit your needs.
@if (@CodeSection == @Batch) @then
@echo off
rem Use %SendKeys% to send keys to the keyboard buffer
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Start the other program in the same Window
start "" /B cmd
%SendKeys% "echo off{ENTER}"
set /P "=Wait and send a command: " < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "echo Hello, world!{ENTER}"
set /P "=Wait and send an Up Arrow key: [" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{UP}"
set /P "=] Wait and send an Enter key:" < NUL
ping -n 5 -w 1 127.0.0.1 > NUL
%SendKeys% "{ENTER}"
%SendKeys% "exit{ENTER}"
goto :EOF
@end
// JScript section
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
For a list of key names for SendKeys, see: http://msdn.microsoft.com/en-us/library/8c6yea83(v=vs.84).aspx
For example:
LEFT ARROW {LEFT}
RIGHT ARROW {RIGHT}
For a further explanation of this solution, see: GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs
I like this one: it - vec.begin()
, because to me it clearly says "distance from beginning". With iterators we're used to thinking in terms of arithmetic, so the -
sign is the clearest indicator here.
I was needing to find out just which version of .NET framework I had on my computer, and all I did was go to the control panel and select the "Uninstall a Program" option. After that, I sorted the programs by name, and found Microsoft .NET Framework 4 Client Profile.
r stands for a raw string, so things like \ will be automatically escaped by Python.
Normally, if you wanted your pattern to include something like a backslash you'd need to escape it with another backslash. raw strings eliminate this problem.
In your case, it does not matter much but it's a good habit to get into early otherwise something like \b will bite you in the behind if you are not careful (will be interpreted as backspace character instead of word boundary)
As per re.match vs re.search here's an example that will clarify it for you:
>>> import re
>>> testString = 'hello world'
>>> re.match('hello', testString)
<_sre.SRE_Match object at 0x015920C8>
>>> re.search('hello', testString)
<_sre.SRE_Match object at 0x02405560>
>>> re.match('world', testString)
>>> re.search('world', testString)
<_sre.SRE_Match object at 0x015920C8>
So search will find a match anywhere, match will only start at the beginning
This works in Chrome but not Firefox 3.6 (warning: RickRoll video):
<iframe width="420" height="345" src="http://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1" frameborder="0" allowfullscreen></iframe>
The JavaScript API for iframe embeds exists, but is still posted as an experimental feature.
UPDATE: The iframe API is now fully supported and "Creating YT.Player objects - Example 2" shows how to set "autoplay" in JavaScript.
Updating timestamp, only if the values changed
Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
NEW.modified = now();
RETURN NEW;
ELSE
RETURN OLD;
END IF;
END;
$$ language 'plpgsql';
Rather then write a lot of code, just do this:
{
dynamic tableNameAttribute = typeof(T).CustomAttributes.FirstOrDefault().ToString();
dynamic tableName = tableNameAttribute.Substring(tableNameAttribute.LastIndexOf('.'), tableNameAttribute.LastIndexOf('\\'));
}
You should check ExcelJS
Works with CSV and XLSX formats.
Great for reading/writing XLSX streams. I've used it to stream an XLSX download to an Express response object, basically like this:
app.get('/some/route', function(req, res) {
res.writeHead(200, {
'Content-Disposition': 'attachment; filename="file.xlsx"',
'Transfer-Encoding': 'chunked',
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
var workbook = new Excel.stream.xlsx.WorkbookWriter({ stream: res })
var worksheet = workbook.addWorksheet('some-worksheet')
worksheet.addRow(['foo', 'bar']).commit()
worksheet.commit()
workbook.commit()
}
Works great for large files, performs much better than excel4node (got huge memory usage & Node process "out of memory" crash after nearly 5 minutes for a file containing 4 million cells in 20 sheets) since its streaming capabilities are much more limited (does not allows to "commit()" data to retrieve chunks as soon as they can be generated)
See also this SO answer.
If I had to do this with a regex, I'd do it like this:
s = re.sub(r'\.jpg$', '', s)
<% form_for(@message) do |f| %>
<%= f.radio_button :contactmethod, 'email', :checked => true %>
<%= label :contactmethod_email, 'Email' %>
<%= f.radio_button :contactmethod, 'sms' %>
<%= label :contactmethod_sms, 'SMS' %>
<% end %>
Bits per second is straightforward. It is exactly what it sounds like. If I have 1000 bits and am sending them at 1000 bps, it will take exactly one second to transmit them.
Baud is symbols per second. If these symbols — the indivisible elements of your data encoding — are not bits, the baud rate will be lower than the bit rate by the factor of bits per symbol. That is, if there are 4 bits per symbol, the baud rate will be ¼ that of the bit rate.
This confusion arose because the early analog telephone modems weren't very complicated, so bps was equal to baud. That is, each symbol encoded one bit. Later, to make modems faster, communications engineers invented increasingly clever ways to send more bits per symbol.¹
System 1, bits: Imagine a communication system with a telescope on the near side of a valley and a guy on the far side holding up one hand or the other. Call his left hand "0" and his right hand "1," and you have a system for communicating one binary digit — one bit — at a time.
System 2, baud: Now imagine that the guy on the far side of the valley is holding up playing cards instead of his bare hands. He is using a subset of the cards, ace through 8 in each suit, for a total of 32 cards. Each card — each symbol — encodes 5 bits: 00000 through 11111 in binary.²
The System 2 guy can convey 5 bits of information per card in the same time it takes the System 1 guy to convey one bit by revealing one of his bare hands.
You see how the analogy seems to break down: finding a particular card in a deck and showing it takes longer than simply deciding to show your left or right hand. But, that just provides an opportunity to extend the analogy profitably.
A communications system with many bits per symbol faces a similar difficulty, because the encoding schemes required to send multiple bits per symbol are much more complicated than those that send only one bit at a time. To extend the analogy, then, the guy showing playing cards could have several people behind him sharing the work of finding the next card in the deck, handing him cards as fast as he can show them. The helpers are analogous to the more powerful processors required to produce the many-bits-per-baud encoding schemes.
That is to say, by using more processing power, System 2 can send data 5 times faster than the more primitive System 1.
What shall we do with our 5-bit code? It seems natural to an English speaker to use 26 of the 32 available code points for the English alphabet. We can use the remaining 6 code points for a space character and a small set of control codes and symbols.
Or, we could just use Baudot code, a 5-bit code invented by Émile Baudot, after whom the unit "baud" was coined.³
Footnotes and Digressions:
For example, the V.34 standard defined a 3,429 baud mode at 8.4 bits per symbol to achieve 28.8 kbit/sec throughput.
That standard only talks about the POTS side of the modem. The RS-232 side remains a 1 bit per symbol system, so you could also correctly call it a 28.8k baud modem. Confusing, but technically correct.
I've purposely kept things simple here.
One thing you might think about is whether the absence of a playing card conveys information. If it does, that implies the existence of some clock or latch signal, so that you can tell the information-carrying absence of a card from the gap between the display of two cards.
Also, what do you do with the cards left over in a poker deck, 9 through King, and the Jokers? One idea would be to use them as special flags to carry metadata. For example, you'll need a way to indicate a short trailing block. If you need to send 128 bits of information, you're going to need to show 26 cards. The first 25 cards convey 5×25=125 bits, with the 26th card conveying the trailing 3 bits. You need some way to signal that the last two bits in the symbol should be disregarded.
This is why the early analog telephone modems were specified in terms of baud instead of bps: communications engineers had been using that terminology since the telegraph days. They weren't trying to confuse bps and baud; it was simply a fact, in their minds, that these modems were transmitting one bit per symbol.
Why do you need 'input:radio[name=cols]'
. Don't know your html, but assuming that ids are unique, you can simply do this.
$('#'+newcol).prop('checked', true);
The clearest explanation I found was not in the current 2.4 apache docs, but in version 2.0.
# /abc/def/.htaccess -- per-dir config file for directory /abc/def
# Remember: /abc/def is the physical path of /xyz, i.e., the server
# has a 'Alias /xyz /abc/def' directive e.g.
RewriteEngine On
# let the server know that we were reached via /xyz and not
# via the physical path prefix /abc/def
RewriteBase /xyz
How does it work? For you apache hackers, this 2.0 doc goes on to give "detailed information about the internal processing steps."
Lesson learned: While we need to be familiar with "current," gems can be found in the annals.
Have you tried HttpServerUtility.UrlDecode
or HttpUtility.UrlDecode
?
var div = document.createElement('div');
document.body.appendChild(div);
div.style.left = '32px';
div.style.top = '-16px';
div.className = 'ui-modal';
div.id = 'test';
div.innerHTML = '<span class="msg">Hello world.</span>';
div.textContent = 'Hello world.';
div.parentNode.removeChild(div);
div = document.getElementById('test');
array = document.getElementsByTagName('div');
array = document.getElementsByClassName('ui-modal');
div = document.querySelector('div #test .ui-modal');
array = document.querySelectorAll('div');
This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.
In your IDE right click on the file you want to read and choose "copy path" then paste it into your code.
Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"
The trick for me was I had ssh
conflict.
I have Git installed on my Windows path, which includes ssh. cwrsync also installs ssh.
The trick is to have make a batch file to set the correct paths:
rsync.bat
@echo off
SETLOCAL
SET CWRSYNCHOME=c:\commands\cwrsync
SET HOME=c:\Users\Petah\
SET CWOLDPATH=%PATH%
SET PATH=%CWRSYNCHOME%\bin;%PATH%
%~dp0\cwrsync\bin\rsync.exe %*
On Windows you can type where ssh
to check if this is an issue. You will get something like this:
where ssh
C:\Program Files (x86)\Git\bin\ssh.exe
C:\Program Files\cwRsync\ssh.exe
You might get the error with the latest android gradle plugin (3.0):
Cannot set the value of read-only property 'outputFile'
According to the migration guide, we should use the following approach now:
applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${applicationName}_${variant.buildType.name}_${defaultConfig.versionName}.apk"
}
}
Note 2 main changes here:
all
is used now instead of each
to iterate over the variant outputs.outputFileName
property is used instead of mutating a file reference.{
InputStream is = HTTPClient.get(url);
InputStreamReader reader = new InputStreamReader(is);
JSONTokener tokenizer = new JSONTokener(reader);
JSONObject jsonObject = new JSONObject(tokenizer);
}
The bootstrap docs says about this:
Requires custom widths Inputs, selects, and textareas are 100% wide by default in Bootstrap. To use the inline form, you'll have to set a width on the form controls used within.
The default width of 100% as all form elements gets when they got the class form-control
didn't apply if you use the form-inline
class on your form.
You could take a look at the bootstrap.css (or .less, whatever you prefer) where you will find this part:
.form-inline {
// Kick in the inline
@media (min-width: @screen-sm-min) {
// Inline-block all the things for "inline"
.form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
// In navbar-form, allow folks to *not* use `.form-group`
.form-control {
display: inline-block;
width: auto; // Prevent labels from stacking above inputs in `.form-group`
vertical-align: middle;
}
// Input groups need that 100% width though
.input-group > .form-control {
width: 100%;
}
[...]
}
}
Maybe you should take a look at input-groups, since I guess they have exactly the markup you want to use (working fiddle here):
<div class="row">
<div class="col-lg-12">
<div class="input-group input-group-lg">
<input type="text" class="form-control input-lg" id="search-church" placeholder="Your location (City, State, ZIP)">
<span class="input-group-btn">
<button class="btn btn-default btn-lg" type="submit">Search</button>
</span>
</div>
</div>
</div>
In the C++ programming language V4, Stroustrup recommends using vectors or valarrays over builtin arrays. With valarrary's, when you create them, you can init them to a specific value like:
valarray <int>seven7s=(7777777,7);
To initialize an array 7 members long with "7777777".
This is a C++ way of implementing the answer using a C++ data structure instead of a "plain old C" array.
I switched to using the valarray as an attempt in my code to try to use C++'isms v. C'isms....
I like this one, that hasn't been mentioned above.
require 'pathname'
Pathname.new('/my/dir').children.each do |path|
puts path
end
The benefit is that you get a Pathname object instead of a string, that you can do useful stuff with and traverse further.
public V[] getV(DataTable dtCloned)
{
V[] objV = new V[dtCloned.Rows.Count];
MyClasses mc = new MyClasses();
int i = 0;
int intError = 0;
foreach (DataRow dr in dtCloned.Rows)
{
try
{
V vs = new V();
vs.R = int.Parse(mc.ReplaceChar(dr["r"].ToString()).Trim());
vs.S = Int64.Parse(mc.ReplaceChar(dr["s"].ToString()).Trim());
objV[i] = vs;
i++;
}
catch (Exception ex)
{
//
DataRow row = dtError.NewRow();
row["r"] = dr["r"].ToString();
row["s"] = dr["s"].ToString();
dtError.Rows.Add(row);
intError++;
}
}
return vs;
}
declare @T table(Roles xml)
insert into @T values
('<root>
<role>Alpha</role>
<role>Beta</role>
<role>Gamma</role>
</root>')
declare @Role varchar(10)
set @Role = 'Beta'
select Roles
from @T
where Roles.exist('/root/role/text()[. = sql:variable("@Role")]') = 1
If you want the query to work as where col like '%Beta%'
you can use contains
declare @T table(Roles xml)
insert into @T values
('<root>
<role>Alpha</role>
<role>Beta</role>
<role>Gamma</role>
</root>')
declare @Role varchar(10)
set @Role = 'et'
select Roles
from @T
where Roles.exist('/root/role/text()[contains(., sql:variable("@Role"))]') = 1
check for scipy.stats module:
scipy.stats.scoreatpercentile
Order Collection Limit :
$orderCollection = Mage::getResourceModel('sales/order_collection');
$orderCollection->getSelect()->limit(10);
foreach ($orderCollection->getItems() as $order) :
$orderModel = Mage::getModel('sales/order');
$order = $orderModel->load($order['entity_id']);
echo $order->getId().'<br>';
endforeach;
You could use coalesce:
insert into destination select coalesce(field1,'somedata'),... from source;
I also got the following error when I run a command with PHP
, I did the solution like that:
C:\xampp\php
to your PATH Environment Variable.Very important note: restart command prompt
create a new file with string image path
String imagePath;
File test = new File(imagePath);
test.getName();
test.getPath();
getExtension(test.getName());
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
Following @Sampson's answer, I approached it this way -
HTML:
div
with content
class in each page, which holds the contents of that page. Header and Footer are separated.content
. For example, if I am creating a CONTACT US page, I will put the contents of the page inside <section class="content contact-us"></section>
.<body>
<header>
<div class="nav-menu">
<ul class="parent-nav">
<li><a href="#">Home</a></li>
<li><a href="#">Contact us</a></li>
...
</ul>
</div>
</header>
<section class="content contact-us">
Content for contact us page goes here
</section>
<footer> ... </footer>
</body>
_x000D_
CSS:
active
class, which holds the styling for an active menu..active {
color: red;
text-decoration: none;
}
_x000D_
<body>
<header>
<div class="nav-menu">
<ul class="parent-nav">
<li><a href="#">Home</a></li>
<li><a href="#">Contact us</a></li>
...
</ul>
</div>
</header>
<section class="content contact-us">
Content for contact us page goes here
</section>
<footer> ... </footer>
</body>
_x000D_
JavaScript:
content
class have the same class as menu text (lowercase and without spaces), add active
class to the menu item.var $allMenu = $('.nav-menu > .parent-nav > li > a');
var $currentContent = $('.content');
$allMenu.each(function() {
$singleMenuTitle = $(this).text().replace(/\s+/g, '-').toLowerCase();
if ($currentContent.hasClass($singleMenuTitle)) {
$(this).addClass('active');
}
});
_x000D_
.active {
color: red;
text-decoration: none;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<header>
<div class="nav-menu">
<ul class="parent-nav">
<li><a href="#">Home</a></li>
<li><a href="#">Contact us</a></li>
...
</ul>
</div>
</header>
<section class="content contact-us">
Content for contact us page goes here
</section>
<footer> ... </footer>
</body>
_x000D_
Why I Approached This?
body
tag is in header.php
file which means I cannot write unique class name for every page.First open Visual studio ..select your project in solution explorer..Right click and choose option "browse with" then set IE as default browser.
Now open IE ..go to
Tools >> Internet option >> Advance>> uncheck the checkbox having "Disable Script Debugging (Internet Explorer).
and then click Apply
and OK
and you are done ..
Now you can set breakpoints in your JS file and then hit the debug button in VS..
EDIT:- For asp.net web application right click on the page which is your startup page(say default.aspx) and perform the same steps. :)
Sorry, there is no operation similar to LIKE IN
in mysql.
If you want to use the LIKE operator without a join, you'll have to do it this way:
(field LIKE value OR field LIKE value OR field LIKE value)
You know, MySQL will not optimize that query, FYI.
with maven it is automatic:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jasperreports-maven-plugin</artifactId>
<configuration>
<outputDirectory>target/${project.artifactId}/WEB-INF/reports</outputDirectory>
</configuration>
<executions>
<execution>
<phase>prepare-package</phase>
<inherited>false</inherited>
<goals>
<goal>compile-reports</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>3.7.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<type>jar</type>
</dependency>
</dependencies>
</plugin>
var today = new Date().toISOString().split('T')[0];
$("#datePicker").val(today);
Above code will work.
If you need the space for the purpose of later concatenating it with other strings, then you can use the string formatting approach of adding arguments to your string definition:
<string name="error_">Error: %s</string>
Then for format the string (eg if you have an error returned by the server, otherwise use getString(R.string.string_resource_example)
):
String message = context.getString(R.string.error_, "Server error message here")
Which results in:
Error: Server error message here
Beside rowid, you can define your own auto increment field but it is not recommended. It is always be better solution when we use rowid that is automatically increased.
The
AUTOINCREMENT
keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.
Read here for detailed information.
You want to do something like this instead:
<Button>
<StackPanel>
<Image Source="Pictures/apple.jpg" />
<TextBlock>Disconnect from Server</TextBlock>
</StackPanel>
</Button>
If you use spring-boot, you don't need to create a DataSource class, just specify the data url/username/password/driver in application.properties
, then you can simply @Autowired
it.
@Repository
public class JdbcRepository {
private final JdbcTemplate jdbcTemplate;
@Autowired
public DynamicRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void insert() {
jdbcTemplate.update("INSERT INTO BOOK (name, description) VALUES ('book name', 'book description')");
}
}
Example of application.properties
:
#Basic Spring Boot Config for Oracle
spring.datasource.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YourHostIP)(PORT=YourPort))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=YourServiceName)))
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
Then add the driver and connection pool dependencies in pom.xml
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.1</version>
</dependency>
<!-- HikariCP connection pool -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.0</version>
</dependency>
See the official doc for more details.
I am sure there is ANT tags to do it but have used this 7zip hack in .bat script. I use http://www.7-zip.org/ command line tool. All the times I use this for changing jdbc url within j2ee context.xml file.
mkdir .\temp-install
c:\apps\commands\7za.exe x -y mywebapp.war META-INF/context.xml -otemp-install\mywebapp
..here I have small tool to replace text in xml file..
c:\apps\commands\7za.exe u -y -tzip mywebapp.war ./temp-install/mywebapp/*
rmdir /Q /S .\temp-install
You could extract entire .war file (its zip after all), delete files, replace files, add files, modify files and repackage to .war archive file. But changing one file in a large .war archive this might be best extracting specific file and then update original archive.
I got tired of seeing this page with its by-now stale references to defunct Codehaus pages so I asked on the Maven Users mailing list and got some more up-to-date answers.
I would say that the best (and most authoritative) answer contained in my link above is the one contributed by Hervé BOUTEMY:
here is the core reference: http://maven.apache.org/ref/3-LATEST/maven-model-builder/
it does not explain everyting that can be found in POM or in settings, since there are so much info available but it points to POM and settings descriptors and explains everything that is not POM or settings
You could also do
npm i alex-cory/fasthacks
or
npm i github:alex-cory/fasthacks
Basically:
npm i user_or_org/repo_name
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
I normally use the 'back tick' feature of bash
export NUM_LINES=`wc -l filename`
Note the 'tick' is the 'back tick' e.g. ` not the normal single quote
Ricardo's answer is correct, however: sometimes you may find yourself in a situation where the container simply doesn't resize as desired as the browser window changes size, thus not allowing highcharts to resize itself.
This always works:
chart.setSize(width, height, doAnimation =
true);
in your actual resize function to set the height and width
dynamicallyreflow: false
in the highcharts-options and of course set height
and width
explicitly on creation. As we'll be doing our own resize event handling there's no need Highcharts hooks in another one.For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly
and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.
This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.
To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.
cc -DDISPLAY_STRING demo.c
If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.
#define TERMINAL "/dev/ttyUSB0"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
int set_interface_attribs(int fd, int speed)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error from tcgetattr: %s\n", strerror(errno));
return -1;
}
cfsetospeed(&tty, (speed_t)speed);
cfsetispeed(&tty, (speed_t)speed);
tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8; /* 8-bit characters */
tty.c_cflag &= ~PARENB; /* no parity bit */
tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */
tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */
/* setup for non-canonical mode */
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tty.c_oflag &= ~OPOST;
/* fetch bytes as they become available */
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSANOW, &tty) != 0) {
printf("Error from tcsetattr: %s\n", strerror(errno));
return -1;
}
return 0;
}
void set_mincount(int fd, int mcount)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error tcgetattr: %s\n", strerror(errno));
return;
}
tty.c_cc[VMIN] = mcount ? 1 : 0;
tty.c_cc[VTIME] = 5; /* half second timer */
if (tcsetattr(fd, TCSANOW, &tty) < 0)
printf("Error tcsetattr: %s\n", strerror(errno));
}
int main()
{
char *portname = TERMINAL;
int fd;
int wlen;
char *xstr = "Hello!\n";
int xlen = strlen(xstr);
fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0) {
printf("Error opening %s: %s\n", portname, strerror(errno));
return -1;
}
/*baudrate 115200, 8 bits, no parity, 1 stop bit */
set_interface_attribs(fd, B115200);
//set_mincount(fd, 0); /* set to pure timed read */
/* simple output */
wlen = write(fd, xstr, xlen);
if (wlen != xlen) {
printf("Error from write: %d, %d\n", wlen, errno);
}
tcdrain(fd); /* delay for output */
/* simple noncanonical input */
do {
unsigned char buf[80];
int rdlen;
rdlen = read(fd, buf, sizeof(buf) - 1);
if (rdlen > 0) {
#ifdef DISPLAY_STRING
buf[rdlen] = 0;
printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
unsigned char *p;
printf("Read %d:", rdlen);
for (p = buf; rdlen-- > 0; p++)
printf(" 0x%x", *p);
printf("\n");
#endif
} else if (rdlen < 0) {
printf("Error from read: %d: %s\n", rdlen, strerror(errno));
} else { /* rdlen == 0 */
printf("Timeout from read\n");
}
/* repeat read to get full message */
} while (1);
}
For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.
Sql Server we can use %
select * from orders where ID % 2 = 0;
This can be used in both Mysql and oracle. It is more affection to use mod function that %.
select * from orders where mod(ID,2) = 0
this type of error usually occur when you try to access data through the index in which data data has not been assign. for example
//assign of data in to array
for(int i=0; i<10; i++){
arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}
the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.
I don't believe you can do this with an accordion since it's specifically designed preserve the property that at most one item will be opened. However, even though you say you don't want to re-implement accordion, you might be over estimating the complexity involved.
Consider the following scenario where you have a vertical stack of elements,
++++++++++++++++++++
+ Header 1 +
++++++++++++++++++++
+ +
+ Item 1 +
+ +
++++++++++++++++++++
+ Header 2 +
++++++++++++++++++++
+ +
+ Item 2 +
+ +
++++++++++++++++++++
If you're lazy you could build this using a table, otherwise, suitably styled DIVs will also work.
Each of the item blocks can have a class of itemBlock
. Clicking on a header will cause all elements of class itemBlock to be hidden ($(".itemBlock").hide()
). You can then use the jquery slideDown()
function to expand the item below the header. Now you've pretty much implemented accordion.
To expand all items, just use $(".itemBlock").show()
or if you want it animated, $(".itemBlock").slideDown(500)
. To hide all items, just use $(".itemBlock").hide()
.
This instruction works fine:
Thread.currentThread().getStackTrace()[1].getClassName();
I tried many of the suggestions above/below, but ultimately, the issue I faced was a permissions one with watchman, which was installed using homebrew earlier. If you look at your terminal messages while trying to use the emulator, and encounter 'Permission denied' errors with regards to watchman along with this 'Could not get BatchedBridge" message on your emulator, do the following:
Go to your /Users/<username>/Library/LaunchAgents
directory and change the permissions settings so your user can Read and Write. This is regardless of whether or not you actually have a com.github.facebook.watchman.plist
file in there.
If you need to just empty the style
of an element then:
element.style.cssText = null;
This should do good. Hope it helps!
I think doing this way is much simpler:
button.setBackgroundColor(Color.BLACK);
And you need to import android.graphics.Color;
not: import android.R.color;
Or you can just write the 4-byte hex code (not 3-byte) 0xFF000000
where the first byte is setting the alpha.
You can use index arrays, simply pass your ind_pos
as an index argument as below:
a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])
print(a[ind_pos])
# [88,85,16]
Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).
The count
method of NSArray
returns an NSUInteger
, and on the 64-bit OS X platform
NSUInteger
is defined as unsigned long
, andunsigned long
is a 64-bit unsigned integer.int
is a 32-bit integer.So int
is a "smaller" datatype than NSUInteger
, therefore the compiler warning.
See also NSUInteger in the "Foundation Data Types Reference":
When building 32-bit applications, NSUInteger is a 32-bit unsigned integer. A 64-bit application treats NSUInteger as a 64-bit unsigned integer.
To fix that compiler warning, you can either declare the local count
variable as
NSUInteger count;
or (if you are sure that your array will never contain more than 2^31-1
elements!),
add an explicit cast:
int count = (int)[myColors count];
1.Go to Windows-->Preferences-->Java-->Installed JREs-->Execution Environments
2.select the java version you are using currently in the "Execution Environments" box. So that in the "Compatible JREs" box, you are able to see as "jre1.8.0_102[perfect match]"(if your java version is 1.8). Then try to build using maven.
To run an executable in mac
1). Move to the path of the file:
cd/PATH_OF_THE_FILE
2). Run the following command to set the file's executable bit using the chmod command:
chmod +x ./NAME_OF_THE_FILE
3). Run the following command to execute the file:
./NAME_OF_THE_FILE
Once you have run these commands, going ahead you just have to run command 3, while in the files path.
I suggest Validator.nu's parser, based on the HTML5 parsing algorithm. It is the parser used in Mozilla from 2010-05-03
An actual JSON request would look like this:
data: '{"command":"on"}',
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify()
to serialize an object to JSON, like this:
data: JSON.stringify({ "command": "on" }),
To support older browsers that don't have the JSON
object, use json2.js which will add it in.
What's currently happening is since you have processData: false
, it's basically sending this: ({"command":"on"}).toString()
which is [object Object]
...what you see in your request.
There's a wealth of clipboards you could be dealing with. I expect you're probably a Linux user who wants to put stuff in the X Windows primary clipboard. Usually, the clipboard you want to talk to has a utility that lets you talk to it.
In the case of X, there's xclip
(and others). xclip -selection c
will send data to the clipboard that works with Ctrl + C, Ctrl + V in most applications.
If you're on Mac OS X, there's pbcopy
. e.g cat example.txt | pbcopy
If you're in Linux terminal mode (no X) then look into gpm
or screen which has a clipboard. Try the screen
command readreg
.
Under Windows 10+ or cygwin, use /dev/clipboard
or clip
.
Would you please try with below code block, which is exactly what you're looking for:
SqlConnection conn = new SqlConnection
{
ConnectionString = "Data Source=" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\Database.sdf"
};
Input the following to your Apache configuration:
php_value memory_limit 2048M
LIMIT 1
is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order
clause in an outer query).
Here is my answer:
var options = ["1", "2", "3", "4", "5"];
for(m = 0 ; m <= options.length-1; m++){
var opt= document.createElement("OPTION");
opt.text = options[m];
opt.value = (m+1);
if(options[m] == "5"){
opt.selected = true;}
document.getElementById("selectNum").options.add(opt);}
<?php
class Test {
function MethodA(){
echo __FUNCTION__ ;
}
}
$test = new Test;
echo $test->MethodA();
?>
Result: "MethodA";
"At run time, the authorization module iterates through the allow and deny elements, starting at the most local configuration file, until the authorization module finds the first access rule that fits a particular user account. Then, the authorization module grants or denies access to a URL resource depending on whether the first access rule found is an allow or a deny rule. The default authorization rule is . Thus, by default, access is allowed unless configured otherwise."
Article at MSDN
deny = * means deny everyone
deny = ? means deny unauthenticated users
In your 1st example deny * will not affect dan, matthew since they were already allowed by the preceding rule.
According to the docs, here is no difference in your 2 rule sets.