I went for it because I could insert new items to the tree easily (you just need a branch's id to insert a new item to it) and also query it quite fast.
+-------------+----------------------+--------+-----+-----+
| category_id | name | parent | lft | rgt |
+-------------+----------------------+--------+-----+-----+
| 1 | ELECTRONICS | NULL | 1 | 20 |
| 2 | TELEVISIONS | 1 | 2 | 9 |
| 3 | TUBE | 2 | 3 | 4 |
| 4 | LCD | 2 | 5 | 6 |
| 5 | PLASMA | 2 | 7 | 8 |
| 6 | PORTABLE ELECTRONICS | 1 | 10 | 19 |
| 7 | MP3 PLAYERS | 6 | 11 | 14 |
| 8 | FLASH | 7 | 12 | 13 |
| 9 | CD PLAYERS | 6 | 15 | 16 |
| 10 | 2 WAY RADIOS | 6 | 17 | 18 |
+-------------+----------------------+--------+-----+-----+
parent
column.lft
between lft
and rgt
of parent.lft
lower than the node's lft
and rgt
bigger than the node's rgt
and sort the by parent
.I needed to make accessing and querying the tree faster than inserts, that's why I chose this
The only problem is to fix the left
and right
columns when inserting new items. well I created a stored procedure for it and called it every time I inserted a new item which was rare in my case but it is really fast.
I got the idea from the Joe Celko's book, and the stored procedure and how I came up with it is explained here in DBA SE
https://dba.stackexchange.com/q/89051/41481
If I had to guess, I'd say you installed the PPA 7.1.8 as CLI only (php7-cli). You're getting your version info from that, but your libapache2-mod-php package is still 14.04 main which is 5.6. Check your phpinfo in your browser to confirm the version. You might also consider migrating to Ubuntu 16.04 to get PHP 7.0 in main.
I have written a SP for the this which returns the search results in form of Table name, the Column names in which the search keyword string was found as well as the searches the corresponding rows as shown in below screen shot.
This might not be the most efficient solution but you can always modify and use it according to your need.
IF OBJECT_ID('sp_KeywordSearch', 'P') IS NOT NULL
DROP PROC sp_KeywordSearch
GO
CREATE PROCEDURE sp_KeywordSearch @KeyWord NVARCHAR(100)
AS
BEGIN
DECLARE @Result TABLE
(TableName NVARCHAR(300),
ColumnName NVARCHAR(MAX))
DECLARE @Sql NVARCHAR(MAX),
@TableName NVARCHAR(300),
@ColumnName NVARCHAR(300),
@Count INT
DECLARE @tableCursor CURSOR
SET @tableCursor = CURSOR LOCAL SCROLL FOR
SELECT N'SELECT @Count = COUNT(1) FROM [dbo].[' + T.TABLE_NAME + '] WITH (NOLOCK) WHERE CAST([' + C.COLUMN_NAME +
'] AS NVARCHAR(MAX)) LIKE ''%' + @KeyWord + N'%''',
T.TABLE_NAME,
C.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLES AS T WITH (NOLOCK)
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS C WITH (NOLOCK)
ON T.TABLE_SCHEMA = C.TABLE_SCHEMA AND
T.TABLE_NAME = C.TABLE_NAME
WHERE T.TABLE_TYPE = 'BASE TABLE' AND
C.TABLE_SCHEMA = 'dbo' AND
C.DATA_TYPE NOT IN ('image', 'timestamp')
OPEN @tableCursor
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @Count = 0
EXEC sys.sp_executesql
@Sql,
N'@Count INT OUTPUT',
@Count OUTPUT
IF @Count > 0
BEGIN
INSERT INTO @Result
(TableName, ColumnName)
VALUES (@TableName, @ColumnName)
END
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
END
CLOSE @tableCursor
DEALLOCATE @tableCursor
SET @tableCursor = CURSOR LOCAL SCROLL FOR
SELECT SUBSTRING(TB.Sql, 1, LEN(TB.Sql) - 3) AS Sql, TB.TableName, SUBSTRING(TB.Columns, 1, LEN(TB.Columns) - 1) AS Columns
FROM (SELECT R.TableName, (SELECT R2.ColumnName + ', ' FROM @Result AS R2 WHERE R.TableName = R2.TableName FOR XML PATH('')) AS Columns,
'SELECT * FROM ' + R.TableName + ' WITH (NOLOCK) WHERE ' +
(SELECT 'CAST(' + R2.ColumnName + ' AS NVARCHAR(MAX)) LIKE ''%' + @KeyWord + '%'' OR '
FROM @Result AS R2
WHERE R.TableName = R2.TableName
FOR
XML PATH('')) AS Sql
FROM @Result AS R
GROUP BY R.TableName) TB
ORDER BY TB.Sql
OPEN @tableCursor
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Sql
SELECT @TableName AS [Table],
@ColumnName AS Columns
EXEC(@Sql)
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
END
CLOSE @tableCursor
DEALLOCATE @tableCursor
END
Try this script to create a temporary table TESTTEST and watch the order of precedence as the triggers are called in this order: 1) INSTEAD OF, 2) FOR, 3) AFTER
All of the logic is placed in INSTEAD OF trigger and I have 2 examples of how you might code some scenarios...
Good luck...
CREATE TABLE TESTTEST
(
ID INT,
Modified0 DATETIME,
Modified1 DATETIME
)
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_0] ON [dbo].TESTTEST
INSTEAD OF INSERT,UPDATE,DELETE
AS
BEGIN
SELECT 'INSTEAD OF'
SELECT 'TT0.0'
SELECT * FROM TESTTEST
SELECT *, 'I' Mode
INTO #work
FROM INSERTED
UPDATE #work SET Mode='U' WHERE ID IN (SELECT ID FROM DELETED)
INSERT INTO #work (ID, Modified0, Modified1, Mode)
SELECT ID, Modified0, Modified1, 'D'
FROM DELETED WHERE ID NOT IN (SELECT ID FROM INSERTED)
--Check Security or any other logic to add and remove from #work before processing
DELETE FROM #work WHERE ID=9 -- because you don't want anyone to edit this id?!?!
DELETE FROM #work WHERE Mode='D' -- because you don't want anyone to delete any records
SELECT 'EV'
SELECT * FROM #work
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='I'))
BEGIN
SELECT 'I0.0'
INSERT INTO dbo.TESTTEST (ID, Modified0, Modified1)
SELECT ID, Modified0, Modified1
FROM #work
WHERE Mode='I'
SELECT 'Cool stuff would happen here if you had FOR INSERT or AFTER INSERT triggers.'
SELECT 'I0.1'
END
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='D'))
BEGIN
SELECT 'D0.0'
DELETE FROM TESTTEST WHERE ID IN (SELECT ID FROM #work WHERE Mode='D')
SELECT 'Cool stuff would happen here if you had FOR DELETE or AFTER DELETE triggers.'
SELECT 'D0.1'
END
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='U'))
BEGIN
SELECT 'U0.0'
UPDATE t SET t.Modified0=e.Modified0, t.Modified1=e.Modified1
FROM dbo.TESTTEST t
INNER JOIN #work e ON e.ID = t.ID
WHERE e.Mode='U'
SELECT 'U0.1'
END
DROP TABLE #work
SELECT 'TT0.1'
SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_1] ON [dbo].TESTTEST
FOR UPDATE
AS
BEGIN
SELECT 'FOR UPDATE'
SELECT 'TT1.0'
SELECT * FROM TESTTEST
SELECT 'I1'
SELECT * FROM INSERTED
SELECT 'D1'
SELECT * FROM DELETED
SELECT 'TT1.1'
SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_2] ON [dbo].TESTTEST
AFTER UPDATE
AS
BEGIN
SELECT 'AFTER UPDATE'
SELECT 'TT2.0'
SELECT * FROM TESTTEST
SELECT 'I2'
SELECT * FROM INSERTED
SELECT 'D2'
SELECT * FROM DELETED
SELECT 'TT2.1'
SELECT * FROM TESTTEST
END
GO
SELECT 'Start'
INSERT INTO TESTTEST (ID, Modified0) VALUES (9, GETDATE())-- not going to insert
SELECT 'RESTART'
INSERT INTO TESTTEST (ID, Modified0) VALUES (10, GETDATE())--going to insert
SELECT 'RESTART'
UPDATE TESTTEST SET Modified1=GETDATE() WHERE ID=10-- gointo to update
SELECT 'RESTART'
DELETE FROM TESTTEST WHERE ID=10-- not going to DELETE
SELECT 'FINISHED'
SELECT * FROM TESTTEST
DROP TABLE TESTTEST
Is there any advantage in creating a temporary file in a more careful way
The temporary files are usually created in the temporary directory (such as /tmp
) where all other users and processes has read and write access (any other script can create the new files there). Therefore the script should be careful about creating the files such as using with the right permissions (e.g. read only for the owner, see: help umask
) and filename should be be not easily guessed (ideally random). Otherwise if the filenames aren't unique, it can create conflict with the same script ran multiple times (e.g. race condition) or some attacker could either hijack some sensitive information (e.g. when permissions are too open and filename is easy to guess) or create/replacing the file with their own version of the code (like replacing the commands or SQL queries depending on what is being stored).
You could use the following approach to create the temporary directory:
TMPDIR=".${0##*/}-$$" && mkdir -v "$TMPDIR"
or temporary file:
TMPFILE=".${0##*/}-$$" && touch "$TMPFILE"
However it is still predictable and not considered safe.
As per man mktemp
, we can read:
Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.
So to be safe, it is recommended to use mktemp
command to create unique temporary file or directory (-d
).
Existence of sessionid can cause the session fixation attack that is one of the point in PCI compliance. To remove the sessionid and overcome the session fixation attack, read this solution - How to avoid the Session fixation vulnerability in ASP.NET?.
Suppose your DataTable has the following columns try this code:
DataTable dt =new DataTable();
txtTGrossWt.Text = dt.Compute("sum(fldGrossWeight)", "").ToString() == "" ? "0" : dt.Compute("sum(fldGrossWeight)", "").ToString();
txtTOtherWt.Text = dt.Compute("sum(fldOtherWeight)", "").ToString() == "" ? "0" : dt.Compute("sum(fldOtherWeight)", "").ToString();
txtTNetWt.Text = dt.Compute("sum(fldNetWeight)", "").ToString() == "" ? "0" : dt.Compute("sum(fldNetWeight)", "").ToString();
txtFinalValue.Text = dt.Compute("sum(fldValue)", "").ToString() == "" ? "0" : dt.Compute("sum(fldValue)", "").ToString();
SELECT TOP 1 * FROM foo ORDER BY Dates DESC
Will return one result with the latest date.
SELECT * FROM foo WHERE foo.Dates = (SELECT MAX(Dates) FROM foo)
Will return all results that have the same maximum date, to the milissecond.
This is for SQL Server. I'll leave it up to you to use the DATEPART function if you want to use dates but not times.
The purpose of interfaces is polymorphism, a.k.a. type substitution. For example, given the following method:
public void scale(IBox b, int i) {
b.setSize(b.getSize() * i);
}
When calling the scale
method, you can provide any value that is of a type that implements the IBox
interface. In other words, if Rectangle
and Square
both implement IBox
, you can provide either a Rectangle
or a Square
wherever an IBox
is expected.
Your array.xml is not right. change it to like this
Here is array.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="testArray">
<item>first</item>
<item>second</item>
<item>third</item>
<item>fourth</item>
<item>fifth</item>
</string-array>
</resources>
Fragments that are hard coded in XML, cannot be replaced. If you need to replace a fragment with another, you should have added them dynamically, first of all.
Note: R.id.fragment_container is a layout or container of your choice in the activity you are bringing the fragment to.
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
<div class="jumbotron">
<div class="container">
<div class="row">
<div>
<h2 class="col-md-4 offset-md-4">Browse.</h2>
<h2 class="col-md-4 offset-md-4">create.</h2>
<h2 class="col-md-4 offset-md-4">share.</h2>
</div>
</div>
</div>
</div>
You can try this.
Since it's not mentioned here yet: You should also take a look at Dojox.drawing, which also provides good SVG drawing capabilities. It has a pretty impressive set of features. I'm just starting a project with it, but it seems to me that it's far superior (at least in terms of features) to Raphael and JQuerySVG.
This presentation convinced me to use it instead of Raphael/JQuerySVG: http://www.slideshare.net/elazutkin/dojo-gfx-svg-in-the-real-world-2114082
Reference: http://dojotoolkit.org/reference-guide/dojox/index.html
Reference on Dojocampus: http://docs.dojocampus.org/dojox/drawing
Download Dojo (including Dojox): http://dojotoolkit.org/download/
You can simply use JavaScripts join()
function for that. This would simply look like a.value.join(',')
. The output would be a string though.
If you're using Python 3, you can you use the star before a variable (on the left side of an assignment) to have it be a list in unpacking.
# Example 1: a is 1 and b is [2, 3]
a, *b = [1, 2, 3]
# Example 2: a is 1, b is [2, 3], and c is 4
a, *b, c = [1, 2, 3, 4]
# Example 3: b is [1, 2] and c is 3
*b, c = [1, 2, 3]
# Example 4: a is 1 and b is []
a, *b = [1]
You need to install the Chrome driver. You can install this package using NuGet as shown below:
ResponseEntity
is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.
@ResponseBody
is a marker for the HTTP response body and @ResponseStatus
declares the status code of the HTTP response.
@ResponseStatus
isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse
or a HttpHeaders
parameter.
Basically, ResponseEntity
lets you do more.
Your code is correct. Kindly mark small correction.
#rightcolumn {
width: 750px;
background-color: #777;
display: block;
**float: left;(wrong)**
**float: right; (corrected)**
border: 1px solid white;
}
alignment-baseline
is not the right attribute to use here. The correct answer is to use a combination of dominant-baseline="central"
and text-anchor="middle"
:
<svg width="200" height="100">_x000D_
<g>_x000D_
<rect x="0" y="0" width="200" height="100" style="stroke:red; stroke-width:3px; fill:white;"/>_x000D_
<text x="50%" y="50%" style="dominant-baseline:central; text-anchor:middle; font-size:40px;">TEXT</text>_x000D_
</g>_x000D_
</svg>
_x000D_
So ... more digging, with the result. It seems that although I ran one process normal and one "As Administrator", I had UAC off. Turning UAC to medium allowed me to see different results. Basically, it all boils down to integrity levels, which are 5.
Browsers, for example, run at Low Level (1), while services (System user) run at System Level (4). Everything is very well explained in Windows Integrity Mechanism Design . When UAC is enabled, processes are created with Medium level (SID S-1-16-8192 AKA 0x2000 is added) while when "Run as Administrator", the process is created with High Level (SID S-1-16-12288 aka 0x3000).
So the correct ACCESS_TOKEN for a normal user (Medium Integrity level) is:
0:000:x86> !token
Thread is not impersonating. Using process token...
TS Session ID: 0x1
User: S-1-5-21-1542574918-171588570-488469355-1000
Groups:
00 S-1-5-21-1542574918-171588570-488469355-513
Attributes - Mandatory Default Enabled
01 S-1-1-0
Attributes - Mandatory Default Enabled
02 S-1-5-32-544
Attributes - DenyOnly
03 S-1-5-32-545
Attributes - Mandatory Default Enabled
04 S-1-5-4
Attributes - Mandatory Default Enabled
05 S-1-2-1
Attributes - Mandatory Default Enabled
06 S-1-5-11
Attributes - Mandatory Default Enabled
07 S-1-5-15
Attributes - Mandatory Default Enabled
08 S-1-5-5-0-1908477
Attributes - Mandatory Default Enabled LogonId
09 S-1-2-0
Attributes - Mandatory Default Enabled
10 S-1-5-64-10
Attributes - Mandatory Default Enabled
11 S-1-16-8192
Attributes - GroupIntegrity GroupIntegrityEnabled
Primary Group: LocadDumpSid failed to dump Sid at addr 000000000266b458, 0xC0000078; try own SID dump.
s-1-0x515000000
Privs:
00 0x000000013 SeShutdownPrivilege Attributes -
01 0x000000017 SeChangeNotifyPrivilege Attributes - Enabled Default
02 0x000000019 SeUndockPrivilege Attributes -
03 0x000000021 SeIncreaseWorkingSetPrivilege Attributes -
04 0x000000022 SeTimeZonePrivilege Attributes -
Auth ID: 0:1d1f65
Impersonation Level: Anonymous
TokenType: Primary
Is restricted token: no.
Now, the differences are as follows:
S-1-5-32-544
Attributes - Mandatory Default Enabled Owner
for "As Admin", while
S-1-5-32-544
Attributes - DenyOnly
for non-admin.
Note that S-1-5-32-544 is BUILTIN\Administrators. Also, there are fewer privileges, and the most important thing to notice:
admin:
S-1-16-12288
Attributes - GroupIntegrity GroupIntegrityEnabled
while for non-admin:
S-1-16-8192
Attributes - GroupIntegrity GroupIntegrityEnabled
I hope this helps.
Further reading: http://www.blackfishsoftware.com/blog/don/creating_processes_sessions_integrity_levels
giammin's solution is partially incorrect. You SHOULD NOT remove that entire PropertyGroup from your solution. If you do, MSBuild's "DeployTarget=Package" feature will stop working. This feature relies on the "VSToolsPath" being set.
<PropertyGroup>
<!-- VisualStudioVersion is incompatible with later versions of Visual Studio. Removing. -->
<!-- <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion> -->
<!-- VSToolsPath is required by MSBuild for features like "DeployTarget=Package" -->
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
...
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
Swift 4.0 Xcode 10.0 with a TabViewController as last view
If your last ViewController is embebed in a TabViewController the below code will send you to the root...
navigationController?.popToRootViewController(animated: true)
navigationController?.popViewController(animated: true)
But If you really want to go back to the last view (That could be Tab1, Tab2 or Tab3 view..)you have to write the below code:
_ = self.navigationController?.popViewController(animated: true)
This works for me, i was using a view after one of my TabView :)
run - Create a container using image and Start the same. (Create & Start)
start - Start the container(s) in docker list which was in stopped state.
Here's a short example, that creates and array of objects, and sorts numerically or alphabetically:
// Create Objects Array
var arrayCarObjects = [
{brand: "Honda", topSpeed: 45},
{brand: "Ford", topSpeed: 6},
{brand: "Toyota", topSpeed: 240},
{brand: "Chevrolet", topSpeed: 120},
{brand: "Ferrari", topSpeed: 1000}
];
// Sort Objects Numerically
arrayCarObjects.sort((a, b) => (a.topSpeed - b.topSpeed));
// Sort Objects Alphabetically
arrayCarObjects.sort((a, b) => (a.brand > b.brand) ? 1 : -1);
My recommendation is TORA
I find that the best way to do this is to use SUMPRODUCT
instead:
=SUMPRODUCT((A1:A10<>"")*1)
It's also pretty great if you want to throw in more criteria:
=SUMPRODUCT((A1:A10<>"")*(A1:A10>$B$1)*(A1:A10<=$B$2))
Check out the PHP cURL functions. They should do what you want.
Or if you just want a simple URL GET then:
$lines = file('http://www.example.com/');
I hope this will help somebody, I solved the problem like this
There was a problem because the database was not open. Command startup opens the database.
This you can solve with command alter database open
in some case with alter database open resetlogs
$ sqlplus / sysdba
SQL> startup
ORACLE instance started.
Total System Global Area 1073741824 bytes
Fixed Size 8628936 bytes
Variable Size 624952632 bytes
Database Buffers 436207616 bytes
Redo Buffers 3952640 bytes
Database mounted.
Database opened.
SQL> conn user/pass123
Connected.
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public List<StudentEntity> findAllByOrderByIdAsc();
}
The code above should work. I'm using something similar:
public List<Pilot> findTop10ByOrderByLevelDesc();
It returns 10 rows with the highest level.
IMPORTANT: Since I've been told that it's easy to miss the key point of this answer, here's a little clarification:
findAllByOrderByIdAsc(); // don't miss "by"
^
If you're running this with php file.php
. You need to edit php.ini
Find this file:
: locate php.ini
/etc/php/php.ini
And append file's path to open_basedir
property:
open_basedir = /srv/http/:/home/:/tmp/:/usr/share/pear/:/usr/share/webapps/:/etc/webapps/:/run/media/andrew/ext4/protected
If you want to use column names to select the columns, simply use .()
, which is an alias for list()
:
library(data.table)
dt <- data.table(a = 1:2, b = 2:3, c = 3:4)
dt[ , .(b, c)] # select the columns b and c
# Result:
# b c
# 1: 2 3
# 2: 3 4
While working on a project, this was also my question. As stated above, the HAVING checks the condition on the query result already found. But WHERE is for checking condition while query runs.
Let me give an example to illustrate this. Suppose you have a database table like this.
usertable{ int userid, date datefield, int dailyincome }
Suppose, the following rows are in table:
1, 2011-05-20, 100
1, 2011-05-21, 50
1, 2011-05-30, 10
2, 2011-05-30, 10
2, 2011-05-20, 20
Now, we want to get the userid
s and sum(dailyincome)
whose sum(dailyincome)>100
If we write:
SELECT userid, sum(dailyincome) FROM usertable WHERE sum(dailyincome)>100 GROUP BY userid
This will be an error. The correct query would be:
SELECT userid, sum(dailyincome) FROM usertable GROUP BY userid HAVING sum(dailyincome)>100
I am using Sequelize ORM 6.0.0 and am using "logging": false as the rest but posted my answer for latest version of the ORM.
const sequelize = new Sequelize(
process.env.databaseName,
process.env.databaseUser,
process.env.password,
{
host: process.env.databaseHost,
dialect: process.env.dialect,
"logging": false,
define: {
// Table names won't be pluralized.
freezeTableName: true,
// All tables won't have "createdAt" and "updatedAt" Auto fields.
timestamps: false
}
}
);
Note: I am storing my secretes in a configuration file .env
observing the 12-factor methodology.
You can try searching for local .m2 repository by using the command in the project directory.
mvn help:evaluate -Dexpression=settings.localRepository
your output will be similar to below and you can see local .m2 directory path as shown below: /Users/arai/.m2/repository
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.7/commons-lang3-3.7.jar
Downloaded from central: https://repo.maven.apache.org/maven2/net/sf/jtidy/jtidy/r938/jtidy-r938.jar (250 kB at 438 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/commons-codec/commons-codec/1.11/commons-codec-1.11.jar (335 kB at 530 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar (305 kB at 430 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.7/commons-lang3-3.7.jar (500 kB at 595 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/com/thoughtworks/xstream/xstream/1.4.11.1/xstream-1.4.11.1.jar (621 kB at 671 kB/s)
[INFO] No artifact parameter specified, using 'org.apache.maven:standalone-pom:pom:1' as project.
[INFO]
/Users/arai/.m2/repository
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.540 s
[INFO] Finished at: 2019-01-23T13:57:54-05:00
[INFO] ------------------------------------------------------------------------
You can set the cookie after having checked if it exists with a value.
$(document).ready(function(){
if ($.cookie('cookie')) { //if cookie isset
//do stuff here like hide a popup when cookie isset
//document.getElementById("hideElement").style.display = "none";
}else{
var CookieSet = $.cookie('cookie', 'value'); //set cookie
}
});
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName();
and hit return.
Do
$userinput = <STDIN>; #read stdin and put it in $userinput
chomp ($userinput); #cut the return / line feed character
if you want to read just one line
Personally i think you should learn the hard way first. It will make you a better programmer and you will be able to solve that one of a kind issue when it comes up. After you can do it with pure JavaScript then using jQuery to speed up development is just an added bonus.
If you can do it the hard way then you can do it the easy way, it doesn't work the other way around. That applies to any programming paradigm.
The OnChange
event is a good choice. But if a user select the same image, the event will not be triggered because the current value is the same as the previous.
The image is the same with a width changed, for example, and it should be uploaded to the server.
To prevent this problem you could to use the following code:
$(document).ready(function(){
$("input[type=file]").click(function(){
$(this).val("");
});
$("input[type=file]").change(function(){
alert($(this).val());
});
});
On mobile devices sending everything to the GPU will cause a memory overload and crash the application. I encountered this on an iPad app in Cordova. Best to only send the required items to the GPU, the divs that you're specifically moving around.
Better yet, use the 3d transitions transforms to do the animations like translateX(50px) as opposed to left:50px;
10 * * * Sun
Position 1 for minutes, allowed values are 1-60
position 2 for hours, allowed values are 1-24
position 3 for day of month ,allowed values are 1-31
position 4 for month ,allowed values are 1-12
position 5 for day of week ,allowed values are 1-7 or and the day starts at Monday.
In my case I was trying ssh like this
ssh [email protected]:22
when the correct format is:
ssh [email protected] -p 22
The synchronized
keyword causes a thread to obtain a lock when entering the method, so that only one thread can execute the method at the same time (for the given object instance, unless it is a static method).
This is frequently called making the class thread-safe, but I would say this is a euphemism. While it is true that synchronization protects the internal state of the Vector from getting corrupted, this does not usually help the user of Vector much.
Consider this:
if (vector.isEmpty()){
vector.add(data);
}
Even though the methods involved are synchronized, because they are being locked and unlocked individually, two unfortunately timed threads can create a vector with two elements.
So in effect, you have to synchronize in your application code as well.
Because method-level synchronization is a) expensive when you don't need it and b) insufficient when you need synchronization, there are now un-synchronized replacements (ArrayList in the case of Vector).
More recently, the concurrency package has been released, with a number of clever utilities that take care of multi-threading issues.
This shows the licence type and number of licences:
SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')
Your question is similar to below:
What is the difference between application server and web server?
In Java: Web Container or Servlet Container or Servlet Engine : is used to manage the components like Servlets, JSP. It is a part of the web server.
Web Server or HTTP Server: A server which is capable of handling HTTP requests, sent by a client and respond back with a HTTP response.
Application Server or App Server: can handle all application operations between users and an organization's back end business applications or databases.It is frequently viewed as part of a three-tier application with: Presentation tier, logic tier,Data tier
A functional approach must consider using only pure functions without side effects, each of which is only concerned with a single job.
These restrictions enhance the composability and reusability of the functions involved.
// small, reusable auxiliary functions_x000D_
_x000D_
const createSet = xs => new Set(xs);_x000D_
const filter = f => xs => xs.filter(apply(f));_x000D_
const apply = f => x => f(x);_x000D_
_x000D_
_x000D_
// intersection_x000D_
_x000D_
const intersect = xs => ys => {_x000D_
const zs = createSet(ys);_x000D_
return filter(x => zs.has(x)_x000D_
? true_x000D_
: false_x000D_
) (xs);_x000D_
};_x000D_
_x000D_
_x000D_
// mock data_x000D_
_x000D_
const xs = [1,2,2,3,4,5];_x000D_
const ys = [0,1,2,3,3,3,6,7,8,9];_x000D_
_x000D_
_x000D_
// run it_x000D_
_x000D_
console.log( intersect(xs) (ys) );
_x000D_
Please note that the native Set
type is used, which has an advantageous
lookup performance.
Obviously repeatedly occurring items from the first Array
are preserved, while the second Array
is de-duplicated. This may be or may be not the desired behavior. If you need a unique result just apply dedupe
to the first argument:
// auxiliary functions_x000D_
_x000D_
const apply = f => x => f(x);_x000D_
const comp = f => g => x => f(g(x));_x000D_
const afrom = apply(Array.from);_x000D_
const createSet = xs => new Set(xs);_x000D_
const filter = f => xs => xs.filter(apply(f));_x000D_
_x000D_
_x000D_
// intersection_x000D_
_x000D_
const intersect = xs => ys => {_x000D_
const zs = createSet(ys);_x000D_
return filter(x => zs.has(x)_x000D_
? true_x000D_
: false_x000D_
) (xs);_x000D_
};_x000D_
_x000D_
_x000D_
// de-duplication_x000D_
_x000D_
const dedupe = comp(afrom) (createSet);_x000D_
_x000D_
_x000D_
// mock data_x000D_
_x000D_
const xs = [1,2,2,3,4,5];_x000D_
const ys = [0,1,2,3,3,3,6,7,8,9];_x000D_
_x000D_
_x000D_
// unique result_x000D_
_x000D_
console.log( intersect(dedupe(xs)) (ys) );
_x000D_
Array
sIf you want to compute the intersection of an arbitrarily number of Array
s just compose intersect
with foldl
. Here is a convenience function:
// auxiliary functions_x000D_
_x000D_
const apply = f => x => f(x);_x000D_
const uncurry = f => (x, y) => f(x) (y);_x000D_
const createSet = xs => new Set(xs);_x000D_
const filter = f => xs => xs.filter(apply(f));_x000D_
const foldl = f => acc => xs => xs.reduce(uncurry(f), acc);_x000D_
_x000D_
_x000D_
// intersection_x000D_
_x000D_
const intersect = xs => ys => {_x000D_
const zs = createSet(ys);_x000D_
return filter(x => zs.has(x)_x000D_
? true_x000D_
: false_x000D_
) (xs);_x000D_
};_x000D_
_x000D_
_x000D_
// intersection of an arbitrarily number of Arrays_x000D_
_x000D_
const intersectn = (head, ...tail) => foldl(intersect) (head) (tail);_x000D_
_x000D_
_x000D_
// mock data_x000D_
_x000D_
const xs = [1,2,2,3,4,5];_x000D_
const ys = [0,1,2,3,3,3,6,7,8,9];_x000D_
const zs = [0,1,2,3,4,5,6];_x000D_
_x000D_
_x000D_
// run_x000D_
_x000D_
console.log( intersectn(xs, ys, zs) );
_x000D_
This is the new way to do it:
Path root = FileSystems.getDefault().getPath("").toAbsolutePath();
Path filePath = Paths.get(root.toString(),"src", "main", "resources", fileName);
Or even better:
Path root = Paths.get(".").normalize().toAbsolutePath();
But I would take it one step further:
public String getUsersProjectRootDirectory() {
String envRootDir = System.getProperty("user.dir");
Path rootDIr = Paths.get(".").normalize().toAbsolutePath();
if ( rootDir.startsWith(envRootDir) ) {
return rootDir;
} else {
throw new RuntimeException("Root dir not found in user directory.");
}
}
https://forums.oracle.com/forums/thread.jspa?threadID=447344
The pertinent section reads:
There's no setting to fetch all records. You wouldn't like SQL Developer to fetch for minutes on big tables anyway. If, for 1 specific table, you want to fetch all records, you can do Control-End in the results pane to go to the last record. You could time the fetching time yourself, but that will vary on the network speed and congestion, the program (SQL*Plus will be quicker than SQL Dev because it's more simple), etc.
There is also a button on the toolbar which is a "Fetch All
" button.
FWIW Be careful retrieving all records, for a very large recordset it could cause you to have all sorts of memory issues etc.
As far as I know, SQL Developer uses JDBC behind the scenes to fetch the records and the limit is set by the JDBC setMaxRows()
procedure, if you could alter this (it would prob be unsupported) then you might be able to change the SQL Developer behaviour.
If it's jQuery...
$("#myText").val('');
or
document.getElementById('myText').value = '';
Reference: Text Area Object
Open the file using Notepad++ and check the "Encoding" menu, you can check the current Encoding and/or Convert to a set of encodings available.
eburgos, I've modified your code slightly because when you have multiple datatables in your dataset it was just overwriting them in the spreadsheet so you were only left with one sheet in the workbook. I basically just moved the part where the workbook is created out of the loop. Here is the updated code.
private void ExportDSToExcel(DataSet ds, string destination)
{
using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();
uint sheetId = 1;
foreach (DataTable table in ds.Tables)
{
var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
{
sheetId =
sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
sheets.Append(sheet);
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
List<String> columns = new List<string>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow dsrow in table.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (String col in columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
}
}
}
For MySQL, this can be shortened to:
SELECT distributor_id,
COUNT(*) total,
SUM(level = 'exec') ExecCount,
SUM(level = 'personal') PersonalCount
FROM yourtable
GROUP BY distributor_id
Run command. You will get installed extentions:
php -r "print_r(get_loaded_extensions());"
Or run this command to get all module install and uninstall with version
dpkg -l | grep php5
I liked the solution that does it from Application_Start()
as in the answer here
Apparently I could not access the json objects in JavaScript using the configuration within my function as in DalSoft's answer as the object returned had "\n \r" all over the (key, val) of the object.
Anyway whatever works is great (because different approaches work in different scenario based on the comments and questions asked) though a standard way of doing it would be preferable with some good documentation supporting the approach.
Handles hex, octal, binary, int, and float
Using the standard prefixes (i.e. 0x, 0b, 0, and 0o) this function will convert any suitable string to a number. I answered this here: https://stackoverflow.com/a/58997070/2464381 but here is the needed function.
def to_number(n):
''' Convert any number representation to a number
This covers: float, decimal, hex, and octal numbers.
'''
try:
return int(str(n), 0)
except:
try:
# python 3 doesn't accept "010" as a valid octal. You must use the
# '0o' prefix
return int('0o' + n, 0)
except:
return float(n)
If you're using bash you can just say
if grep -q "$SOURCE" <<< "$LIST" ; then
...
fi
Actually, scala has old Java-style loops with index:
scala> val xs = Array("first","second","third")
xs: Array[java.lang.String] = Array(first, second, third)
scala> for (i <- 0 until xs.length)
| println("String # " + i + " is "+ xs(i))
String # 0 is first
String # 1 is second
String # 2 is third
Where 0 until xs.length
or 0.until(xs.length)
is a RichInt
method which returns Range
suitable for looping.
Also, you can try loop with to
:
scala> for (i <- 0 to xs.length-1)
| println("String # " + i + " is "+ xs(i))
String # 0 is first
String # 1 is second
String # 2 is third
this question asked in 2009 but i want to share my codes:
Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable
Dim x As Integer
Dim y As Integer
Dim bln As Boolean
Dim dttable2 As New DataTable
For x = 0 To dttable.Columns.Count - 1
dttable2.Columns.Add(dttable.Columns(x).ColumnName)
Next
For x = 0 To dttable.Rows.Count - 1
For y = 0 To searchcolumns.Length - 1
If String.IsNullOrEmpty(searchcolumns(y)) = False Then
If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
bln = True
Else
bln = False
Exit For
End If
End If
Next
If bln = True Then
dttable2.Rows.Add(dttable.Rows(x).ItemArray)
End If
Next
Return dttable2
End Function
YOUR-COMMAND &> YOUR-LOG.log &
This should run the command and assign a process id you can simply tail -f YOUR-LOG.log to see results written to it as they happen. you can log out anytime and the process will carry on
In your doSomething()
function, pass in the event e
and use e.preventDefault()
.
doSomething = function (e) {
alert('it works!');
e.preventDefault();
}
Add the image to Your project by clicking File -> "Add Files to ...".
Then choose the image in ImageView properties (Utilities -> Attributes Inspector).
That's known as an Arrow Function, part of the ECMAScript 2015 spec...
var foo = ['a', 'ab', 'abc'];_x000D_
_x000D_
var bar = foo.map(f => f.length);_x000D_
_x000D_
console.log(bar); // 1,2,3
_x000D_
Shorter syntax than the previous:
// < ES6:_x000D_
var foo = ['a', 'ab', 'abc'];_x000D_
_x000D_
var bar = foo.map(function(f) {_x000D_
return f.length;_x000D_
});_x000D_
console.log(bar); // 1,2,3
_x000D_
The other awesome thing is lexical this
... Usually, you'd do something like:
function Foo() {_x000D_
this.name = name;_x000D_
this.count = 0;_x000D_
this.startCounting();_x000D_
}_x000D_
_x000D_
Foo.prototype.startCounting = function() {_x000D_
var self = this;_x000D_
setInterval(function() {_x000D_
// this is the Window, not Foo {}, as you might expect_x000D_
console.log(this); // [object Window]_x000D_
// that's why we reassign this to self before setInterval()_x000D_
console.log(self.count);_x000D_
self.count++;_x000D_
}, 1000)_x000D_
}_x000D_
_x000D_
new Foo();
_x000D_
But that could be rewritten with the arrow like this:
function Foo() {_x000D_
this.name = name;_x000D_
this.count = 0;_x000D_
this.startCounting();_x000D_
}_x000D_
_x000D_
Foo.prototype.startCounting = function() {_x000D_
setInterval(() => {_x000D_
console.log(this); // [object Object]_x000D_
console.log(this.count); // 1, 2, 3_x000D_
this.count++;_x000D_
}, 1000)_x000D_
}_x000D_
_x000D_
new Foo();
_x000D_
For more, here's a pretty good answer for when to use arrow functions.
The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.
You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:
In computers, these two actions are represented by two different characters - carriage return is CR
, ASCII character 13, vbCr
; line feed is LF
, ASCII character 10, vbLf
. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF
-- to start a new line, and so the CRLF
combination -- vbCrLf
-- became a traditional line ending sequence, in some computing environments.
The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF
alone (used in Unix and Macintoshes), CR
alone (apparently used in older Mac OSes) and the CRLF
combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode
, where any CRLF
pair read from the file was converted to a single CR
(and vice versa when writing).
So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine
which means someone else has decided for you which to use, and future portability issues should be reduced.
They cause the compiler to emit the appropriate branch hints where the hardware supports them. This usually just means twiddling a few bits in the instruction opcode, so code size will not change. The CPU will start fetching instructions from the predicted location, and flush the pipeline and start over if that turns out to be wrong when the branch is reached; in the case where the hint is correct, this will make the branch much faster - precisely how much faster will depend on the hardware; and how much this affects the performance of the code will depend on what proportion of the time hint is correct.
For instance, on a PowerPC CPU an unhinted branch might take 16 cycles, a correctly hinted one 8 and an incorrectly hinted one 24. In innermost loops good hinting can make an enormous difference.
Portability isn't really an issue - presumably the definition is in a per-platform header; you can simply define "likely" and "unlikely" to nothing for platforms that do not support static branch hints.
For the best possible browser support, your CSS code should look like this :
@font-face {
font-family: 'MyWebFont';
src: url('webfont.eot'); /* IE9 Compat Modes */
src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
url('webfont.ttf') format('truetype'), /* Safari, Android, iOS */
url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}
body {
font-family: 'MyWebFont', Fallback, sans-serif;
}
For more info, see the article Using @font-face at CSS-tricks.com.
#!/bin/bash
variable=`ps -ef | grep "port 10 -" | grep -v "grep port 10 -" | awk '{printf $12}'`
echo $variable
Notice that there's no space after the equal sign.
You can also use $()
which allows nesting and is readable.
You can bind to dom directly
<div dangerouslySetInnerHTML={{__html: '<p>First · Second</p>'}}></div>
fireTableStructureChanged();
will default the resize behavior ! If this method is called somewhere in your code AFTER you did set the column resize properties all your settings will be reset. This side effect can happen indirectly. F.e. as a consequence of the linked data model being changed in a way this method is called, after properties are set.
You need to subscribe to the observable and pass a callback that processes emitted values
this.myService.getConfig().subscribe(val => console.log(val));
You also could use simpler regex designed for your case like (.*)\/(([^\?\n\r])*)
where $2
match what you want.
SQL*Plus uses &1, &2... &n to access the parameters.
Suppose you have the following script test.sql
:
SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off
you could call this script like this for example:
$ sqlplus login/pw @test Hello World!
In a UNIX script you would usually call a SQL script like this:
sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF
so that your login/password won't be visible with another session's ps
This works at least in Python3.4
import subprocess
process = subprocess.Popen(cmd_list, stdout=subprocess.PIPE)
for line in process.stdout:
print(line.decode().strip())
I tried all the above solutions, however none of them worked. If you're on linux/macOS i highly suggest using tsocks over an ssh tunnel. What you need in order to get this setup working is a machine where you can log in via ssh, and in addition to that a programm called tsocks installed.
The idea here is to create a dynamic tunnel via SSH (a socks5 proxy). We then configure tsocks to use this tunnel and to start our applications, in this case:
tsocks gem install ...
or to account for rails 3.0:
tsocks bundle install
A more detailed guide can be found under:
http://blog.byscripts.info/2011/04/bypass-a-proxy-with-ssh-tunnel-and-tsocks-under-ubuntu/
Despite being written for Ubuntu the procedure should be applicable for all Unix based machines. An alternative to tsocks for Windows is FreeCap (http://www.freecap.ru/eng/). A viable SSH client on windows is called putty.
you can use layout_constraintCircle for center view inside ConstraintLayout.
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mparent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/btn_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_home_black_24dp"
app:layout_constraintCircle="@id/mparent"
app:layout_constraintCircleRadius="0dp"
/>
</android.support.constraint.ConstraintLayout>
with constraintCircle to parent and zero radius you can make your view be center of parent.
What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);
my @array = ();
should work just fine -- it allocates a new array called @array
, and then assigns it the empty list, ()
. Note that this is identical to simply saying my @array;
, since the initial value of a new array is the empty list anyway.
Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings;
in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)
An IEnumerator
is a thing that can enumerate: it has the Current
property and the MoveNext
and Reset
methods (which in .NET code you probably won't call explicitly, though you could).
An IEnumerable
is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator
.
Which do you use? The only reason to use IEnumerator
is if you have something that has a nonstandard way of enumerating (that is, of returning its various elements one-by-one), and you need to define how that works. You'd create a new class implementing IEnumerator
. But you'd still need to return that IEnumerator
in an IEnumerable
class.
For a look at what an enumerator (implementing IEnumerator<T>
) looks like, see any Enumerator<T>
class, such as the ones contained in List<T>
, Queue<T>,
or Stack<T>
. For a look at a class implementing IEnumerable
, see any standard collection class.
Maybe worth looking at QRGen, which is built on top of ZXing and supports UTF-8 with this kind of syntax:
// if using special characters don't forget to supply the encoding
VCard johnSpecial = new VCard("Jöhn D?e")
.setAdress("ëåäö? Sträät 1, 1234 Döestüwn");
QRCode.from(johnSpecial).withCharset("UTF-8").file();
One fast solution is set image property for image1 and set backgroundimage property to imag2, the only inconvenience is that you have the two images inside the picture box, but you can change background properties to tile, streched, etc. Make sure that backcolor be transparent. Hope this helps
By default, Rails 4 uses the 'value' attribute to control the visible button text, so to keep the markup clean I would use
<%= f.submit :value => "Visible Button Text", :class => 'class_name' %>
Swift
You should always use the system defaults and not hard coding the font name because the default font could be changed by Apple at any time.
There are a couple of system default fonts(normal, bold, italic) with different sizes(label, button, others):
let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let font2 = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
let font3 = UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)
beaware that the default font size depends on the target view (label, button, others)
Examples:
let labelFont = UIFont.systemFont(ofSize: UIFont.labelFontSize)
let buttonFont = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
let textFieldFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)
I think a 32 bit JVM has a maximum of 2GB memory.This might be out of date though. If I understood correctly, you set the -Xmx on Eclipse launcher. If you want to increase the memory for the program you run from Eclipse, you should define -Xmx in the "Run->Run configurations..."(select your class and open the Arguments tab put it in the VM arguments area) menu, and NOT on Eclipse startup
Edit: details you asked for. in Eclipse 3.4
Run->Run Configurations...
if your class is not listed in the list on the left in the "Java Application" subtree, click on "New Launch configuration" in the upper left corner
on the right, "Main" tab make sure the project and the class are the right ones
select the "Arguments" tab on the right.
this one has two text areas. one is for the program arguments that get in to the args[] array supplied to your main method. the other one is for the VM arguments. put into the one with the VM arguments(lower one iirc) the following:
-Xmx2048m
I think that 1024m should more than enough for what you need though!
Click Apply, then Click Run
Should work :)
The problem appears to be that the global symbol clear
is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah
), it works just fine:
Live: Version using clear
which fails | Version using blah
which works
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function blah() {
document.getElementById("goy").innerHTML = "";
}
</script>
</body>
</html>
This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this.
A corollary to that is to not use old-style onxyz=...
attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 id="the-header">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
// Scoping function makes the declarations within
// it *not* globals
(function(){
var header = document.getElementById("the-header");
header.onmouseover = function() {
go('The dog is in its shed');
};
header.onmouseout = clear;
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
})();
</script>
</body>
</html>
...and even better, use DOM2's addEventListener
(or attachEvent
on IE8 and earlier) so you can have multiple handlers for an event on an element.
text2 = text2.textureName.replacingOccurrences(of: "\"", with: "", options: NSString.CompareOptions.literal, range:nil)
Latest documents updated to Swift 3.0.1 have:
- Null Character (
\0
)- Backslash (
\\
)- Horizontal Tab (
\t
)- Line Feed (
\n
)- Carriage Return (
\r
)- Double Quote (
\"
)- Single Quote (
\'
)- Unicode scalar (
\u{n}
), where n is between one and eight hexadecimal digits
If you need more details you can take a look to the official docs here
Firebase: https://firebase.google.com/docs/cloud-messaging/
GCM(Deprecated): http://developer.android.com/google/gcm/index.html
I don't have much knowledge about C2DM. Use GCM, it's very easy to implement and configure.
If I understand your question correctly, it appears you want to know the following:
How do I check if my
String
array containsusercode
, theString
that was just inputted?
See here for a similar question. It quotes solutions that have been pointed out by previous answers. I hope this helps.
This method was
deprecatedin API level 24.
You should use FROM_HTML_MODE_LEGACY
Separate block-level elements with blank lines (two newline characters) in between. This is the legacy behavior prior to N.
Code
if (Build.VERSION.SDK_INT >= 24)
{
etOBJ.setText(Html.fromHtml("Intellij \n Amiyo",Html.FROM_HTML_MODE_LEGACY));
}
else
{
etOBJ.setText(Html.fromHtml("Intellij \n Amiyo"));
}
For Kotlin
fun setTextHTML(html: String): Spanned
{
val result: Spanned = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
} else {
Html.fromHtml(html)
}
return result
}
Call
txt_OBJ.text = setTextHTML("IIT Amiyo")
All of these internally end up calling a method called InternalGetValueAsString
. The difference between ToString
and GetName
would be that GetName
has to verify a few things first:
GetType
on the value to check this. .ToString
doesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToString
method doesn't have the same verification issues as the static methods, I would conclude that .ToString
is the fastest way to get the value as a string.
In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key
publickey = key.publickey() # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
This only works for convex shapes, but Minkowski Portal Refinement, and GJK are also great options for testing if a point is in a polygon. You use minkowski subtraction to subtract the point from the polygon, then run those algorithms to see if the polygon contains the origin.
Also, interestingly, you can describe your shapes a bit more implicitly using support functions which take a direction vector as input and spit out the farthest point along that vector. This allows you to describe any convex shape.. curved, made out of polygons, or mixed. You can also do operations to combine the results of simple support functions to make more complex shapes.
More info: http://xenocollide.snethen.com/mpr2d.html
Also, game programming gems 7 talks about how to do this in 3d (:
I think you should use, instead of document.write
, DOM JavaScript API like document.createElement
, .createTextNode
, .appendChild
and similar. Safe and almost cross browser.
ihunger's outerHTML
is not cross browser, it's IE only.
There is a free library called barcode4j
If you want to trigger the keypress or keydown event then all you have to do is:
var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
$("input").trigger(e);
I am currently checking a large number of conditions, which becomes unwieldy using the if statement method beyond say 4 conditions. Just to share a clean looking alternative for future viewers... which scales nicely, I use:
var a = 0;
var b = 0;
a += ("condition 1")? 1 : 0; b += 1;
a += ("condition 2")? 1 : 0; b += 1;
a += ("condition 3")? 1 : 0; b += 1;
a += ("condition 4")? 1 : 0; b += 1;
a += ("condition 5")? 1 : 0; b += 1;
a += ("condition 6")? 1 : 0; b += 1;
// etc etc
if(a == b) {
//do stuff
}
Your Maven is reading Java version as 1.6.0_65, Where as the pom.xml says the version is 1.7.
Try installing the required verison.
If already installed check your $JAVA_HOME environment variable, it should contain the path of Java JDK 7. If you dont find it, fix your environment variable.
also remove the lines
<fork>true</fork>
<executable>${JAVA_1_7_HOME}/bin/javac</executable>
from the pom.xml
Put the content on google drive and make it download protect. This way people can only see your documents, pictures but cannot download it.
When you choose any value from spinner, then you get selected value,
interested.getSelectedItem().toString();
ffmpeg -codecs
should give you all the info about the codecs available.
You will see some letters next to the codecs:
Codecs:
D..... = Decoding supported
.E.... = Encoding supported
..V... = Video codec
..A... = Audio codec
..S... = Subtitle codec
...I.. = Intra frame-only codec
....L. = Lossy compression
.....S = Lossless compression
Though you can have several <form>
elements in one HTML page, you cannot nest them.
From SQL Server 2012 you can use a native pagination in order to have semplicity and best performance:
Your query become:
SELECT * FROM Reflow
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC;
OFFSET 20 ROWS
FETCH NEXT 20 ROWS ONLY;
This works too ..
var image = new Image();
image.src = 'image url';
image.onload = function(e){
// functionalities on load
}
$("#img-container").append(image);
keep.update((0,1,2,3,4,5,6,7,8,9,10))
Or
keep.update(np.arange(11))
I'm not certain on what it is you're trying to achieve. But maybe you can use this:
$var =~ s/^start/foo/;
$var =~ s/end$/bar/;
I.e. just leave the middle alone and replace the start and end.
When you open a transaction nothing gets locked by itself. But if you execute some queries inside that transaction, depending on the isolation level, some rows, tables or pages get locked so it will affect other queries that try to access them from other transactions.
Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});
this function limit decimal without round number
function limitDecimal(num,decimal){
return num.toString().substring(0, num.toString().indexOf('.')) + (num.toString().substr(num.toString().indexOf('.'), decimal+1));
}
You are looking for str.rsplit()
, with a limit:
print x.rsplit('-', 1)[0]
.rsplit()
searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.
Another option is to use str.rpartition()
, which will only ever split just once:
print x.rpartition('-')[0]
For splitting just once, str.rpartition()
is the faster method as well; if you need to split more than once you can only use str.rsplit()
.
Demo:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
and the same with str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
I did it even simpler. Problem: A CSS file had url links to img folder. Gets 404.
I looked at url, http://tomcatfolder:port/img/blablah.png, which does not exist. But, that is really pointing to the ROOT app in Tomcat.
So I just copied the img folder from my webapp into that ROOT app. Works!
Not recommended for production, of course, but this is for an internal tool dev app.
Java documentation is helpful to know the root cause of a particular IOException.
Just have a look at the direct known sub-interfaces of IOException
from the documentation page:
ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException
Most of these exceptions are self-explanatory.
A few IOExceptions
with root causes:
EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.
SocketException: Thrown to indicate that there is an error creating or accessing a Socket.
RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.
UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).
MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
Semantically you are asking "insert Competitors where doesn't already exist":
INSERT Competitors (cName)
SELECT DISTINCT Name
FROM CompResults cr
WHERE
NOT EXISTS (SELECT * FROM Competitors c
WHERE cr.Name = c.cName)
To get the current router instance or current location you have to create a Higher order component with withRouter
from react-router-dom
. otherwise, when you are trying to access this.props.location
it will return undefined
Example
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
class className extends Component {
render(){
return(
....
)
}
}
export default withRouter(className)
You can break from a forEach loop if you overwrite the Array method:
(function(){
window.broken = false;
Array.prototype.forEach = function(cb, thisArg) {
var newCb = new Function("with({_break: function(){window.broken = true;}}){("+cb.replace(/break/g, "_break()")+"(arguments[0], arguments[1], arguments[2]));}");
this.some(function(item, index, array){
newCb(item, index, array);
return window.broken;
}, thisArg);
window.broken = false;
}
}())
example:
[1,2,3].forEach("function(x){\
if (x == 2) break;\
console.log(x)\
}")
Unfortunately with this solution you can't use normal break inside your callbacks, you must wrap invalid code in strings and native functions don't work directly (but you can work around that)
Happy breaking!
If you're talking about an HTTP request, you can find the request host in:
request.headers.host
But that relies on an incoming request.
More at http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest
If you're looking for machine/native information, try the process object.
Check the php.ini
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
ini_set('max_execution_time', 0); //0=NOLIMIT
The problem is that you have not included bootstrap.min.css
. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
If you can't update configuration files but control the code that handles file uploads use HttpContext.Current.Request.GetBufferlessInputStream(true)
.
The true
value for disableMaxRequestLength
parameter tells the framework to ignore configured request limits.
For detailed description visit https://msdn.microsoft.com/en-us/library/hh195568(v=vs.110).aspx
Here is another way:
df[[i for i in list(df.columns) if i != '<your column>']]
You just pass all columns to be shown except of the one you do not want.
Invoke mysql with the -N
(the alias for -N
is --skip-column-names
) option:
mysql -N ...
use testdb;
select * from names;
+------+-------+
| 1 | pete |
| 2 | john |
| 3 | mike |
+------+-------+
3 rows in set (0.00 sec)
Credit to ErichBSchulz for pointing out the -N alias.
To remove the grid (the vertical and horizontal lines) around the results use -s
(--silent
). Columns are separated with a TAB
character.
mysql -s ...
use testdb;
select * from names;
id name
1 pete
2 john
3 mike
To output the data with no headers and no grid just use both -s
and -N
.
mysql -sN ...
All I had to do was go over to oracle, and download the MySQL Connector C 6.0.2 (newer doesn't work!) and do the typical install.
https://downloads.mysql.com/archives/c-c/
Be sure to include all optional extras (Extra Binaries) via the custom install, without these it did not work for the win64.msi
Once that was done, I went into pycharms, and selected the MySQL-python>=1.2.4 package to install, and it worked great. No need to update any configuration or anything like that. This was the simplest version for me to work through.
Hope it helps
I like using pandas.apply() with python format().
import pandas as pd
s = pd.Series([1.357, 1.489, 2.333333])
make_float = lambda x: "${:,.2f}".format(x)
s.apply(make_float)
Also, it can be easily used with multiple columns...
df = pd.concat([s, s * 2], axis=1)
make_floats = lambda row: "${:,.2f}, ${:,.3f}".format(row[0], row[1])
df.apply(make_floats, axis=1)
Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see the simple example:
class Simple{
public static void main(int a){
System.out.println(a);
}
public static void main(String args[]){
System.out.println("main() method invoked");
main(10);
}
}
It will give the following output:
main() method invoked
10
>>> import numpy
>>> x = numpy.zeros((3,4))
>>> x
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
>>> y = numpy.zeros(5)
>>> y
array([ 0., 0., 0., 0., 0.])
x is a 2-d array, and y is a 1-d array. They are both initialized with zeros.
Above answers are correct, but if run script in other folder, there will be some problem.
For example, the a.sh
and b.sh
are in same folder,
a include b with . ./b.sh
to include.
When run script out of the folder, for example with xx/xx/xx/a.sh
, file b.sh
will not found: ./b.sh: No such file or directory
.
I use
. $(dirname "$0")/b.sh
What really works for me was putting my favicon into assets folder and apear automatically in the browser.
<link rel="icon" type="image/x-icon" href="assets/favicon.png">
You have two records in your json file, and json.loads()
is not able to decode more than one. You need to do it record by record.
See Python json.loads shows ValueError: Extra data
OR you need to reformat your json to contain an array:
{
"foo" : [
{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
]
}
would be acceptable again. But there cannot be several top level objects.
$('#input').on('keyup', function() {
var RegExpression = /^[a-zA-Z\s]*$/;
...
});
\s
will allow the space
In JSP, you'd normally like to use JSTL <fmt:formatDate>
for this. You can of course also throw in a scriptlet with SimpleDateFormat
, but scriptlets are strongly discouraged since 2003.
Assuming that ${bean.date}
returns java.util.Date
, here's how you can use it:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<fmt:formatDate value="${bean.date}" pattern="yyyy-MM-dd HH:mm:ss" />
If you're actually using a java.util.Calendar
, then you can invoke its getTime()
method to get a java.util.Date
out of it that <fmt:formatDate>
accepts:
<fmt:formatDate value="${bean.calendar.time}" pattern="yyyy-MM-dd HH:mm:ss" />
Or, if you're actually holding the date in a java.lang.String
(this indicates a serious design mistake in the model; you should really fix your model to store dates as java.util.Date
instead of as java.lang.String
!), here's how you can convert from one date string format e.g. MM/dd/yyyy
to another date string format e.g. yyyy-MM-dd
with help of JSTL <fmt:parseDate>
.
<fmt:parseDate pattern="MM/dd/yyyy" value="${bean.dateString}" var="parsedDate" />
<fmt:formatDate value="${parsedDate}" pattern="yyyy-MM-dd" />
i Create new E-mail without any phone number or related E-mail then Turn ON less secure app access that done with me
It supports lists, but not as a separate data structure (ignoring arrays for the moment).
The for
loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:
for i in 1 2 3; do
echo "$i"
done
or via parameter expansion:
listVar="1 2 3"
for i in $listVar; do
echo "$i"
done
or command substitution:
for i in $(echo 1; echo 2; echo 3); do
echo "$i"
done
An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:
array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do # The quotes are necessary here
echo "$i"
done
list='"item 1" "item 2" "item 3"'
for i in $list; do
echo $i
done
for i in "$list"; do
echo $i
done
for i in ${array[@]}; do
echo $i
done
You should have look at http://en.wikipedia.org/wiki/Breadth-first_search first.
Below is a quick implementation, in which I used a list of list to represent the queue of paths.
# graph is in adjacent list representation
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def bfs(graph, start, end):
# maintain a queue of paths
queue = []
# push the first path into the queue
queue.append([start])
while queue:
# get the first path from the queue
path = queue.pop(0)
# get the last node from the path
node = path[-1]
# path found
if node == end:
return path
# enumerate all adjacent nodes, construct a new path and push it into the queue
for adjacent in graph.get(node, []):
new_path = list(path)
new_path.append(adjacent)
queue.append(new_path)
print bfs(graph, '1', '11')
Another approach would be maintaining a mapping from each node to its parent, and when inspecting the adjacent node, record its parent. When the search is done, simply backtrace according the parent mapping.
graph = {
'1': ['2', '3', '4'],
'2': ['5', '6'],
'5': ['9', '10'],
'4': ['7', '8'],
'7': ['11', '12']
}
def backtrace(parent, start, end):
path = [end]
while path[-1] != start:
path.append(parent[path[-1]])
path.reverse()
return path
def bfs(graph, start, end):
parent = {}
queue = []
queue.append(start)
while queue:
node = queue.pop(0)
if node == end:
return backtrace(parent, start, end)
for adjacent in graph.get(node, []):
if node not in queue :
parent[adjacent] = node # <<<<< record its parent
queue.append(adjacent)
print bfs(graph, '1', '11')
The above codes are based on the assumption that there's no cycles.
You can loop through keys like this:
for (var key in data) {
console.log(key);
}
This logs "Name" and "Value".
If you have a more complex object type (not just a plain hash-like object, as in the original question), you'll want to only loop through keys that belong to the object itself, as opposed to keys on the object's prototype:
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key);
}
}
As you noted, keys are not guaranteed to be in any particular order. Note how this differs from the following:
for each (var value in data) {
console.log(value);
}
This example loops through values, so it would log Property Name
and 0
. N.B.: The for each
syntax is mostly only supported in Firefox, but not in other browsers.
If your target browsers support ES5, or your site includes es5-shim.js
(recommended), you can also use Object.keys
:
var data = { Name: 'Property Name', Value: '0' };
console.log(Object.keys(data)); // => ["Name", "Value"]
and loop with Array.prototype.forEach
:
Object.keys(data).forEach(function (key) {
console.log(data[key]);
});
// => Logs "Property Name", 0
you can use /<code>([\s\S]*)<\/code>/msU
this catch NEWLINES too!
This is not possible with the magic find methods. Try using the query builder:
$result = $em->getRepository("Orders")->createQueryBuilder('o')
->where('o.OrderEmail = :email')
->andWhere('o.Product LIKE :product')
->setParameter('email', '[email protected]')
->setParameter('product', 'My Products%')
->getQuery()
->getResult();
Yes, you can do it, but you have to find the position of the first string with string's find() member, and then replace with it's replace() member.
string s("hello $name");
size_type pos = s.find( "$name" );
if ( pos != string::npos ) {
s.replace( pos, 5, "somename" ); // 5 = length( $name )
}
If you are planning on using the Standard Library, you should really get hold of a copy of the book The C++ Standard Library which covers all this stuff very well.
Use http instead of https; it will give warning message and redirect to https, get cloned without any issues.
$ git clone http://github.com/karthikeyana/currency-note-classifier-counter.git
Cloning into 'currency-note-classifier-counter'...
warning: redirecting to https://github.com/karthikeyana/currency-note-classifier-counter.git
remote: Enumerating objects: 533, done.
remote: Total 533 (delta 0), reused 0 (delta 0), pack-reused 533
Receiving objects: 100% (533/533), 608.96 KiB | 29.00 KiB/s, done.
Resolving deltas: 100% (295/295), done.
Mby bootstrap img-responsive
class is you looking for.
If the case is accessing the IFrame via console, e. g. Chrome Dev Tools then you can just select the context of DOM requests via dropdown (see the picture).
I tried using objc_setAssociatedObject as mentioned in a few of the answers here, but after failing with it a few times I stepped back and realized there is no reason I need that. Borrowing from a few of the ideas here, I came up with this code which simply stores an array of whatever my extra data is (MyClass in this example) indexed by the object I want to associate it with:
class MyClass {
var a = 1
init(a: Int)
{
self.a = a
}
}
extension UIView
{
static var extraData = [UIView: MyClass]()
var myClassData: MyClass? {
get {
return UIView.extraData[self]
}
set(value) {
UIView.extraData[self] = value
}
}
}
// Test Code: (Ran in a Swift Playground)
var view1 = UIView()
var view2 = UIView()
view1.myClassData = MyClass(a: 1)
view2.myClassData = MyClass(a: 2)
print(view1.myClassData?.a)
print(view2.myClassData?.a)
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
//Function Call
requestFocus(yourEditetxt);
php\php.ini
set your loadable php extensions path (eg. extension_dir = "C:\php\ext"
)
(https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)php\php.ini
) check if extension=php_mysqli.dll
is uncommented
(https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)"C:\php"
) and php\ext folder (eg."C:\php\ext"
) as your runtime environment variable path
(https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)For multi-line shell scripts or those run multiple times, I would create a new bash script file (starting from #!/bin/bash
), and simply run it with sh
from Jenkinsfile:
sh 'chmod +x ./script.sh'
sh './script.sh'
Using the PHPExcel library to read an Excel file and transfer the data into a database
// Include PHPExcel_IOFactory
include 'PHPExcel/IOFactory.php';
$inputFileName = './sampleData/example1.xls';
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database of choice here
}
Anything more becomes very dependent on your database, and how you want the data structured in it
You can also control optimisations internally with #pragma GCC push_options
#pragma GCC push_options
/* #pragma GCC optimize ("unroll-loops") */
.... code here .....
#pragma GCC pop_options
OK so I did this and it works. It's basically hacked together from different responses here. Since there is STILL not a clear answer in this thread I decided to post this.
<script type="text/javascript">
$(document).ready(function () {
$("#logo").hide();
$("#logo").bind("load", function () { $(this).fadeIn(); });
});
</script>
This seems to me to be the best way to go about it. Despite Sohnee's best intentions he failed to mention that the object must first be set to display:none with CSS. The problem here is that if for what ever reason the user's JS is not working the object will just never appear. Not good, especially if it's the frikin' logo.
This solution leaves the item alone in the CSS, and first hides, then fades it in all using JS. This way if JS is not working properly the item will just load as normal.
Hope that helps anyone else who stumbles into this google ranked #1 not-so-helpful thread.
call generateNumbers(numbers);
, your generateNumbers();
expects int[]
as an argument
ans you were passing none, thus the error
[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);
int main(int argc, char *argv[]){
DIR *dip;
struct dirent *dit;
struct stat statbuf;
char currentPath[FILENAME_MAX];
int depth = 0; /*Used to correctly space output*/
/*Open Current Directory*/
if((dip = opendir(".")) == NULL)
return errno;
/*Store Current Working Directory in currentPath*/
if((getcwd(currentPath, FILENAME_MAX)) == NULL)
return errno;
/*Read all items in directory*/
while((dit = readdir(dip)) != NULL){
/*Skips . and ..*/
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
/*Correctly forms the path for stat and then resets it for rest of algorithm*/
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
if(stat(currentPath, &statbuf) == -1){
perror("stat");
return errno;
}
getcwd(currentPath, FILENAME_MAX);
/*Checks if current item is of the type file (type 8) and no command line arguments*/
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*If a command line argument is given, checks for filename match*/
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
if(strcmp(dit->d_name, argv[1]) == 0)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*Checks if current item is of the type directory (type 4)*/
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
closedir(dip);
return 0;
}
/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
if((dip = opendir(currentPath)) == NULL)
printf("Error: Failed to open Directory ==> %s\n", currentPath);
while((dit = readdir(dip)) != NULL){
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
stat(currentPath, &statbuf);
getcwd(currentPath, FILENAME_MAX);
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
if(strcmp(dit->d_name, argv[1]) == 0){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
}
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
/*Changing back here is necessary because of how stat is done*/
chdir("..");
closedir(dip);
}
void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
/*If two directories exist at the same level the path
is built wrong and needs to be corrected*/
if((chdir(currentPath)) == -1){
chdir("..");
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
for(i = 0; i < depth; i++)
printf (" ");
printf("%s (subdirectory)\n", dit->d_name);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
else{
for(i =0; i < depth; i++)
printf(" ");
printf("%s (subdirectory)\n", dit->d_name);
chdir(currentPath);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
}
Best explanation for X = aY + b
(in fact it f(x) = ax + b
)) is provided at https://math.stackexchange.com/a/906280/357701
A Simpler one by just adjusting lightness/luma/brightness for contrast as is below:
import cv2
img = cv2.imread('test.jpg')
cv2.imshow('test', img)
cv2.waitKey(1000)
imghsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]
cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))
cv2.waitKey(1000)
raw_input()
Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.
we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.
medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.
E.g Small Text
This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"
If you are using command line tools, then you can also set it in the shell.
On linux, with a sh type shell, you can do for example:
export NLS_TIMESTAMP_FORMAT='DD/MON/RR HH24:MI:SSXFF'
Then you can use the command line tools and it will use the specified format:
/path/to/dbhome_1/bin/sqlldr user/pass@host:port/service control=table.ctl direct=true
This will definately work for you.
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/top_bg" >
<Button
android:id="@+id/btn_report_lbAlert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="@dimen/btn_back_margin_left"
android:background="@drawable/btn_edit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:text="FlitsLimburg"
android:textColor="@color/white"
android:textSize="@dimen/tv_header_text"
android:textStyle="bold" />
<Button
android:id="@+id/btn_refresh_lbAlert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="@dimen/btn_back_margin_right"
android:background="@drawable/btn_refresh" />
</RelativeLayout>
The variable $_POST
is automatically populated.
Try var_dump($_POST);
to see the contents.
You can access individual values like this: echo $_POST["name"];
This, of course, assumes your form is using the typical form encoding (i.e. enctype=”multipart/form-data”
If your post data is in another format (e.g. JSON or XML, you can do something like this:
$post = file_get_contents('php://input');
and $post
will contain the raw data.
Assuming you're using the standard $_POST
variable, you can test if a checkbox is checked like this:
if(isset($_POST['myCheckbox']) && $_POST['myCheckbox'] == 'Yes')
{
...
}
If you have an array of checkboxes (e.g.
<form action="myscript.php" method="post">
<input type="checkbox" name="myCheckbox[]" value="A" />val1<br />
<input type="checkbox" name="myCheckbox[]" value="B" />val2<br />
<input type="checkbox" name="myCheckbox[]" value="C" />val3<br />
<input type="checkbox" name="myCheckbox[]" value="D" />val4<br />
<input type="checkbox" name="myCheckbox[]" value="E" />val5
<input type="submit" name="Submit" value="Submit" />
</form>
Using [ ]
in the checkbox name indicates that the selected values will be accessed by PHP script as an array. In this case $_POST['myCheckbox']
won't return a single string but will return an array consisting of all the values of the checkboxes that were checked.
For instance, if I checked all the boxes, $_POST['myCheckbox']
would be an array consisting of: {A, B, C, D, E}
. Here's an example of how to retrieve the array of values and display them:
$myboxes = $_POST['myCheckbox'];
if(empty($myboxes))
{
echo("You didn't select any boxes.");
}
else
{
$i = count($myboxes);
echo("You selected $i box(es): <br>");
for($j = 0; $j < $i; $j++)
{
echo $myboxes[$j] . "<br>";
}
}
Change the h1.textContent
to h1.innerHTML
and use <br>
to go to the new line.
Do you actually need more information than plain IEnumerable
gives you? Just cast it to that and use foreach
with it. I face exactly the same situation in some bits of Protocol Buffers, and I've found that casting to IEnumerable
(or IList
to access it like a list) works very well.
If you want to use the default settings from http package, so you don't need to create a new Transport and Client object, you can change to ignore the certificate verification like this:
tr := http.DefaultTransport.(*http.Transport)
tr.TLSClientConfig.InsecureSkipVerify = true
My preferred method:
if (*ptr == 0) // empty string
Probably more common:
if (strlen(ptr) == 0) // empty string
I invite you to explore what Python 3.8 has to offer for the subject matter in form of Structural subtyping (static duck typing)
(PEP 544)
See the short description https://docs.python.org/3/library/typing.html#typing.Protocol
For the simple example here it goes like this:
from typing import Protocol
class MyShowProto(Protocol):
def show(self):
...
class MyClass:
def show(self):
print('Hello World!')
class MyOtherClass:
pass
def foo(o: MyShowProto):
return o.show()
foo(MyClass()) # ok
foo(MyOtherClass()) # fails
foo(MyOtherClass())
will fail static type checks:
$ mypy proto-experiment.py
proto-experiment.py:21: error: Argument 1 to "foo" has incompatible type "MyOtherClass"; expected "MyShowProto"
Found 1 error in 1 file (checked 1 source file)
In addition, you can specify the base class explicitly, for instance:
class MyOtherClass(MyShowProto):
but note that this makes methods of the base class actually available on the subclass, and thus the static checker will not report that a method definition is missing on the MyOtherClass
.
So in this case, in order to get a useful type-checking, all the methods that we want to be explicitly implemented should be decorated with @abstractmethod
:
from typing import Protocol
from abc import abstractmethod
class MyShowProto(Protocol):
@abstractmethod
def show(self): raise NotImplementedError
class MyOtherClass(MyShowProto):
pass
MyOtherClass() # error in type checker
The Javascript interpreter natively stores objects in a hash table. If you're worried about contamination from the prototype chain, you can always do something like this:
// Simple ECMA5 hash table
Hash = function(oSource){
for(sKey in oSource) if(Object.prototype.hasOwnProperty.call(oSource, sKey)) this[sKey] = oSource[sKey];
};
Hash.prototype = Object.create(null);
var oHash = new Hash({foo: 'bar'});
oHash.foo === 'bar'; // true
oHash['foo'] === 'bar'; // true
oHash['meow'] = 'another prop'; // true
oHash.hasOwnProperty === undefined; // true
Object.keys(oHash); // ['foo', 'meow']
oHash instanceof Hash; // true
CASE case_value
WHEN when_value THEN statements
[WHEN when_value THEN statements]
ELSE statements
END
Or:
CASE
WHEN <search_condition> THEN statements
[WHEN <search_condition> THEN statements]
ELSE statements
END
here CASE is an expression in 2nd scenario search_condition will evaluate and if no search_condition is equal then execute else
SELECT
CASE course_enrollment_settings.base_price
WHEN course_enrollment_settings.base_price = 0 THEN 1
should be
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
for me i solved it like the following In Visual Studio 2015 : From View menu click Other Windows then click Package Manager Console then run the following commands :
PM> enable-migrations
Migrations have already been enabled in project 'mvcproject'. To overwrite the existing migrations configuration, use the -Force parameter.
PM> enable-migrations -Force
Checking if the context targets an existing database... Code First Migrations enabled for project mvcproject.
then add the migration name under the migration folder it will add the class you need in Solution Explorer by run the following command
PM>Add-migration AddColumnUser
Finally update the database
PM> update-database
You can solve this by having a long stripe that you show in steps, like a filmstrip. Then you can stop the film on any frame. Example below (fiddle available at http://jsfiddle.net/HPXq4/9/):
the markup:
<div class="thumbnail-wrapper">
<img src="blah.jpg">
</div>
the css:
.thumbnail-wrapper{
width:190px;
height:100px;
overflow:hidden;
position:absolute;
}
.thumbnail-wrapper img{
position:relative;
top:0;
}
the js:
var gifTimer;
var currentGifId=null;
var step = 100; //height of a thumbnail
$('.thumbnail-wrapper img').hover(
function(){
currentGifId = $(this)
gifTimer = setInterval(playGif,500);
},
function(){
clearInterval(gifTimer);
currentGifId=null;
}
);
var playGif = function(){
var top = parseInt(currentGifId.css('top'))-step;
var max = currentGifId.height();
console.log(top,max)
if(max+top<=0){
console.log('reset')
top=0;
}
currentGifId.css('top',top);
}
obviously, this can be optimized much further, but I simplified this example for readability
Similar to one of the answers above, but try adding .sort_values()
to your .groupby()
will allow you to change the sort order. If you need to sort on a single column, it would look like this:
df.groupby('group')['id'].count().sort_values(ascending=False)
ascending=False
will sort from high to low, the default is to sort from low to high.
*Careful with some of these aggregations. For example .size() and .count() return different values since .size() counts NaNs.
Sort the array just as before, but print the elements out in reverse order, using a loop that counts down rather than counting up.
Also, move the sort out of the loop - you are currently sorting the array over and over again when you only need to sort it once.
Arrays.sort(arr);
for(int i = 0; i < arr.length; i++){
//Arrays.sort(arr); // not here
System.out.print( " " +arr[i]);
}
for(int i = arr.length-1; i >= 0; i--){
//Arrays.sort(arr); // not here
System.out.print( " " +arr[i]);
}
Okay, everyone here as a different opinion as to the tradeoffs and advantages of xrange versus range. They're mostly correct, xrange is an iterator, and range fleshes out and creates an actual list. For the majority of cases, you won't really notice a difference between the two. (You can use map with range but not with xrange, but it uses up more memory.)
What I think you rally want to hear, however, is that the preferred choice is xrange. Since range in Python 3 is an iterator, the code conversion tool 2to3 will correctly convert all uses of xrange to range, and will throw out an error or warning for uses of range. If you want to be sure to easily convert your code in the future, you'll use xrange only, and list(xrange) when you're sure that you want a list. I learned this during the CPython sprint at PyCon this year (2008) in Chicago.
change 80 to 81 and 443 to 444 by clicking config button and editing httpd.conf and httpd-ssl.congf. Now you can Access XAMPP from 127.0.0.1:81
I used zxing-1.3 jar and I had to make some changes implementing code from other answers, so I will leave my solution for others. I did the following:
1) find zxing-1.3.jar, download it and add in properties (add external jar).
2) in my activity layout add ImageView and name it (in my example it was tnsd_iv_qr).
3) include code in my activity to create qr image (in this example I was creating QR for bitcoin payments):
QRCodeWriter writer = new QRCodeWriter();
ImageView tnsd_iv_qr = (ImageView)findViewById(R.id.tnsd_iv_qr);
try {
ByteMatrix bitMatrix = writer.encode("bitcoin:"+btc_acc_adress+"?amount="+amountBTC, BarcodeFormat.QR_CODE, 512, 512);
int width = 512;
int height = 512;
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
if (bitMatrix.get(x, y)==0)
bmp.setPixel(x, y, Color.BLACK);
else
bmp.setPixel(x, y, Color.WHITE);
}
}
tnsd_iv_qr.setImageBitmap(bmp);
} catch (WriterException e) {
//Log.e("QR ERROR", ""+e);
}
If someone is wondering, variable "btc_acc_adress" is a String (with BTC adress), amountBTC is a double, with, of course, transaction amount.
There is no automated uninstaller.
You have to remove Eclipse manually. At least Eclipse does not write anything in the system registry, so deleting some directories and files is enough.
Note: I use Unix style paths in this answer but the locations should be the same on Windows or Unix systems, so ~
refers to the user home directory even on Windows.
According to this discussion about uninstalling Eclipse, the reasoning for not providing an uninstaller is that the Eclipse installer is supposed to just automate a few tasks that in the past had to be done manually (like downloading and extracting Eclipse and adding shortcuts), so they also can be undone manually. There is no entry in "Programs and Features" because the installer does not register anything in the system registry.
Just delete the Eclipse directory and any desktop and start menu shortcuts and be done with it, if you don't mind a few leftover files.
In my opinion this is generally enough and I would stop here, because multiple Eclipse installations can share some files and you don't accidentally want to delete those shared files. You also keep all your projects.
If you really want to remove Eclipse without leaving any traces, you have to manually delete
~/eclipse/photon/
)The installer has a "Bundle Pools" menu entry which lists the locations of all bundle pools. If you have other Eclipse installations on your system you can use the "Cleanup Agent" to clean up unused bundles. If you don't have any other Eclipse installations you can delete the whole bundle pool directory instead (by default ~/p2/
).
If you want to completely remove the Eclipse installer too, delete the installer's executable and the ~/.eclipse/
directory.
Depending on what kind of work you did with Eclipse, there can be more directories that you may want to delete. If you used Maven, then ~/.m2/
contains the Maven cache and settings (shared with Maven CLI and other IDEs). If you develop Eclipse plugins, then there might be JUnit workspaces from test runs, next to you Eclipse workspace. Likewise other build tools and development environments used in Eclipse could have created similar directories.
If you want to delete your projects and workspace metadata, you have to delete your workspace(s). The default workspace location is ´~/workspace/´. You can also search for the .metadata
directory to get all Eclipse workspaces on your machine.
If you are working with Git projects, these are generally not saved in the workspace but in the ~/git/
directory.
Following example php script can help you to optimize all tables in your database
<?php
dbConnect();
$alltables = mysql_query("SHOW TABLES");
while ($table = mysql_fetch_assoc($alltables))
{
foreach ($table as $db => $tablename)
{
mysql_query("OPTIMIZE TABLE '".$tablename."'")
or die(mysql_error());
}
}
?>
The correct config key is retention.ms
$ bin/kafka-topics.sh --zookeeper zk.prod.yoursite.com --alter --topic as-access --config retention.ms=86400000
Updated config for topic "my-topic".
Get your scrolling feature easily. It also supports Animated/Smooth scrolling as an additional feature. Details for Angular Scroll library:
Github - https://github.com/oblador/angular-scroll
Bower: bower install --save angular-scroll
npm : npm install --save angular-scroll
Minfied version - only 9kb
Smooth Scrolling (animated scrolling) - yes
Scroll Spy - yes
Documentation - excellent
Demo - http://oblador.github.io/angular-scroll/
Hope this helps.
This can be something to start with:
import configparser
config = configparser.ConfigParser()
config.read('FILE.INI')
print(config['DEFAULT']['path']) # -> "/path/name/"
config['DEFAULT']['path'] = '/var/shared/' # update
config['DEFAULT']['default_message'] = 'Hey! help me!!' # create
with open('FILE.INI', 'w') as configfile: # save
config.write(configfile)
You can find more at the official configparser documentation.
Make sure, that all of your class methods (updateVelocity
, updatePosition
, ...) take at least one positional argument, which is canonically named self
and refers to the current instance of the class.
When you call particle.updateVelocity()
, the called method implicitly gets an argument: the instance, here particle
as first parameter.
Declare two export inside your .bashrc or .zshrc:
export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_11_HOME=$(/usr/libexec/java_home -v11)
Add alias for quick change:
alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java11='export JAVA_HOME=$JAVA_11_HOME'
set default to Java 11
java11
export PATH
export PATH=$JAVA_HOME/bin:$PATH
you could change java11 by java8 inside your .bashrc/zshrc file to change permanently your java version
On Windows, it's native with Win32 api...
__repr__
is used by the standalone Python interpreter to display a class in printable format. Example:
~> python3.5
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class StackOverflowDemo:
... def __init__(self):
... pass
... def __repr__(self):
... return '<StackOverflow demo object __repr__>'
...
>>> demo = StackOverflowDemo()
>>> demo
<StackOverflow demo object __repr__>
In cases where a __str__
method is not defined in the class, it will call the __repr__
function in an attempt to create a printable representation.
>>> str(demo)
'<StackOverflow demo object __repr__>'
Additionally, print()
ing the class will call __str__
by default.
Documentation, if you please
image: reporting services line chart horizontal axis properties
To see all dates on the report; Set Axis Type to Scalar, Set Interval to 1 -Jump Labels section Set disable auto-fit set label rotation angle as you desire.
These would help.
<script type="text/javascript">
$("a.more").fancybox({
'titleShow' : false,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
'type' : 'swf',
'swf' : {'wmode':'transparent','allowfullscreen':'true'}
});
</script>
This way if the user javascript is enabled it opens a fancybox with the youtube embed video, if javascript is disabled it opens the video's youtube page. If you want you can add
target="_blank"
to each of your links, it won't validate on most doctypes, but it will open the link in a new window if fancybox doesn't pick it up.
this
, above, isn't referenced correctly, so the code won't find href
under this
. You have to call it like this:
$("a.more").click(function() {
$.fancybox({
'padding' : 0,
'autoScale' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'title' : this.title,
'width' : 680,
'height' : 495,
'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
'type' : 'swf',
'swf' : {
'wmode' : 'transparent',
'allowfullscreen' : 'true'
}
});
return false;
});
as covered at http://fancybox.net/blog #4, replicated above
No, there isn't.
You could use Thread.Sleep()
function, e.g.
int milliseconds = 2000;
Thread.Sleep(milliseconds);
that completely stops the execution of the current thread for 2 seconds.
Probably the most appropriate scenario for Thread.Sleep
is when you want to delay the operations in another thread, different from the main e.g. :
MAIN THREAD --------------------------------------------------------->
(UI, CONSOLE ETC.) | |
| |
OTHER THREAD ----- ADD A DELAY (Thread.Sleep) ------>
For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.
I had originally decided to use a static field in my API class to reference an instance of MyDataContext object (Where MyDataContext is an EF5 Context object), but that is what seemed to create the problem. I added code something like the following to every one of my API methods and that fixed the problem.
using(MyDBContext db = new MyDBContext())
{
//Do some linq queries
}
As other people have stated, the EF Data Context objects are NOT thread safe. So placing them in the static object will eventually cause the "data reader" error under the right conditions.
My original assumption was that creating only one instance of the object would be more efficient, and afford better memory management. From what I have gathered researching this issue, that is not the case. In fact, it seems to be more efficient to treat each call to your API as an isolated, thread safe event. Ensuring that all resources are properly released, as the object goes out of scope.
This makes sense especially if you take your API to the next natural progression which would be to expose it as a WebService or REST API.
Disclosure
Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
You can't combine a character string and numeric string. You need to convert the number to a string using either CONVERT or CAST.
For example:
print 'There are ' + cast(@Number as varchar) + ' alias combinations did not match a record'
or
print 'There are ' + convert(varchar,@Number) + ' alias combinations did not match a record'
It's a quote issue, you need :
projectID=$(
cat file.json | jq -r ".resource[] | select(.username=='$EMAILID') | .id"
)
If you put single quotes to delimit the main string, the shell takes $EMAILID
literally.
"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var"
, "$(command "$var")"
, "${array[@]}"
, "a & b"
. Use 'single quotes'
for code or literal $'s: 'Costs $5 US'
, ssh host 'echo "$HOSTNAME"'
. See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words
I think in certain cases, you can create a FAKE "list" of items in the database, for example, the merchandise has a few pictures to show its details, you can concatenate all the IDs of pictures split by comma and store the string into the DB, then you just need to parse the string when you need it. I am working on a website now and I am planning to use this way.
Something like this should work:
var dropdown = document.getElementById("dropdown1");
if (dropdown) {
for (var i=0; i < month.length;++i){
addOption(dropdown, month[i], month[i]);
}
}
addOption = function(selectbox, text, value) {
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
You can refer to this article for more details:
http://www.plus2net.com/javascript_tutorial/list-adding.php
In View Replace this:
@Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
With:
@if(@Model.AuditDate.Value != null){@Model.AuditDate.Value.ToString("dd/MM/yyyy")}
else {@Html.DisplayFor(Model => Model.AuditDate)}
Explanation: If the AuditDate value is not null then it will format the date to dd/MM/yyyy, otherwise leave it as it is because it has no value.
Future.delayed(Duration(seconds: 3) , your_function)
Use:
if (function_exists('curl_file_create')) { // php 5.5+
$cFile = curl_file_create($file_name_with_full_path);
} else { //
$cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);
You can also refer:
http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/
Important hint for PHP 5.5+:
Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
SELECT * FROM table WHERE field1 NOT LIKE '%$x%';
(Make sure you escape $x properly beforehand to avoid SQL injection)
Edit: NOT IN
does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%'
can use an index. LIKE '%xxx'
or LIKE '%xxx%'
can't.
SELECT * FROM MyTable WHERE
Column1 LIKE '%word1%'
AND Column1 LIKE '%word2%'
AND Column1 LIKE '%word3%'
Changed OR
to AND
based on edit to question.
Yes, but it's clunky as hell, e.g.
<c:choose>
<c:when test="${condition1}">
...
</c:when>
<c:when test="${condition2}">
...
</c:when>
<c:otherwise>
...
</c:otherwise>
</c:choose>
According to this: http://www.vistax64.com/vista-installation-setup/33219-regsvr32-error-0x80004005.html
Run it in a elevated command prompt.
public string HtmlAgi(string url, string key)
{
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
HtmlNode ourNode = doc.DocumentNode.SelectSingleNode(string.Format("//meta[@name='{0}']", key));
if (ourNode != null)
{
return ourNode.GetAttributeValue("content", "");
}
else
{
return "not fount";
}
}
File myFile=new File("/tmp/myfile");
URL myUrl = myFile.toURI().toURL();
You probably don't have the System.Configuration dll added to the project references. It is not there by default, and you have to add it manually.
Right-click on the References and search for System.Configuration in the .net assemblies.
Check to see if it is in your references...
Right-click and select Add Reference...
Find System.Configuration in the list of .Net Assemblies, select it, and click Ok...
The assembly should now appear in your references...
This post is already a year old... but, I really, really like the ES6 @dzuc answer. However it is incomplete by not been able to handle multiple selects or checkboxes. This has already pointed and code solutions has been offered. I find them heavy and not optimized. So I wrote a 2 versions based on @dzuc to handle these cases:
let r=Array.from(fd).reduce(
(o , [k,v]) => (
(!o[k])
? {...o , [k] : v}
: {...o , [k] : [...o[k] , v]}
)
,{}
);
let obj=JSON.stringify(r);
One line Hotshot version:
Array.from(fd).reduce((o,[k,v])=>((!o[k])?{...o,[k]:v}:{...o,[k]:[...o[k],v]}),{});
[]
suffix.let r=Array.from(fd).reduce(
(o , [k,v]) => (
(k.split('[').length>1)
? (k=k.split('[')[0]
, (!o[k])
? {...o , [k] : [v]}
: {...o , [k] : [...o[k] , v ]}
)
: {...o , [k] : v}
)
,{}
);
let obj=JSON.stringify(r);
One line Hotshot version:
Array.from(fd).reduce((o,[k,v])=>((k.split('[').length>1)?(k=k.split('[')[0],(!o[k])?{...o,[k]:[v]}:{...o,[k]:[...o[k],v]}):{...o,[k]:v}),{});
Since last time I wrote the previous second case, at work it came a case that the PHP form has checkboxes on multi-levels. I wrote a new case to support previous case and this one. I created a snippet to better showcase this case, the result show on the console for this demo, modify this to your need. Tried to optimize it the best I could without compromising performance, however, it compromise some human readability. It takes advantage that arrays are objects and variables pointing to arrays are kept as reference. No hotshot for this one, be my guest.
let nosubmit = (e) => {_x000D_
e.preventDefault();_x000D_
const f = Array.from(new FormData(e.target));_x000D_
const obj = f.reduce((o, [k, v]) => {_x000D_
let a = v,_x000D_
b, i,_x000D_
m = k.split('['),_x000D_
n = m[0],_x000D_
l = m.length;_x000D_
if (l > 1) {_x000D_
a = b = o[n] || [];_x000D_
for (i = 1; i < l; i++) {_x000D_
m[i] = (m[i].split(']')[0] || b.length) * 1;_x000D_
b = b[m[i]] = ((i + 1) == l) ? v : b[m[i]] || [];_x000D_
}_x000D_
}_x000D_
return { ...o, [n]: a };_x000D_
}, {});_x000D_
console.log(obj);_x000D_
}_x000D_
document.querySelector('#theform').addEventListener('submit', nosubmit, {capture: true});
_x000D_
<h1>Multilevel Form</h1>_x000D_
<form action="#" method="POST" enctype="multipart/form-data" id="theform">_x000D_
<input type="hidden" name="_id" value="93242" />_x000D_
<input type="hidden" name="_fid" value="45c0ec96929bc0d39a904ab5c7af70ef" />_x000D_
<label>Select:_x000D_
<select name="uselect">_x000D_
<option value="A">A</option>_x000D_
<option value="B">B</option>_x000D_
<option value="C">C</option>_x000D_
</select>_x000D_
</label>_x000D_
<br /><br />_x000D_
<label>Checkboxes one level:<br/>_x000D_
<input name="c1[]" type="checkbox" checked value="1"/>v1 _x000D_
<input name="c1[]" type="checkbox" checked value="2"/>v2_x000D_
<input name="c1[]" type="checkbox" checked value="3"/>v3_x000D_
</label>_x000D_
<br /><br />_x000D_
<label>Checkboxes two levels:<br/>_x000D_
<input name="c2[0][]" type="checkbox" checked value="4"/>0 v4 _x000D_
<input name="c2[0][]" type="checkbox" checked value="5"/>0 v5_x000D_
<input name="c2[0][]" type="checkbox" checked value="6"/>0 v6_x000D_
<br/>_x000D_
<input name="c2[1][]" type="checkbox" checked value="7"/>1 v7 _x000D_
<input name="c2[1][]" type="checkbox" checked value="8"/>1 v8_x000D_
<input name="c2[1][]" type="checkbox" checked value="9"/>1 v9_x000D_
</label>_x000D_
<br /><br />_x000D_
<label>Radios:_x000D_
<input type="radio" name="uradio" value="yes">YES_x000D_
<input type="radio" name="uradio" checked value="no">NO_x000D_
</label>_x000D_
<br /><br />_x000D_
<input type="submit" value="Submit" />_x000D_
</form>
_x000D_
Just add 0 before the permission number:
For example - we want to give all permissions - 777
Syntax: os.chmod("file_name" , permission)
import os
os.chmod("file_name" , 0777)
Python version 3.7 does not support this syntax. It requires '0o' prefix for octal literals - this is the comment I have got in PyCharm
So for python 3.7, it will be
import os
os.chmod("file_name" , 0o777)
I just made a class to handle this with Generics, so it can be used with all the object types that are serializable:
public class SerializableManager {
/**
* Saves a serializable object.
*
* @param context The application context.
* @param objectToSave The object to save.
* @param fileName The name of the file.
* @param <T> The type of the object.
*/
public static <T extends Serializable> void saveSerializable(Context context, T objectToSave, String fileName) {
try {
FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(objectToSave);
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Loads a serializable object.
*
* @param context The application context.
* @param fileName The filename.
* @param <T> The object type.
*
* @return the serializable object.
*/
public static<T extends Serializable> T readSerializable(Context context, String fileName) {
T objectToReturn = null;
try {
FileInputStream fileInputStream = context.openFileInput(fileName);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
objectToReturn = (T) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return objectToReturn;
}
/**
* Removes a specified file.
*
* @param context The application context.
* @param filename The name of the file.
*/
public static void removeSerializable(Context context, String filename) {
context.deleteFile(filename);
}
}
To expand on Bartho Bernsmann's answer, I should like to add that one can have a universal, future-proof implementation at the expense of a little reflection:
static void AllowAllSecurityPrototols()
{ int i, n;
Array types;
SecurityProtocolType combined;
types = Enum.GetValues( typeof( SecurityProtocolType ) );
combined = ( SecurityProtocolType )types.GetValue( 0 );
n = types.Length;
for( i = 1; i < n; i += 1 )
{ combined |= ( SecurityProtocolType )types.GetValue( i ); }
ServicePointManager.SecurityProtocol = combined;
}
I invoke this method in the static constructor of the class that accesses the internet.
I would just like to add, that simply closing and reopening eclipse has always worked for me with this type of error.
From http://vyaskn.tripod.com/programming_faq.htm#q17:
Oracle has a rownum to access rows of a table using row number or row id. Is there any equivalent for that in SQL Server? Or how to generate output with row number in SQL Server?
There is no direct equivalent to Oracle's rownum or row id in SQL Server. Strictly speaking, in a relational database, rows within a table are not ordered and a row id won't really make sense. But if you need that functionality, consider the following three alternatives:
Add an
IDENTITY
column to your table.Use the following query to generate a row number for each row. The following query generates a row number for each row in the authors table of pubs database. For this query to work, the table must have a unique key.
SELECT (SELECT COUNT(i.au_id) FROM pubs..authors i WHERE i.au_id >= o.au_id ) AS RowID, au_fname + ' ' + au_lname AS 'Author name' FROM pubs..authors o ORDER BY RowID
Use a temporary table approach, to store the entire resultset into a temporary table, along with a row id generated by the
IDENTITY()
function. Creating a temporary table will be costly, especially when you are working with large tables. Go for this approach, if you don't have a unique key in your table.