The service cannot be started, either because it is disabled or because it has no enabled devices associated with it
This error can occur on anything that requires elevated privileges in Windows.
It happens when the "Application Information" service is disabled in Windows services. There are a few viruses that use this as an attack vector to prevent people from removing the virus. It also prevents people from installing software to remove viruses.
The normal way to fix this would be to run services.msc, or to go into Administrative Tools and run "Services". However, you will not be able to do that if the "Application Information" service is disabled.
Instead, reboot your computer into Safe Mode (reboot and press F8 until the Windows boot menu appears, select Safe Mode with Networking). Then run services.msc and look for services that are designated as "Disabled" in the Startup Type column. Change these "Disabled" services to "Automatic".
Make sure the "Application Information" service is set to a Startup Type of "Automatic".
When you are done enabling your services, click Ok at the bottom of the tool and reboot your computer back into normal mode. The problem should be resolved when Windows reboots.
Check if table exists and if it doesn't exist, create it in SQL Server 2008
Just for contrast, I like using the object_id function as shown below. It's a bit easier to read, and you don't have to worry about sys.objects vs. sysobjects vs. sys.all_objects
vs. sys.tables. Basic form:
IF object_id('MyTable') is not null
PRINT 'Present!'
ELSE
PRINT 'Not accounted for'
Of course this will show as "Present" if there is any object present with that name. If you want to check just tables, you'd need:
IF object_id('MyTable', 'U') is not null
PRINT 'Present!'
ELSE
PRINT 'Not accounted for'
It works for temp tables as well:
IF object_id('tempdb.dbo.#MyTable') is not null
PRINT 'Present!'
ELSE
PRINT 'Not accounted for'
Conversion failed when converting date and/or time from character string in SQL SERVER 2008
Seems like last_accessed_on, is a date time, and you are converting '23-07-2014 09:37:00' to a varchar. This would not work, and give you conversion errors. Try
last_accessed_on= convert(datetime,'23-07-2014 09:37:00', 103)
I think you can avoid the cast though, and update with '23-07-2014 09:37:00'. It should work given that the format is correct.
Your query is not going to work because in last_accessed_on (which is DateTime2 type), you are trying to pass a Varchar value.
You query would be
UPDATE student_queues SET Deleted=0 , last_accessed_by='raja', last_accessed_on=convert(datetime,'23-07-2014 09:37:00', 103)
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
How to query for Xml values and attributes from table in SQL Server?
Actually you're close to your goal, you just need to use nodes() method to split your rows and then get values:
select
s.SqmId,
m.c.value('@id', 'varchar(max)') as id,
m.c.value('@type', 'varchar(max)') as type,
m.c.value('@unit', 'varchar(max)') as unit,
m.c.value('@sum', 'varchar(max)') as [sum],
m.c.value('@count', 'varchar(max)') as [count],
m.c.value('@minValue', 'varchar(max)') as minValue,
m.c.value('@maxValue', 'varchar(max)') as maxValue,
m.c.value('.', 'nvarchar(max)') as Value,
m.c.value('(text())[1]', 'nvarchar(max)') as Value2
from sqm as s
outer apply s.data.nodes('Sqm/Metrics/Metric') as m(c)
sql fiddle demo
Convert NVARCHAR to DATETIME in SQL Server 2008
As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)
| YOUR_DT | SQL2008 |
|-----------------------------|---------------------|
| 2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
| 2013-08-29 13:55:48 blah | (null) |
| 2013-08-29 13:55:48 rubbish | (null) |
SELECT
[Your_Dt]
, convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
FROM your_table
CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
THEN convert(datetime,[Your_Dt])
ELSE NULL
END
) AS ca1 (dt_converted)
;
Notes:
You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'
For that specific output I think you will need 2 sql 2008 date styles (105 & 8)
sql2012 added for comparison
declare @your_dt as datetime2
set @your_dt = '2013-08-29 13:55:48'
select
FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
, convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008
| SQL2012 | SQL2008 |
|---------------------|---------------------|
| 29-08-2013 13:55:48 | 29-08-2013 13:55:48 |
Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)
USE MASTER
GO
DECLARE @Spid INT
DECLARE @ExecSQL VARCHAR(255)
DECLARE KillCursor CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT DISTINCT SPID
FROM MASTER..SysProcesses
WHERE DBID = DB_ID('dbname')
OPEN KillCursor
-- Grab the first SPID
FETCH NEXT
FROM KillCursor
INTO @Spid
WHILE @@FETCH_STATUS = 0
BEGIN
SET @ExecSQL = 'KILL ' + CAST(@Spid AS VARCHAR(50))
EXEC (@ExecSQL)
-- Pull the next SPID
FETCH NEXT
FROM KillCursor
INTO @Spid
END
CLOSE KillCursor
DEALLOCATE KillCursor
Search of table names
I know this is an old thread, but if you prefer case-insensitive searching:
SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE Lower(TABLE_NAME) LIKE Lower('%%')
Calculating distance between two points (Latitude, Longitude)
The below function gives distance between two geocoordinates in miles
create function [dbo].[fnCalcDistanceMiles] (@Lat1 decimal(8,4), @Long1 decimal(8,4), @Lat2 decimal(8,4), @Long2 decimal(8,4))
returns decimal (8,4) as
begin
declare @d decimal(28,10)
-- Convert to radians
set @Lat1 = @Lat1 / 57.2958
set @Long1 = @Long1 / 57.2958
set @Lat2 = @Lat2 / 57.2958
set @Long2 = @Long2 / 57.2958
-- Calc distance
set @d = (Sin(@Lat1) * Sin(@Lat2)) + (Cos(@Lat1) * Cos(@Lat2) * Cos(@Long2 - @Long1))
-- Convert to miles
if @d <> 0
begin
set @d = 3958.75 * Atan(Sqrt(1 - power(@d, 2)) / @d);
end
return @d
end
The below function gives distance between two geocoordinates in kilometres
CREATE FUNCTION dbo.fnCalcDistanceKM(@lat1 FLOAT, @lat2 FLOAT, @lon1 FLOAT, @lon2 FLOAT)
RETURNS FLOAT
AS
BEGIN
RETURN ACOS(SIN(PI()*@lat1/180.0)*SIN(PI()*@lat2/180.0)+COS(PI()*@lat1/180.0)*COS(PI()*@lat2/180.0)*COS(PI()*@lon2/180.0-PI()*@lon1/180.0))*6371
END
The below function gives distance between two geocoordinates in kilometres
using Geography data type which was introduced in sql server 2008
DECLARE @g geography;
DECLARE @h geography;
SET @g = geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656)', 4326);
SET @h = geography::STGeomFromText('POINT(-122.34900 47.65100)', 4326);
SELECT @g.STDistance(@h);
Usage:
select [dbo].[fnCalcDistanceKM](13.077085,80.262675,13.065701,80.258916)
Reference: Ref1,Ref2
Select SQL Server database size
You can check how this query works following this link.
IF OBJECT_ID('tempdb..#spacetable') IS NOT NULL
DROP TABLE tempdb..#spacetable
create table #spacetable
(
database_name varchar(50) ,
total_size_data int,
space_util_data int,
space_data_left int,
percent_fill_data float,
total_size_data_log int,
space_util_log int,
space_log_left int,
percent_fill_log char(50),
[total db size] int,
[total size used] int,
[total size left] int
)
insert into #spacetable
EXECUTE master.sys.sp_MSforeachdb 'USE [?];
select x.[DATABASE NAME],x.[total size data],x.[space util],x.[total size data]-x.[space util] [space left data],
x.[percent fill],y.[total size log],y.[space util],
y.[total size log]-y.[space util] [space left log],y.[percent fill],
y.[total size log]+x.[total size data] ''total db size''
,x.[space util]+y.[space util] ''total size used'',
(y.[total size log]+x.[total size data])-(y.[space util]+x.[space util]) ''total size left''
from (select DB_NAME() ''DATABASE NAME'',
sum(size*8/1024) ''total size data'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
,case when sum(size*8/1024)=0 then ''divide by zero'' else
substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
from sys.master_files where database_id=DB_ID(DB_NAME()) and type=0
group by type_desc ) as x ,
(select
sum(size*8/1024) ''total size log'',sum(FILEPROPERTY(name,''SpaceUsed'')*8/1024) ''space util''
,case when sum(size*8/1024)=0 then ''divide by zero'' else
substring(cast((sum(FILEPROPERTY(name,''SpaceUsed''))*1.0*100/sum(size)) as CHAR(50)),1,6) end ''percent fill''
from sys.master_files where database_id=DB_ID(DB_NAME()) and type=1
group by type_desc )y'
select * from #spacetable
order by database_name
drop table #spacetable
SQL Server procedure declare a list
If you want input comma separated string as input & apply in in query in that then you can make Function like:
create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))
returns @temptable TABLE (items varchar(MAX))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end;
You can use it like :
Declare @Values VARCHAR(MAX);
set @Values ='1,2,5,7,10';
Select * from DBTable
Where id in (select items from [dbo].[Split] (@Values, ',') )
Alternatively if you don't have comma-separated string as input, You can try Table variable
OR TableType
Or Temp table
like: INSERT using LIST into Stored Procedure
Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0
I downloaded "Microsoft® System CLR Types for Microsoft® SQL Server® 2012" and "Microsoft® SQL Server® 2012 Shared Management Objects" from @ImanMahmoudinasab mentioned link, but Shared Management Objects had problem while installing and it showed some dependencies message and at the end installation Failed!
Finally I solved the problem with Power Shell. I run PS as administrator with the below command:
Start-Process <path>\SharedManagementObjects.msi
T-SQL split string based on delimiter
The examples above work fine when there is only one delimiter, but it doesn't scale well for multiple delimiters. Note that this will only work for SQL Server 2016 and above.
/*Some Sample Data*/
DECLARE @mytable TABLE ([id] VARCHAR(10), [name] VARCHAR(1000));
INSERT INTO @mytable
VALUES ('1','John/Smith'),('2','Jane/Doe'), ('3','Steve'), ('4','Bob/Johnson')
/*Split based on delimeter*/
SELECT P.id, [1] 'FirstName', [2] 'LastName', [3] 'Col3', [4] 'Col4'
FROM(
SELECT A.id, X1.VALUE, ROW_NUMBER() OVER (PARTITION BY A.id ORDER BY A.id) RN
FROM @mytable A
CROSS APPLY STRING_SPLIT(A.name, '/') X1
) A
PIVOT (MAX(A.[VALUE]) FOR A.RN IN ([1],[2],[3],[4],[5])) P
How do I find the data directory for a SQL Server instance?
Alex's answer is the right one, but for posterity here's another option: create a new empty database. If you use CREATE DATABASE without specifying a target dir you get... the default data / log directories. Easy.
Personally however I'd probably either:
- RESTORE the database to the developer's PC, rather than copy/attach (backups can be compressed, exposed on a UNC), or
- Use a linked server to avoid doing this in the first place (depends how much data goes over the join)
ps: 20gb is not huge, even in 2015. But it's all relative.
Rebuild all indexes in a Database
Try the following script:
Exec sp_msforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'
GO
Also
I prefer(After a long search) to use the following script, it contains @fillfactor
determines how much percentage of the space on each leaf-level page is filled with data.
DECLARE @TableName VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80
DECLARE TableCursor CURSOR FOR
SELECT QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))+'.' + QUOTENAME(name) AS TableName
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO
for more info, check the following link:
https://blog.sqlauthority.com/2009/01/30/sql-server-2008-2005-rebuild-every-index-of-all-tables-of-database-rebuild-index-with-fillfactor/
and if you want to Check Index Fragmentation on Indexes in a Database, try the following script:
SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID() AND dbtables.[name] like '%%'
ORDER BY indexstats.avg_fragmentation_in_percent desc
For more information, Check the following link:
http://www.schneider-electric.com/en/faqs/FA234246/
Partition Function COUNT() OVER possible using DISTINCT
Necromancing:
It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:
;WITH baseTable AS
(
SELECT 'RM1' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr
FROM baseTable
)
SELECT
RM
,ADR
,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1
,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2
-- Not supported
--,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu
FROM CTE
Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.
Using the "With Clause" SQL Server 2008
Just a poke, but here's another way to write FizzBuzz :)
100 rows is enough to show the WITH statement, I reckon.
;WITH t100 AS (
SELECT n=number
FROM master..spt_values
WHERE type='P' and number between 1 and 100
)
SELECT
ISNULL(NULLIF(
CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END +
CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3))
FROM t100
But the real power behind WITH (known as Common Table Expression http://msdn.microsoft.com/en-us/library/ms190766.aspx "CTE") in SQL Server 2005 and above is the Recursion, as below where the table is built up through iterations adding to the virtual-table each time.
;WITH t100 AS (
SELECT n=1
union all
SELECT n+1
FROM t100
WHERE n < 100
)
SELECT
ISNULL(NULLIF(
CASE WHEN n % 3 = 0 THEN 'Fizz' Else '' END +
CASE WHEN n % 5 = 0 THEN 'Buzz' Else '' END, ''), RIGHT(n,3))
FROM t100
To run a similar query in all database, you can use the undocumented sp_msforeachdb. It has been mentioned in another answer, but it is sp_msforeachdb, not sp_foreachdb.
Be careful when using it though, as some things are not what you expect. Consider this example
exec sp_msforeachdb 'select count(*) from sys.objects'
Instead of the counts of objects within each DB, you will get the SAME count reported, begin that of the current DB.
To get around this, always "use" the database first. Note the square brackets to qualify multi-word database names.
exec sp_msforeachdb 'use [?]; select count(*) from sys.objects'
For your specific query about populating a tally table, you can use something like the below. Not sure about the DATE column, so this tally table has only the DBNAME and IMG_COUNT columns, but hope it helps you.
create table #tbl (dbname sysname, img_count int);
exec sp_msforeachdb '
use [?];
if object_id(''tbldoc'') is not null
insert #tbl
select ''?'', count(*) from tbldoc'
select * from #tbl
Stored Procedure parameter default value - is this a constant or a variable
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
If has_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise, NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
Error: Specified cast is not valid. (SqlManagerUI)
Sometimes it happens because of the version change like store 2012 db on 2008, so how to check it?
RESTORE VERIFYONLY FROM DISK = N'd:\yourbackup.bak'
if it gives error like:
Msg 3241, Level 16, State 13, Line 2
The media family on device 'd:\alibaba.bak' is incorrectly formed. SQL Server cannot process this media family.
Msg 3013, Level 16, State 1, Line 2
VERIFY DATABASE is terminating abnormally.
Check it further:
RESTORE HEADERONLY FROM DISK = N'd:\yourbackup.bak'
BackupName is "* INCOMPLETE *",
Position is "1",
other fields are "NULL".
Means either your backup is corrupt or taken from newer version.
SQL Server 2008 R2 can't connect to local database in Management Studio
I also received this error when the service stopped. Here's another path to start your service...
- Search for "Services" in you start menu like so and click on it:
- Find the service for the instance you need started and select it
(shown below)
- Click start (shown below)
Note: As Kenan stated, if your services Startup Type is not set to Automatic, then you probably want to double click on the service and set it to Automatic.
SQL Update with row_number()
I did this for my situation and worked
WITH myUpdate (id, myRowNumber )
AS
(
SELECT id, ROW_NUMBER() over (order by ID) As myRowNumber
FROM AspNetUsers
WHERE UserType='Customer'
)
update AspNetUsers set EmployeeCode = FORMAT(myRowNumber,'00000#')
FROM myUpdate
left join AspNetUsers u on u.Id=myUpdate.id
Convert from DateTime to INT
Or, once it's already in SSIS, you could create a derived column (as part of some data flow task) with:
(DT_I8)FLOOR((DT_R8)systemDateTime)
But you'd have to test to doublecheck.
what is numeric(18, 0) in sql server 2008 r2
The first value is the precision and the second is the scale, so 18,0
is essentially 18 digits with 0 digits after the decimal place. If you had 18,2
for example, you would have 18 digits, two of which would come after the decimal...
example of 18,2: 1234567890123456.12
There is no functional difference between numeric
and decimal
, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
Select query to remove non-numeric characters
In case if there are some characters possible between digits (e.g. thousands separators), you may try following:
declare @table table (DirtyCol varchar(100))
insert into @table values
('AB ABCDE # 123')
,('ABCDE# 123')
,('AB: ABC# 123')
,('AB#')
,('AB # 1 000 000')
,('AB # 1`234`567')
,('AB # (9)(876)(543)')
;with tally as (select top (100) N=row_number() over (order by @@spid) from sys.all_columns),
data as (
select DirtyCol, Col
from @table
cross apply (
select (select C + ''
from (select N, substring(DirtyCol, N, 1) C from tally where N<=datalength(DirtyCol)) [1]
where C between '0' and '9'
order by N
for xml path(''))
) p (Col)
where p.Col is not NULL
)
select DirtyCol, cast(Col as int) IntCol
from data
Output is:
DirtyCol IntCol
--------------------- -------
AB ABCDE # 123 123
ABCDE# 123 123
AB: ABC# 123 123
AB # 1 000 000 1000000
AB # 1`234`567 1234567
AB # (9)(876)(543) 9876543
For update, add ColToUpdate
to select list of the data
cte:
;with num as (...),
data as (
select ColToUpdate, /*DirtyCol, */Col
from ...
)
update data
set ColToUpdate = cast(Col as int)
SQL Server stored procedure Nullable parameter
It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
Find Locked Table in SQL Server
You can use sp_lock
(and sp_lock2
), but in SQL Server 2005 onwards this is being deprecated in favour of querying sys.dm_tran_locks
:
select
object_name(p.object_id) as TableName,
resource_type, resource_description
from
sys.dm_tran_locks l
join sys.partitions p on l.resource_associated_entity_id = p.hobt_id
SQL Server - Create a copy of a database table and place it in the same database?
Use SELECT ... INTO
:
SELECT *
INTO ABC_1
FROM ABC;
This will create a new table ABC_1
that has the same column structure as ABC
and contains the same data. Constraints (e.g. keys, default values), however, are -not- copied.
You can run this query multiple times with a different table name each time.
If you don't need to copy the data, only to create a new empty table with the same column structure, add a WHERE
clause with a falsy expression:
SELECT *
INTO ABC_1
FROM ABC
WHERE 1 <> 1;
Get AVG ignoring Null or Zero values
You already attempt to filter out NULL
values with NOT NULL
. I have changed this to IS NOT NULL
in the WHERE
clause so it will execute. We can refactor this by removing the ISNULL
function in the AVG
method. Also, I doubt you'll actually need bigint
so we can remove the cast.
SELECT distinct
AVG(a.SecurityW) as Average1
,AVG(a.TransferW) as Average2
,AVG(a.StaffW) as Average3
FROM Table1 a, Table2 b
WHERE a.SecurityW <> 0 AND a.SecurityW IS NOT NULL
AND a.TransferW<> 0 AND a.TransferWIS IS NOT NULL
AND a.StaffW<> 0 AND a.StaffWIS IS NOT NULL
AND MONTH(a.ActualTime) = 4
AND YEAR(a.ActualTime) = 2013
fastest way to export blobs from table into individual files
For me what worked by combining all the posts I have read is:
1.Enable OLE automation - if not enabled
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
2.Create a folder where the generated files will be stored:
C:\GREGTESTING
3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
CREATE TABLE [dbo].[Document](
[Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Extension] [varchar](50) NULL,
[FileName] [varchar](200) NULL,
[Doc_Content] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)
Important note!
Don't forget to add in Doc_Content column the varbinary of file you want to generate!
4.Run the below script
DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max)
, @fPath varchar(max)
, @folderPath varchar(max)
--Get Data into temp Table variable so that we can iterate over it
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num] varchar(100) , [FileName] varchar(100), [Doc_Content] varBinary(max) )
INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM [dbo].[Document]
SELECT @i = COUNT(1) FROM @Doctable
WHILE @i >= 1
BEGIN
SELECT
@data = [Doc_Content],
@fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
@folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+ @fPath
--Reset the variables for next use
SELECT @data = NULL
, @init = NULL
, @fPath = NULL
, @folderPath = NULL
SET @i -= 1
END
5.The results is shown below:
How to automatically generate unique id in SQL like UID12345678?
The only viable solution in my opinion is to use
- an
ID INT IDENTITY(1,1)
column to get SQL Server to handle the automatic increment of your numeric value
- a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.tblUsers
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblUsers
without specifying values for ID
or UserID
:
INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID
value, and UserID
will contain values like UID00000001
, UID00000002
,...... and so on - automatically, safely, reliably, no duplicates.
Update: the column UserID
is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:
Convert YYYYMMDD to DATE
The error is happening because you (or whoever designed this table) have a bunch of dates in VARCHAR
. Why are you (or whoever designed this table) storing dates as strings? Do you (or whoever designed this table) also store salary and prices and distances as strings?
To find the values that are causing issues (so you (or whoever designed this table) can fix them):
SELECT GRADUATION_DATE FROM mydb
WHERE ISDATE(GRADUATION_DATE) = 0;
Bet you have at least one row. Fix those values, and then FIX THE TABLE. Or ask whoever designed the table to FIX THE TABLE. Really nicely.
ALTER TABLE mydb ALTER COLUMN GRADUATION_DATE DATE;
Now you don't have to worry about the formatting - you can always format as YYYYMMDD
or YYYY-MM-DD
on the client, or using CONVERT
in SQL. When you have a valid date as a string literal, you can use:
SELECT CONVERT(CHAR(10), '20120101', 120);
...but this is better done on the client (if at all).
There's a popular term - garbage in, garbage out. You're never going to be able to convert to a date (never mind convert to a string in a specific format) if your data type choice (or the data type choice of whoever designed the table) inherently allows garbage into your table. Please fix it. Or ask whoever designed the table (again, really nicely) to fix it.
Recover sa password
The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).
If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:
Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.
You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).
As an aside, the login properties for sa
would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.
I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM
account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):
And some other resources:
Create a view with ORDER BY clause
Just use TOP 100 Percent in the Select:
CREATE VIEW [schema].[VIEWNAME] (
[COLUMN1],
[COLUMN2],
[COLUMN3],
[COLUMN4])
AS
SELECT TOP 100 PERCENT
alias.[COLUMN1],
alias.[COLUMN2],
alias.[COLUMN3],
alias.[COLUMN4]
FROM
[schema].[TABLENAME] AS alias
ORDER BY alias.COLUMN1
GO
SQL Server 2008: How to query all databases sizes?
All this examples work fine on most of my database servers.
However if you have 1 server with multiple instances and all those servers those query's give you no result.
For instance the first query gives a result like:
name DataFileSizeMB LogFileSizeMB
master NULL NULL
tempdb NULL NULL
model NULL NULL
msdb NULL NULL
So the databases are selected from sys.databases
, however the table sys.master_files
seems to be empty or gives no result.
Even a simple query as select * from sys.master_files
has a result of 0 records.
You don't receive any errors but no records are found.
On my servers with only 1 database instance this works fine.
Exit single-user mode
Use this Script
exec sp_who
Find the dbname and spid column
now execute
kill spid
go
ALTER DATABASE [DBName]
SET MULTI_USER;
Find the last time table was updated
Why not just run this: No need for special permissions
SELECT
name,
object_id,
create_date,
modify_date
FROM
sys.tables
WHERE
name like '%yourTablePattern%'
ORDER BY
modify_date
Connection failed: SQLState: '01000' SQL Server Error: 10061
I had the same error which was coming and dont need to worry about this error, just restart the server and restart the SQL services. This issue comes when there is low disk space issue and system will go into hung state and then the sql services will stop automatically.
What is the syntax meaning of RAISERROR()
The severity level 16 in your example code is typically used for user-defined (user-detected) errors. The SQL Server DBMS itself emits severity levels (and error messages) for problems it detects, both more severe (higher numbers) and less so (lower numbers).
The state should be an integer between 0 and 255 (negative values will give an error), but the choice is basically the programmer's. It is useful to put different state values if the same error message for user-defined error will be raised in different locations, e.g. if the debugging/troubleshooting of problems will be assisted by having an extra indication of where the error occurred.
Error on renaming database in SQL Server 2008 R2
This did it for me:
USE [master];
GO
ALTER DATABASE [OldDataBaseName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
EXEC sp_renamedb N'OldDataBaseName', N'NewDataBaseName';
-- Add users again
ALTER DATABASE [NewDataBaseName] SET MULTI_USER
GO
How to find out what is locking my tables?
For getting straight to "who is blocked/blocking" I combined/abbreviated sp_who and sp_lock into a single query which gives a nice overview of who has what object locked to what level.
--Create Procedure WhoLock
--AS
set nocount on
if object_id('tempdb..#locksummary') is not null Drop table #locksummary
if object_id('tempdb..#lock') is not null Drop table #lock
create table #lock ( spid int, dbid int, objId int, indId int, Type char(4), resource nchar(32), Mode char(8), status char(6))
Insert into #lock exec sp_lock
if object_id('tempdb..#who') is not null Drop table #who
create table #who ( spid int, ecid int, status char(30),
loginame char(128), hostname char(128),
blk char(5), dbname char(128), cmd char(16)
--
, request_id INT --Needed for SQL 2008 onwards
--
)
Insert into #who exec sp_who
Print '-----------------------------------------'
Print 'Lock Summary for ' + @@servername + ' (excluding tempdb):'
Print '-----------------------------------------' + Char(10)
Select left(loginame, 28) as loginame,
left(db_name(dbid),128) as DB,
left(object_name(objID),30) as object,
max(mode) as [ToLevel],
Count(*) as [How Many],
Max(Case When mode= 'X' Then cmd Else null End) as [Xclusive lock for command],
l.spid, hostname
into #LockSummary
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and l.status='GRANT'
group by dbID, objID, l.spid, hostname, loginame
Select * from #LockSummary order by [ToLevel] Desc, [How Many] Desc, loginame, DB, object
Print '--------'
Print 'Who is blocking:'
Print '--------' + char(10)
SELECT p.spid
,convert(char(12), d.name) db_name
, program_name
, p.loginame
, convert(char(12), hostname) hostname
, cmd
, p.status
, p.blocked
, login_time
, last_batch
, p.spid
FROM master..sysprocesses p
JOIN master..sysdatabases d ON p.dbid = d.dbid
WHERE EXISTS ( SELECT 1
FROM master..sysprocesses p2
WHERE p2.blocked = p.spid )
Print '--------'
Print 'Details:'
Print '--------' + char(10)
Select left(loginame, 30) as loginame, l.spid,
left(db_name(dbid),15) as DB,
left(object_name(objID),40) as object,
mode ,
blk,
l.status
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and blk <>0
Order by mode desc, blk, loginame, dbID, objID, l.status
(For what the lock level abbreviations mean, see e.g. https://technet.microsoft.com/en-us/library/ms175519%28v=sql.105%29.aspx)
Copied from: sp_WhoLock – a T-SQL stored proc combining sp_who and sp_lock...
NB the [Xclusive lock for command] column can be misleading -- it shows the current command for that spid; but the X lock could have been triggered by an earlier command in the transaction.
How to commit and rollback transaction in sql server?
Don't use @@ERROR
, use BEGIN TRY/BEGIN CATCH
instead. See this article: Exception handling and nested transactions for a sample procedure:
create procedure [usp_my_procedure_name]
as
begin
set nocount on;
declare @trancount int;
set @trancount = @@trancount;
begin try
if @trancount = 0
begin transaction
else
save transaction usp_my_procedure_name;
-- Do the actual work here
lbexit:
if @trancount = 0
commit;
end try
begin catch
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback
if @xstate = 1 and @trancount > 0
rollback transaction usp_my_procedure_name;
raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
return;
end catch
end
How to redraw DataTable with new data
The following worked really well for me. I needed to redraw the datatable with a different subset of the data based on a parameter.
table.ajax.url('NewDataUrl?parameter=' + param).load();
If your data is static, then use this:
table.ajax.url('NewDataUrl').load();
How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?
This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.
var fs = require("fs");
var filename = "./index.html";
function start(resp) {
fs.readFile(filename, "utf8", function(err, data) {
if (err) {
// may be filename does not exists?
resp.writeHead(404, {
'Content-Type' : 'text/html'
});
// log this error into browser
resp.write(err.toString());
resp.end();
} else {
resp.writeHead(200, {
"Content-Type": "text/html"
});
resp.write(data.toString());
resp.end();
}
});
}
VBA equivalent to Excel's mod function
You want the mod operator.
The expression a Mod b is equivalent to the following formula:
a - (b * (a \ b))
Edited to add:
There are some special cases you may have to consider, because Excel is using floating point math (and returns a float
), which the VBA function returns an integer. Because of this, using mod
with floating-point numbers may require extra attention:
Excel's results may not correspond exactly with what you would predict; this is covered briefly here (see topmost answer) and at great length here.
As @André points out in the comments, negative numbers may round in the opposite direction from what you expect. The Fix()
function he suggests is explained here (MSDN).
Remote JMX connection
the thing that work for me was to set /etc/hosts to point the hostname to the ip and not to the loopback interface and than restart my application.
cat /etc/hosts
127.0.0.1 localhost.localdomain localhost
192.168.0.1 myservername
This is my configuration:
-Dcom.sun.management.jmxremote.port=1617
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
What is the volatile keyword useful for?
There are two different uses of volatile keyword.
- Prevents JVM from reading values from register (assume as cache), and forces its value to be read from memory.
- Reduces the risk of memory in-consistency errors.
Prevents JVM from reading values in register, and forces its
value to be read from memory.
A busy flag is used to prevent a thread from continuing while the device is busy and the flag is not protected by a lock:
while (busy) {
/* do something else */
}
The testing thread will continue when another thread turns off the busy flag:
busy = 0;
However, since busy is accessed frequently in the testing thread, the JVM may optimize the test by placing the value of busy in a register, then test the contents of the register without reading the value of busy in memory before every test. The testing thread would never see busy change and the other thread would only change the value of busy in memory, resulting in deadlock. Declaring the busy flag as volatile forces its value to be read before each test.
Reduces the risk of memory consistency errors.
Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a
"happens-before" relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.
The technique of reading, writing without memory consistency errors is called atomic action.
An atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete.
Below are actions you can specify that are atomic:
- Reads and writes are atomic for reference variables and for most
primitive variables (all types except long and double).
- Reads and writes are atomic for all variables declared volatile
(including long and double variables).
Cheers!
jQuery issue in Internet Explorer 8
Correction:
Check your script include tag, is it using
type="application/javascript" src="/path/to/jquery"
change to
type="text/javascript" src="/path/to/jquery"
How to determine an object's class?
checking with isinstance()
would not be enough if you want to know in run time.
use:
if(someObject.getClass().equals(C.class){
// do something
}
Configure active profile in SpringBoot via Maven
In development, activating a Spring Boot profile when a specific Maven profile is activate is straight. You should use the profiles
property of the spring-boot-maven-plugin in the Maven profile such as :
<project>
<...>
<profiles>
<profile>
<id>development</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<profiles>
<profile>development</profile>
</profiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profiles>
</...>
</project>
You can run the following command to use both the Spring Boot and the Maven development
profile :
mvn spring-boot:run -Pdevelopment
If you want to be able to map any Spring Boot profiles to a Maven profile with the same profile name, you could define a single Maven profile and enabling that as the presence of a Maven property is detected. This property would be the single thing that you need to specify as you run the mvn
command.
The profile would look like :
<profile>
<id>spring-profile-active</id>
<activation>
<property>
<name>my.active.spring.profiles</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<profiles>
<profile>${my.active.spring.profiles}</profile>
</profiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
And you can run the following command to use both the Spring Boot and the Maven development
profile :
mvn spring-boot:run -Dmy.active.spring.profiles=development
or :
mvn spring-boot:run -Dmy.active.spring.profiles=integration
or :
mvn spring-boot:run -Dmy.active.spring.profiles=production
And so for...
This kind of configuration makes sense as in the generic Maven profile you rely on the my.active.spring.profiles
property that is passed to perform some tasks or value some things.
For example I use this way to configure a generic Maven profile that packages the application and build a docker image specific to the environment selected.
How to lazy load images in ListView in Android
Well, image loading time from the Internet has many solutions. You may also use the library Android-Query. It will give you all the required activity. Make sure what you want to do and read the library wiki page. And solve the image loading restriction.
This is my code:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
ImageView imageview = (ImageView) v.findViewById(R.id.icon);
AQuery aq = new AQuery(convertView);
String imageUrl = "http://www.vikispot.com/z/images/vikispot/android-w.png";
aq.id(imageview).progress(this).image(imageUrl, true, true, 0, 0, new BitmapAjaxCallback() {
@Override
public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status) {
iv.setImageBitmap(bm);
}
));
return v;
}
It should be solve your lazy loading problem.
How can I update NodeJS and NPM to the next versions?
First update npm
,
npm install -g npm@next
Then update node
to the next version,
npm install -g node@next
or npm install -g n@next
or, to the latest,
npm install -g node@latest
or npm install -g node
check after version installation,
node --version
or node -v
Losing Session State
In my case setting AppPool->AdvancedSettings->Maximum Worker Proccesses to 1 helped.
Int to byte array
Most of the answers here are either 'UnSafe" or not LittleEndian safe. BitConverter is not LittleEndian safe.
So building on an example in here (see the post by PZahra) I made a LittleEndian safe version simply by reading the byte array in reverse when BitConverter.IsLittleEndian == true
void Main(){
Console.WriteLine(BitConverter.IsLittleEndian);
byte[] bytes = BitConverter.GetBytes(0xdcbaabcdfffe1608);
//Console.WriteLine(bytes);
string hexStr = ByteArrayToHex(bytes);
Console.WriteLine(hexStr);
}
public static string ByteArrayToHex(byte[] data)
{
char[] c = new char[data.Length * 2];
byte b;
if(BitConverter.IsLittleEndian)
{
//read the byte array in reverse
for (int y = data.Length -1, x = 0; y >= 0; --y, ++x)
{
b = ((byte)(data[y] >> 4));
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(data[y] & 0xF));
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
}
else
{
for (int y = 0, x = 0; y < data.Length; ++y, ++x)
{
b = ((byte)(data[y] >> 4));
c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(data[y] & 0xF));
c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
}
return String.Concat("0x",new string(c));
}
It returns this:
True
0xDCBAABCDFFFE1608
which is the exact hex that went into the byte array.
How to extract the decision rules from scikit-learn decision-tree?
This is the code you need
I have modified the top liked code to indent in a jupyter notebook python 3 correctly
import numpy as np
from sklearn.tree import _tree
def tree_to_code(tree, feature_names):
tree_ = tree.tree_
feature_name = [feature_names[i]
if i != _tree.TREE_UNDEFINED else "undefined!"
for i in tree_.feature]
print("def tree({}):".format(", ".join(feature_names)))
def recurse(node, depth):
indent = " " * depth
if tree_.feature[node] != _tree.TREE_UNDEFINED:
name = feature_name[node]
threshold = tree_.threshold[node]
print("{}if {} <= {}:".format(indent, name, threshold))
recurse(tree_.children_left[node], depth + 1)
print("{}else: # if {} > {}".format(indent, name, threshold))
recurse(tree_.children_right[node], depth + 1)
else:
print("{}return {}".format(indent, np.argmax(tree_.value[node])))
recurse(0, 1)
How to fix height of TR?
Putting div inside a td made it work for me.
<table width="100%">
<tr><td><div style="font-size:2px; height:2px; vertical-align:middle;"> </div></td></tr>
C# ListView Column Width Auto
I believe the author was looking for an equivalent method via the IDE that would generate the code behind and make sure all parameters were in place, etc. Found this from MS:
Creating Event Handlers on the Windows Forms Designer
Coming from a VB background myself, this is what I was looking for, here is the brief version for the click adverse:
- Click the form or control that you want to create an event handler for.
- In the Properties window, click the Events button
- In the list of available events, click the event that you want to create an event handler for.
- In the box to the right of the event name, type the name of the handler and press ENTER
Socket send and receive byte array
You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.
This is the easiest case for a known size (100 bytes):
in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);
In this case DataInputStream
makes sense as it offers readFully()
. If you don't use it, you need to loop yourself until the expected number of bytes is read.
How to extract the decimal part from a floating point number in C?
Maybe the best idea is to solve the problem while the data is in String format. If you have the data as String, you may parse it according to the decimal point. You extract the integral and decimal part as Substrings and then convert these substrings to actual integers.
CSS3 Transform Skew One Side
you can make that using transform and transform origins.
Combining various transfroms gives similar result. I hope you find it helpful. :)
See these examples for simpler transforms. this has left point :
_x000D_
_x000D_
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 100% 50%;_x000D_
-moz-transform-origin: 100% 50%;_x000D_
-o-transform-origin: 100% 50%;_x000D_
transform-origin: 100% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_
This has right skew point :
_x000D_
_x000D_
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 0% 50%;_x000D_
-moz-transform-origin: 0% 50%;_x000D_
-o-transform-origin: 0% 50%;_x000D_
transform-origin: 0% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_
what transform: 0% 50%;
does is it sets the origin to vertical middle and horizontal left of the element. so the perspective is not visible at the left part of the image, so it looks flat. Perspective effect is there at the right part, so it looks slanted.
How to parse a JSON string to an array using Jackson
I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]
How to make <div> fill <td> height
You could try making your div float:
.thatSetsABackgroundWithAnIcon{
float:left;
}
Alternativelly, use inline-block:
.thatSetsABackgroundWithAnIcon{
display:inline-block;
}
Working example of the inline-block method:
_x000D_
_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>_x000D_
<div style="border:1px solid red; height:100%; display:inline-block;">_x000D_
I want cell to be the full height_x000D_
</div>_x000D_
</td>_x000D_
<td>_x000D_
This cell_x000D_
<br/>is higher_x000D_
<br/>than the_x000D_
<br/>first one_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
How to convert these strange characters? (ë, Ã, ì, ù, Ã)
Even though utf8_decode
is a useful solution, I prefer to correct the encoding errors on the table itself. In my opinion it is better to correct the bad characters themselves than making "hacks" in the code. Simply do a replace
on the field on the table. To correct the bad encoded characters from OP :
update <table> set <field> = replace(<field>, "ë", "ë")
update <table> set <field> = replace(<field>, "Ã", "à")
update <table> set <field> = replace(<field>, "ì", "ì")
update <table> set <field> = replace(<field>, "ù", "ù")
Where <table>
is the name of the mysql table and <field>
is the name of the column in the table. Here is a very good check-list for those typically bad encoded windows-1252 to utf-8 characters -> Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters.
Remember to backup your table before trying to replace any characters with SQL!
[I know this is an answer to a very old question, but was facing the issue once again. Some old windows machine didnt encoded the text correct before inserting it to the utf8_general_ci collated table.]
lodash multi-column sortBy descending
As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):
var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);
Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):
var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);
In version 4 of lodash this method has been renamed orderBy:
var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);
How to replace substrings in windows batch file
SET string=bath Abath Bbath XYZbathABC
SET modified=%string:bath=hello%
ECHO %string%
ECHO %modified%
EDIT
Didn't see at first that you wanted the replacement to be preceded by reading the string from a file.
Well, with a batch file you don't have much facility of working on files. In this particular case, you'd have to read a line, perform the replacement, then output the modified line, and then... What then? If you need to replace all the ocurrences of 'bath' in all the file, then you'll have to use a loop:
@ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
FOR /F %%L IN (file.txt) DO (
SET "line=%%L"
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO !line:bath=hello!
ENDLOCAL
)
ENDLOCAL
You can add a redirection to a file:
ECHO !line:bath=hello!>>file2.txt
Or you can apply the redirection to the batch file. It must be a different file.
EDIT 2
Added proper toggling of delayed expansion for correct processing of some characters that have special meaning with batch script syntax, like !
, ^
et al. (Thanks, jeb!)
arranging div one below the other
You don't even need the float:left;
It seems the default behavior is to render one below the other,
if it doesn't happen it's because they are inheriting some style from above.
CSS:
#wrapper{
margin-left:auto;
margin-right:auto;
height:auto;
width:auto;
}
</style>
HTML:
<div id="wrapper">
<div id="inner1">inner1</div>
<div id="inner2">inner2</div>
</div>
Catching KeyboardInterrupt in Python during program shutdown
Checkout this thread, it has some useful information about exiting and tracebacks.
If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Interrupted')
try:
sys.exit(0)
except SystemExit:
os._exit(0)
Understanding SQL Server LOCKS on SELECT queries
I have to add an important comment. Everyone is mentioning that NOLOCK
reads only dirty data. This is not precise. It is also possible that you'll get same row twice or whole row is skipped during your read. Reason is that you could ask for some data in same time when SQL Server is re-balancing b-tree.
Check another threads
https://stackoverflow.com/a/5469238/2108874
http://www.sqlmag.com/article/sql-server/quaere-verum-clustered-index-scans-part-iii.aspx)
With the NOLOCK hint (or setting the isolation level of the session to READ UNCOMMITTED) you tell SQL Server that you don't expect consistency, so there are no guarantees. Bear in mind though that "inconsistent data" does not only mean that you might see uncommitted changes that were later rolled back, or data changes in an intermediate state of the transaction. It also means that in a simple query that scans all table/index data SQL Server may lose the scan position, or you might end up getting the same row twice.
python save image from url
import urllib.request
import os
img_url = "https://betanews.com/wp-content/uploads/2017/09/firefox-logo.jpg"
img_name = os.path.basename(img_url)
urllib.request.urlretrieve(img_url,img_name)
How do I pass variables and data from PHP to JavaScript?
Here is one I do not see posted as an option. It is similar to using Ajax, but clearly different.
First, set a script's source directly to a PHP file.
<script type="text/javascript" src="url_to_your_php_file.php" /></script>
You could even pass a variable back to the PHP file such as this example:
<script type="text/javascript" src="url_to_your_php_file.php?var1=value1" /></script>
Then in "your_php_file.php":
<?php
// THIS IS A SIMPLE EXAMPLE
// it demonstrates one method of using the src attribute to link
// to a PHP file which can generate JavaScript code dynamically
// and share data between PHP and JavaScript
// you may take this learning example and develop it further
// relying on your own coding skills for validating data
// and avoiding errors, of course
header('content-type: text/javascript');
// If you pass a $_GET variable from the JavaScript
// you should add code to validate your $_GET variable(s)
// You can add code to query a database
// using $_GET['var1'] or some other criteria
// You can add simple variable assignments
$value = 'some value';
// For the OP's needs (assumes the class object has been defined)
$val = $myService->getValue();
?>
function name() {
// Pay attention because you need to use quotes properly
// and account for possible quotes in the variable strings
// to avoid both PHP and JavaScript errors
// example assumes $val has been returned as a string
// validate $val as needed using your method of choice
var example1 = <?php echo '"' . $val . '"'; ?>;
var example2 = <?php echo '"' . $value . '"'; ?>;
var example3 = <?php echo '"some other data"'; ?>;
alert( example1 + ' / ' + example2 );
}
<?php
// You may even want to include additional files (.php or .js, etc.)
@include 'local_path_to_some_other_js_file.js';
@include 'local_path_to_some_other_php_file.php';
exit;
?>
Authentication plugin 'caching_sha2_password' is not supported
I had this same issue but my resolution was different because this didn't completely work.
I found this on a GitHub forum - copy and paste this into your terminal. You don't have to change your password; it can be the exact same.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '{NewPassword}';
Convert columns to string in Pandas
If you need to convert ALL columns to strings, you can simply use:
df = df.astype(str)
This is useful if you need everything except a few columns to be strings/objects, then go back and convert the other ones to whatever you need (integer in this case):
df[["D", "E"]] = df[["D", "E"]].astype(int)
Get width height of remote image from url
ES6: Using async/await
you can do below getMeta
function in sequence-like way and you can use it as follows (which is almost identical to code in your question (I add await
keyword and change variable end
to img
, and change var
to let
keyword). You need to run getMeta
by await
only from async
function (run).
_x000D_
_x000D_
function getMeta(url) {
return new Promise((resolve, reject) => {
let img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject();
img.src = url;
});
}
async function run() {
let img = await getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");
let w = img.width;
let h = img.height;
size.innerText = `width=${w}px, height=${h}px`;
size.appendChild(img);
}
run();
_x000D_
<div id="size" />
_x000D_
_x000D_
_x000D_
Can't push to remote branch, cannot be resolved to branch
Based on my own testing and the OP's comments, I think at some point they goofed on the casing of the branch name.
First, I believe the OP is on a case insensitive operating system like OS X or Windows. Then they did something like this...
$ git checkout -b SQLMigration/ReportFixes
Switched to a new branch 'SQLMigration/ReportFixes'
$ git push origin SqlMigration/ReportFixes
fatal: SqlMigration/ReportFixes cannot be resolved to branch.
Note the casing difference. Also note the error is very different from if you just typo the name.
$ git push origin SQLMigration/ReportFixme
error: src refspec SQLMigration/ReportFixme does not match any.
error: failed to push some refs to '[email protected]:schwern/testing123.git'
Because Github uses the filesystem to store branch names, it tries to open .git/refs/heads/SqlMigration/ReportFixes
. Because the filesystem is case insensitive it successfully opens .git/refs/heads/SqlMigration/ReportFixes
but gets confused when it tries to compare the branch names case-sensitively and they don't match.
How they got into a state where the local branch is SQLMigration/ReportFixes
and the remote branch is SqlMigration/ReportFixes
I'm not sure. I don't believe Github messed with the remote branch name. Simplest explanation is someone else with push access changed the remote branch name. Otherwise, at some point they did something which managed to create the remote with the typo. If they check their shell history, perhaps with history | grep -i sqlmigration/reportfixes
they might be able to find a command where they mistyped the casing.
Random word generator- Python
Solution for Python 3
For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.
import urllib.request
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()
Output:
>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]
And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:
import random
upper_words = [word for word in words if word[0].isupper()]
name_words = [word for word in upper_words if not word.isupper()]
rand_name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])
And some random names:
>>> for n in range(10):
' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])
'Semiramis Sicilian'
'Julius Genevieve'
'Rwanda Cohn'
'Quito Sutherland'
'Eocene Wheller'
'Olav Jove'
'Weldon Pappas'
'Vienna Leyden'
'Io Dave'
'Schwartz Stromberg'
How can I get a uitableViewCell by indexPath?
[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex]
will give you uitableviewcell. But I am not sure what exactly you are asking for! Because you have this code and still you asking how to get uitableviewcell. Some more information will help to answer you :)
ADD: Here is an alternate syntax that achieves the same thing without the cast.
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];
Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel
No.
If the user is sophisticated or determined enough to:
- Open the Excel VBA editor
- Use the object browser to see the list of all sheets, including VERYHIDDEN ones
- Change the property of the sheet to VISIBLE or just HIDDEN
then they are probably sophisticated or determined enough to:
- Search the internet for "remove Excel 2007 project password"
- Apply the instructions they find.
So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.
The view 'Index' or its master was not found.
I added viewlocationformat to RazorViewEngine and worked for me.
ViewLocationFormats = new[] {
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",
"~/Areas/Admin/Views/{1}/{0}.cshtml",
"~/Areas/Admin/Views/Shared/{0}.cshtml"
};
How to make pylab.savefig() save image for 'maximized' window instead of default size
If I understand correctly what you want to do, you can create your figure and set the size of the window. Afterwards, you can save your graph with the matplotlib toolbox button. Here an example:
from pylab import get_current_fig_manager,show,plt,imshow
plt.Figure()
thismanager = get_current_fig_manager()
thismanager.window.wm_geometry("500x500+0+0")
#in this case 500 is the size (in pixel) of the figure window. In your case you want to maximise to the size of your screen or whatever
imshow(your_data)
show()
Pentaho Data Integration SQL connection
In addition to the other answers here, here's how you can do it on Ubuntu (14.04):
sudo apt-get install libmysql-java
this will download mysql-connector-java-5.x.x.jar
to /usr/share/java/
, which i believe also automatically creates a symlink named mysql-connector-java.jar
.
Then, create a symlink in /your/path/to/data-integration/lib/
:
ln -s /usr/share/java/mysql-connector-java.jar /your/path/to/data-integration/lib/mysql-connector-java.jar
ReactJS lifecycle method inside a function Component
You can use react-pure-lifecycle to add lifecycle functions to functional components.
Example:
import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';
const methods = {
componentDidMount(props) {
console.log('I mounted! Here are my props: ', props);
}
};
const Channels = props => (
<h1>Hello</h1>
)
export default lifecycle(methods)(Channels);
What Ruby IDE do you prefer?
I started out using gEdit (ubuntu user), but even with all the plugins and modifications (class/file browser, terminal, darkmate scheme, etc, etc) it still always seemed to come up short. I've also tried like hell to get Aptana RadRails and Studio to work, but none of them ever really seemed to sync up with my workflow. I've even tried using Eclipse, but again, it just didn't work for me.
RubyMine also seemed like it would be great, but I found it to be way too buggy, even after the upgrade to 3.0.
So far, my favorite Ruby editor is Komodo Edit. It's got syntax highlighting and can detect errors and recognize your code based on user-specified ruby versions. Syntax highlighting schema are easily customizable and easy on the eyes. There are some very nice plugins for git, it can have split-screen editors (love that feature), and a great file-browser. I really wish Komodo had built-in terminal (multiple terminal) support, but everything else about it I've really come to love, and haven't found anything better yet.
Request failed: unacceptable content-type: text/html using AFNetworking 2.0
Setting my RequestOperationManager
Response Serializer to HTTPResponseSerializer
fixed the issue.
Objective-C
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Swift
manager.responseSerializer = AFHTTPResponseSerializer()
Making this change means I don't need to add acceptableContentTypes
to every request I make.
Tool for sending multipart/form-data request
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
Suggestion To Load Via Postman
Fails If In Header
Works
replace NULL with Blank value or Zero in sql server
Different ways to replace NULL in sql server
Replacing NULL value using:
1. ISNULL() function
2. COALESCE() function
3. CASE Statement
SELECT Name as EmployeeName, ISNULL(Bonus,0) as EmployeeBonus from tblEmployee
SELECT Name as EmployeeName, COALESCE(Bonus, 0) as EmployeeBonus
FROM tblEmployee
SELECT Name as EmployeeName, CASE WHEN Bonus IS NULL THEN 0
ELSE Bonus END as EmployeeBonus
FROM tblEmployee
.NET NewtonSoft JSON deserialize map to a different property name
I am using JsonProperty attributes when serializing but ignoring them when deserializing using this ContractResolver
:
public class IgnoreJsonPropertyContractResolver: DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
foreach (var p in properties) { p.PropertyName = p.UnderlyingName; }
return properties;
}
}
The ContractResolver
just sets every property back to the class property name (simplified from Shimmy's solution). Usage:
var airplane= JsonConvert.DeserializeObject<Airplane>(json,
new JsonSerializerSettings { ContractResolver = new IgnoreJsonPropertyContractResolver() });
Telegram Bot - how to get a group chat id?
create a bot, or if already created set as follows:
has access to messages
apparently, regardless of how old/new the Telegram group is:
add a bot to the group
remove bot from the group
add bot again to the group
create a script file and run getUpdates
method
example:
var vApiTokenTelegram = "1234567890:???>yg5GeL5PuItAOEhvdcPPELAOCCy3jBo"; // @?????Bot API token
var vUrlTelegram = "https://api.telegram.org/bot" + vApiTokenTelegram;
function getUpdates() {
var response = UrlFetchApp.fetch(vUrlTelegram + "/getUpdates");
console.log(response.getContentText());
}
- function shall log to the console the following:
[20-04-21 00:46:11:130 PDT] {"ok":true,"result":[{"update_id":81329501,
"message":{"message_id":975,"from":{"id":962548471,"is_bot":false,"first_name":"Trajano","last_name":"Roberto","username":"TrajanoRoberto","language_code":"en"},"chat":{"id":-1001202656383,"title":"R\u00e1dioRN - A voz da na\u00e7\u00e3o!","type":"supergroup"},"date":1587454914,"left_chat_participant":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"left_chat_member":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"}}},{"update_id":81329502,
"message":{"message_id":976,"from":{"id":962548471,"is_bot":false,"first_name":"Trajano","last_name":"Roberto","username":"TrajanoRoberto","language_code":"en"},"chat":{"id":-1001202656383,"title":"R\u00e1dioRN - A voz da na\u00e7\u00e3o!","type":"supergroup"},"date":1587454932,"new_chat_participant":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"new_chat_member":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"new_chat_members":[{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"}]}}]}
- Telegram group chat_id can be extracted from above message
"chat":{"id":-1001202656383,"title"
Git: How to find a deleted file in the project commit history?
Suppose you want to recover a file called MyFile
, but are uncertain of its path (or its extension, for that matter):
Preliminary: Avoid confusion by stepping to the git root
A nontrivial project may have multiple directories with similar or identical filenames.
> cd <project-root>
Find the full path
git log --diff-filter=D --summary | grep delete | grep MyFile
delete mode 100644 full/path/to/MyFile.js
full/path/to/MyFile.js
is the path & file you're seeking.
Determine all the commits that affected that file
git log --oneline --follow -- full/path/to/MyFile.js
bd8374c Some helpful commit message
ba8d20e Another prior commit message affecting that file
cfea812 The first message for a commit in which that file appeared.
Checkout the file
If you choose the first-listed commit (the last chronologically, here bd8374c), the file will not be found, since it was deleted in that commit.
> git checkout bd8374c -- full/path/to/MyFile.js
`error: pathspec 'full/path/to/MyFile.js' did not match any file(s) known to git.`
Just select the preceding (append a caret) commit:
> git checkout bd8374c^ -- full/path/to/MyFile.js
CSS: Set a background color which is 50% of the width of the window
One way to implement your issue is to add a single line to your div's css:
background-image: linear-gradient(90deg, black 50%, blue 50%);
Here is a demonstration code and more options (horizontal, diagonal, etc.), you can click on "Run code snippet" to see it live.
_x000D_
_x000D_
.abWhiteAndBlack
{
background-image: linear-gradient(90deg, black 50%, blue 50%);
height: 300px;
width: 300px;
margin-bottom: 80px;
}
.abWhiteAndBlack2
{
background-image: linear-gradient(180deg, black 50%, blue 50%);
height: 300px;
width: 300px;
margin-bottom: 80px;
}
.abWhiteAndBlack3
{
background-image: linear-gradient(45deg, black 50%, blue 50%);
height: 300px;
width: 300px;
margin-bottom: 80px;
}
_x000D_
Vertical:
<div class="abWhiteAndBlack">
</div>
Horizonal:
<div class="abWhiteAndBlack2">
</div>
Diagonal:
<div class="abWhiteAndBlack3">
</div>
_x000D_
_x000D_
_x000D_
Page vs Window in WPF?
Page Control can be contained in Window Control but vice versa is not possible
You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer).
WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.
Read file data without saving it in Flask
in function
def handleUpload():
if 'photo' in request.files:
photo = request.files['photo']
if photo.filename != '':
image = request.files['photo']
image_string = base64.b64encode(image.read())
image_string = image_string.decode('utf-8')
#use this to remove b'...' to get raw string
return render_template('handleUpload.html',filestring = image_string)
return render_template('upload.html')
in html file
<html>
<head>
<title>Simple file upload using Python Flask</title>
</head>
<body>
{% if filestring %}
<h1>Raw image:</h1>
<h1>{{filestring}}</h1>
<img src="data:image/png;base64, {{filestring}}" alt="alternate" />.
{% else %}
<h1></h1>
{% endif %}
</body>
How can I execute Python scripts using Anaconda's version of Python?
Set your python path to the Anaconda version instead
Windows has a built-in dialog for changing environment variables (following guide applies to XP classical view): Right-click the icon for your machine (usually located on your Desktop and called “My Computer”) and choose Properties there. Then, open the Advanced tab and click the Environment Variables button.
In short, your path is:
My Computer ? Properties ? Advanced ? Environment Variables
In this dialog, you can add or modify User and System variables. To change System variables, you need non-restricted access to your machine (i.e. Administrator rights).
Find your PATH variable and add the location of your Anaconda directory.
Example of someone doing it here: How to add to the PYTHONPATH in Windows, so it finds my modules/packages? Make sure that you sub path out for the Anaconda file though.
Makefile to compile multiple C programs?
This will compile all *.c
files upon make
to executables without the .c
extension as in gcc program.c -o program
.
make
will automatically add any flags you add to CFLAGS
like CFLAGS = -g Wall
.
If you don't need any flags CFLAGS
can be left blank (as below) or omitted completely.
SOURCES = $(wildcard *.c)
EXECS = $(SOURCES:%.c=%)
CFLAGS =
all: $(EXECS)
How to define a List bean in Spring?
<bean id="someBean"
class="com.somePackage.SomeClass">
<property name="myList">
<list value-type="com.somePackage.TypeForList">
<ref bean="someBeanInTheList"/>
<ref bean="someOtherBeanInTheList"/>
<ref bean="someThirdBeanInTheList"/>
</list>
</property>
</bean>
And in SomeClass:
class SomeClass {
List<TypeForList> myList;
@Required
public void setMyList(List<TypeForList> myList) {
this.myList = myList;
}
}
What are carriage return, linefeed, and form feed?
\r
is carriage return and moves the cursor back like if i will do-
printf("stackoverflow\rnine")
ninekoverflow
means it has shifted the cursor to the beginning of "stackoverflow" and overwrites the starting four characters since "nine" is four character long.
\n
is new line character which changes the line and takes the cursor to the beginning of a new line like-
printf("stackoverflow\nnine")
stackoverflow
nine
\f
is form feed, its use has become obsolete but it is used for giving indentation like
printf("stackoverflow\fnine")
stackoverflow
nine
if i will write like-
printf("stackoverflow\fnine\fgreat")
stackoverflow
nine
great
Convert SVG image to PNG with PHP
This is a method for converting a svg picture to a gif using standard php GD tools
1) You put the image into a canvas element in the browser:
<canvas id=myCanvas></canvas>
<script>
var Key='picturename'
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
base_image = new Image();
base_image.src = myimage.svg;
base_image.onload = function(){
//get the image info as base64 text string
var dataURL = canvas.toDataURL();
//Post the image (dataURL) to the server using jQuery post method
$.post('ProcessPicture.php',{'TheKey':Key,'image': dataURL ,'h': canvas.height,'w':canvas.width,"stemme":stemme } ,function(data,status){ alert(data+' '+status) });
}
</script>
And then convert it at the server (ProcessPicture.php) from (default) png to gif and save it. (you could have saved as png too then use imagepng instead of image gif):
//receive the posted data in php
$pic=$_POST['image'];
$Key=$_POST['TheKey'];
$height=$_POST['h'];
$width=$_POST['w'];
$dir='../gif/'
$gifName=$dir.$Key.'.gif';
$pngName=$dir.$Key.'.png';
//split the generated base64 string before the comma. to remove the 'data:image/png;base64, header created by and get the image data
$data = explode(',', $pic);
$base64img = base64_decode($data[1]);
$dimg=imagecreatefromstring($base64img);
//in order to avoid copying a black figure into a (default) black background you must create a white background
$im_out = ImageCreateTrueColor($width,$height);
$bgfill = imagecolorallocate( $im_out, 255, 255, 255 );
imagefill( $im_out, 0,0, $bgfill );
//Copy the uploaded picture in on the white background
ImageCopyResampled($im_out, $dimg ,0, 0, 0, 0, $width, $height,$width, $height);
//Make the gif and png file
imagegif($im_out, $gifName);
imagepng($im_out, $pngName);
How do I change JPanel inside a JFrame on the fly?
The other individuals answered the question. I want to suggest you use a JTabbedPane instead of replacing content. As a general rule, it is bad to have visual elements of your application disappear or be replaced by other content. Certainly there are exceptions to every rule, and only you and your user community can decide the best approach.
How to store and retrieve a dictionary with redis
The redis SET command stores a string, not arbitrary data. You could try using the redis HSET command to store the dict as a redis hash with something like
for k,v in my_dict.iteritems():
r.hset('my_dict', k, v)
but the redis datatypes and python datatypes don't quite line up. Python dicts can be arbitrarily nested, but a redis hash is going to require that your value is a string. Another approach you can take is to convert your python data to string and store that in redis, something like
r.set('this_dict', str(my_dict))
and then when you get the string out you will need to parse it to recreate the python object.
Run a .bat file using python code
python_test.py
import subprocess
a = subprocess.check_output("batch_1.bat")
print a
This gives output from batch file to be print on the python IDLE/running console. So in batch file you can echo the result in each step to debug the issue. This is also useful in automation when there is an error happening in the batch call, to understand and locate the error easily.(put "echo off" in batch file beginning to avoid printing everything)
batch_1.bat
echo off
echo "Hello World"
md newdir
echo "made new directory"
How do I update Anaconda?
root
is the old (pre-conda 4.4) name for the main environment; after conda 4.4, it was renamed to be base
. source
What 95% of people actually want
In most cases what you want to do when you say that you want to update Anaconda is to execute the command:
conda update --all
(But this should be preceeded by conda update -n base conda
so you have the latest conda
version installed)
This will update all packages in the current environment to the latest version -- with the small print being that it may use an older version of some packages in order to satisfy dependency constraints (often this won't be necessary and when it is necessary the package plan solver will do its best to minimize the impact).
This needs to be executed from the command line, and the best way to get there is from Anaconda Navigator, then the "Environments" tab, then click on the triangle beside the base
environment, selecting "Open Terminal":
This operation will only update the one selected environment (in this case, the base
environment). If you have other environments you'd like to update you can repeat the process above, but first click on the environment. When it is selected there is a triangular marker on the right (see image above, step 3). Or from the command line you can provide the environment name (-n envname
) or path (-p /path/to/env
), for example to update your dspyr
environment from the screenshot above:
conda update -n dspyr --all
Update individual packages
If you are only interested in updating an individual package then simply click on the blue arrow or blue version number in Navigator, e.g. for astroid
or astropy
in the screenshot above, and this will tag those packages for an upgrade. When you are done you need to click the "Apply" button:
Or from the command line:
conda update astroid astropy
Updating just the packages in the standard Anaconda Distribution
If you don't care about package versions and just want "the latest set of all packages in the standard Anaconda Distribution, so long as they work together", then you should take a look at this gist.
Why updating the Anaconda package is almost always a bad idea
In most cases updating the Anaconda package in the package list will have a surprising result: you may actually downgrade many packages (in fact, this is likely if it indicates the version as custom
). The gist above provides details.
Leverage conda environments
Your base
environment is probably not a good place to try and manage an exact set of packages: it is going to be a dynamic working space with new packages installed and packages randomly updated. If you need an exact set of packages then create a conda environment to hold them. Thanks to the conda package cache and the way file linking is used doing this is typically i) fast and ii) consumes very little additional disk space. E.g.
conda create -n myspecialenv -c bioconda -c conda-forge python=3.5 pandas beautifulsoup seaborn nltk
The conda documentation has more details and examples.
pip, PyPI, and setuptools?
None of this is going to help with updating packages that have been installed from PyPI via pip
or any packages installed using python setup.py install
. conda list
will give you some hints about the pip-based Python packages you have in an environment, but it won't do anything special to update them.
Commercial use of Anaconda or Anaconda Enterprise
It is pretty much exactly the same story, with the exception that you may not be able to update the base
environment if it was installed by someone else (say to /opt/anaconda/latest
). If you're not able to update the environments you are using you should be able to clone and then update:
conda create -n myenv --clone base
conda update -n myenv --all
How to work on UAC when installing XAMPP
This is a specific issue for Windows Vista, 7, 8 (and presumably newer).
User Account Control (UAC) is a feature in Windows that can help you stay in control of your computer by informing you when a program makes a change that requires administrator-level permission. UAC works by adjusting the permission level of your user account.
This is applied mostly to C:\Program Files. You may have noticed sometimes, that some applications can see files in C:\Program Files that does not exist there. You know why? Windows now tend to have "C:\Program Files" folder customized for every user. For example, old applications store config files (like .ini) in the same folder where the executable files are stored. In the good old days all users had the same configurations for such apps. In nowadays Windows stores configs in the special folder tied to the user account. Thus, now different users may have different configs while application still think that config files are in the same folder with the executables.
XAMPP does not like to have different config for different users. In fact it is not a config file for XAMPP, it is folders where you keep your projects and databases. The idea of XAMPP is to make projects same for all users. This is a source of a conflict with Windows.
All you need is to avoid installing XAMPP into C:\Program Files. Thus XAMPP will always use the original files for all users and there would be no confusion.
I recommend to install XAMPP into the special folder in root directory like in C:\XAMPP. But before you choose the folder you need to click on this warning message.
How to display the value of the bar on each bar with pyplot.barh()?
I was trying to do this with stacked plot bars. The code that worked for me was.
# Code to plot. Notice the variable ax.
ax = df.groupby('target').count().T.plot.bar(stacked=True, figsize=(10, 6))
ax.legend(bbox_to_anchor=(1.1, 1.05))
# Loop to add on each bar a tag in position
for rect in ax.patches:
height = rect.get_height()
ypos = rect.get_y() + height/2
ax.text(rect.get_x() + rect.get_width()/2., ypos,
'%d' % int(height), ha='center', va='bottom')
CSS Background Image Not Displaying
Its always good to have these additional properties besides the
background-image:url('path') no-repeat 0 0;
set dimension to the element
width:x;
height:y;
background-size:100%
- This property helps to fit the image to the above dimension that you define for an element.
How do I capture all of my compiler's output to a file?
From http://www.oreillynet.com/linux/cmd/cmd.csp?path=g/gcc
The > character does not redirect the
standard error. It's useful when you
want to save legitimate output without
mucking up a file with error messages.
But what if the error messages are
what you want to save? This is quite
common during troubleshooting. The
solution is to use a greater-than sign
followed by an ampersand. (This
construct works in almost every modern
UNIX shell.) It redirects both the
standard output and the standard
error. For instance:
$ gcc invinitjig.c >& error-msg
Have a look there, if this helps:
another forum
AngularJS - Create a directive that uses ng-model
This is a little late answer, but I found this awesome post about NgModelController
, which I think is exactly what you were looking for.
TL;DR - you can use require: 'ngModel'
and then add NgModelController
to your linking function:
link: function(scope, iElement, iAttrs, ngModelCtrl) {
//TODO
}
This way, no hacks needed - you are using Angular's built-in ng-model
Forward declaring an enum in C++
I'd do it this way:
[in the public header]
typedef unsigned long E;
void Foo(E e);
[in the internal header]
enum Econtent { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X,
FORCE_32BIT = 0xFFFFFFFF };
By adding FORCE_32BIT we ensure that Econtent compiles to a long, so it's interchangeable with E.
Gson: How to exclude specific fields from Serialization without annotations
I'm working just by putting the @Expose
annotation, here my version that I use
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
In Model
class:
@Expose
int number;
public class AdapterRestApi {
In the Adapter
class:
public EndPointsApi connectRestApi() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(90000, TimeUnit.SECONDS)
.readTimeout(90000,TimeUnit.SECONDS).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ConstantRestApi.ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit.create (EndPointsApi.class);
}
extract part of a string using bash/cut/split
What about sed? That will work in a single command:
sed 's#.*/\([^:]*\).*#\1#' <<<$string
- The
#
are being used for regex dividers instead of /
since the string has /
in it.
.*/
grabs the string up to the last backslash.
\( .. \)
marks a capture group. This is \([^:]*\)
.
- The
[^:]
says any character _except a colon, and the *
means zero or more.
.*
means the rest of the line.
\1
means substitute what was found in the first (and only) capture group. This is the name.
Here's the breakdown matching the string with the regular expression:
/var/cpanel/users/ joebloggs :DNS9=domain.com joebloggs
sed 's#.*/ \([^:]*\) .* #\1 #'
UIScrollView scroll to bottom programmatically
Xamarin.iOS version for UICollectionView
of the accepted answer for ease in copying and pasting
var bottomOffset = new CGPoint (0, CollectionView.ContentSize.Height - CollectionView.Frame.Size.Height + CollectionView.ContentInset.Bottom);
CollectionView.SetContentOffset (bottomOffset, false);
How to draw an overlay on a SurfaceView used by Camera on Android?
Try calling setWillNotDraw(false)
from surfaceCreated
:
public void surfaceCreated(SurfaceHolder holder) {
try {
setWillNotDraw(false);
mycam.setPreviewDisplay(holder);
mycam.startPreview();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG,"Surface not created");
}
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(area, rectanglePaint);
Log.w(this.getClass().getName(), "On Draw Called");
}
and calling invalidate
from onTouchEvent
:
public boolean onTouch(View v, MotionEvent event) {
invalidate();
return true;
}
jquery - Check for file extension before uploading
If you want to do it without a plugin you could use the following.
Javascript, using jQuery:
$(document).ready( function (){
$("#your_form").submit( function(submitEvent) {
// get the file name, possibly with path (depends on browser)
var filename = $("#file_input").val();
// Use a regular expression to trim everything before final dot
var extension = filename.replace(/^.*\./, '');
// Iff there is no dot anywhere in filename, we would have extension == filename,
// so we account for this possibility now
if (extension == filename) {
extension = '';
} else {
// if there is an extension, we convert to lower case
// (N.B. this conversion will not effect the value of the extension
// on the file upload.)
extension = extension.toLowerCase();
}
switch (extension) {
case 'jpg':
case 'jpeg':
case 'png':
alert("it's got an extension which suggests it's a PNG or JPG image (but N.B. that's only its name, so let's be sure that we, say, check the mime-type server-side!)");
// uncomment the next line to allow the form to submitted in this case:
// break;
default:
// Cancel the form submission
submitEvent.preventDefault();
}
});
});
HTML:
<form id="your_form" method="post" enctype="multipart/form-data">
<input id="file_input" type="file" />
<input type="submit">
</form>
Find unique rows in numpy.array
The numpy_indexed package (disclaimer: I am its author) wraps the solution posted by Jaime in a nice and tested interface, plus many more features:
import numpy_indexed as npi
new_a = npi.unique(a) # unique elements over axis=0 (rows) by default
vba error handling in loop
What about?
If oSheet.QueryTables.Count > 0 Then
oCmbBox.AddItem oSheet.Name
End If
Or
If oSheet.ListObjects.Count > 0 Then
'// Source type 3 = xlSrcQuery
If oSheet.ListObjects(1).SourceType = 3 Then
oCmbBox.AddItem oSheet.Name
End IF
End IF
How to use ScrollView in Android?
A ScrollView is a special type of FrameLayout in that it allows users to scroll through a list of views that occupy more space than the physical display.I just add some attributes .
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:scrollbars = "vertical"
android:scrollbarStyle="insideInset"
>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
>
<!-- Add here which you want -->
</TableLayout>
</ScrollView>
Android: ListView elements with multiple clickable buttons
This is sort of an appendage @znq's answer...
There are many cases where you want to know the row position for a clicked item AND you want to know which view in the row was tapped. This is going to be a lot more important in tablet UIs.
You can do this with the following custom adapter:
private static class CustomCursorAdapter extends CursorAdapter {
protected ListView mListView;
protected static class RowViewHolder {
public TextView mTitle;
public TextView mText;
}
public CustomCursorAdapter(Activity activity) {
super();
mListView = activity.getListView();
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// do what you need to do
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = View.inflate(context, R.layout.row_layout, null);
RowViewHolder holder = new RowViewHolder();
holder.mTitle = (TextView) view.findViewById(R.id.Title);
holder.mText = (TextView) view.findViewById(R.id.Text);
holder.mTitle.setOnClickListener(mOnTitleClickListener);
holder.mText.setOnClickListener(mOnTextClickListener);
view.setTag(holder);
return view;
}
private OnClickListener mOnTitleClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(TAG, "Title clicked, row %d", position);
}
};
private OnClickListener mOnTextClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v.getParent());
Log.v(TAG, "Text clicked, row %d", position);
}
};
}
How to import a CSS file in a React Component
The following imports an external CSS file in a React component and outputs the CSS rules in the <head />
of the website.
- Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
- In webpack.config.js:
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
}
- In a component file:
import './path/to/file.css';
DateTime vs DateTimeOffset
The most important distinction is that DateTime does not store time zone information, while DateTimeOffset does.
Although DateTime distinguishes between UTC and Local, there is absolutely no explicit time zone offset associated with it. If you do any kind of serialization or conversion, the server's time zone is going to be used. Even if you manually create a local time by adding minutes to offset a UTC time, you can still get bit in the serialization step, because (due to lack of any explicit offset in DateTime) it will use the server's time zone offset.
For example, if you serialize a DateTime value with Kind=Local using Json.Net and an ISO date format, you'll get a string like 2015-08-05T07:00:00-04
. Notice that last part (-04) had nothing to do with your DateTime or any offset you used to calculate it... it's just purely the server's time zone offset.
Meanwhile, DateTimeOffset explicitly includes the offset. It may not include the name of the time zone, but at least it includes the offset, and if you serialize it, you're going to get the explicitly included offset in your value instead of whatever the server's local time happens to be.
Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Combining border-top,border-right,border-left,border-bottom in CSS
No you can't set them as single one
for example if you have
div{
border-top: 2px solid red;
border-right: 2px solid red;
border-bottom: 2px solid red;
border-left: 2px solid red;
}
same properties for all fours then you can set them in single line
div{border:2px solid red;}
Bogus foreign key constraint fail
On Rails, one can do the following using the rails console
:
connection = ActiveRecord::Base.connection
connection.execute("SET FOREIGN_KEY_CHECKS=0;")
How to achieve function overloading in C?
In the sense you mean — no, you cannot.
You can declare a va_arg
function like
void my_func(char* format, ...);
, but you'll need to pass some kind of information about number of variables and their types in the first argument — like printf()
does.
Check if a string contains a substring in SQL Server 2005, using a stored procedure
CHARINDEX()
searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found
if CHARINDEX('ME',@mainString) > 0
begin
--do something
end
Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX
call would look like:
CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')
(Add more recursive REPLACE() calls for any other punctuation that may occur)
How do I debug Windows services in Visual Studio?
You can also try this.
- Create your Windows service and install and start…. That is, Windows services must be running in your system.
- While your service is running, go to the Debug menu, click on Attach Process (or process in old Visual Studio)
- Find your running service, and then make sure the Show process from all users and Show processes in all sessions is selected, if not then select it.
- Click the Attach button
- Click OK
- Click Close
- Set a break point to your desirable location and wait for execute. It will debug automatic whenever your code reaches to that point.
- Remember, put your breakpoint at reachable place, if it is onStart(), then stop and start the service again
(After a lot of googling, I found this in "How to debug the Windows Services in Visual Studio".)
How to delete specific characters from a string in Ruby?
For those coming across this and looking for performance, it looks like #delete
and #tr
are about the same in speed and 2-4x faster than gsub
.
text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04
How to remove an element from an array in Swift
Remove elements using indexes array:
Array of Strings and indexes
let animals = ["cats", "dogs", "chimps", "moose", "squarrel", "cow"]
let indexAnimals = [0, 3, 4]
let arrayRemainingAnimals = animals
.enumerated()
.filter { !indexAnimals.contains($0.offset) }
.map { $0.element }
print(arrayRemainingAnimals)
//result - ["dogs", "chimps", "cow"]
Array of Integers and indexes
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
let indexesToRemove = [3, 5, 8, 12]
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains($0.offset) }
.map { $0.element }
print(numbers)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
Remove elements using element value of another array
Arrays of integers
let arrayResult = numbers.filter { element in
return !indexesToRemove.contains(element)
}
print(arrayResult)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
Arrays of strings
let arrayLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
let arrayRemoveLetters = ["a", "e", "g", "h"]
let arrayRemainingLetters = arrayLetters.filter {
!arrayRemoveLetters.contains($0)
}
print(arrayRemainingLetters)
//result - ["b", "c", "d", "f", "i"]
Commenting code in Notepad++
Without having selected a language type for your file there are no styles defined. Comment and block comment are language specific style preferences. If that's a PITA...
To select for multi-line editing you can use
shift
+ alt
+ down arrow
PHP if not statements
No matter what $action is, it will always either not be "add" OR not be "delete", which is why the if condition always passes. What you want is to use && instead of ||:
(!isset($action)) || ($action !="add" && $action !="delete"))
JavaScript: Object Rename Key
Here is an example to create a new object with renamed keys.
let x = { id: "checkout", name: "git checkout", description: "checkout repository" };
let renamed = Object.entries(x).reduce((u, [n, v]) => {
u[`__${n}`] = v;
return u;
}, {});
Disable cache for some images
A common and simple solution to this problem that feels like a hack but is fairly portable is to add a randomly generated query string to each request for the dynamic image.
So, for example -
<img src="image.png" />
Would become
<img src="image.png?dummy=8484744" />
Or
<img src="image.png?dummy=371662" />
From the point of view of the web-server the same file is accessed, but from the point of view of the browser no caching can be performed.
The random number generation can happen either on the server when serving the page (just make sure the page itself isn't cached...), or on the client (using JavaScript).
You will need to verify whether your web-server can cope with this trick.
How to combine GROUP BY, ORDER BY and HAVING
ORDER BY
is always last...
However, you need to pick the fields you ACTUALLY WANT then select only those and group by them. SELECT *
and GROUP BY Email
will give you RANDOM VALUES for all the fields but Email
. Most RDBMS will not even allow you to do this because of the issues it creates, but MySQL is the exception.
SELECT Email, COUNT(*)
FROM user_log
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY UpdateDate DESC
Splitting a table cell into two columns in HTML
I came here for a similar problem I was facing with my table headers.
@MrMisterMan's answer, as well as others, were really helpful, but the borders were beating my game. So, I did some research to find the use rowspan.
Here's what I did and I guess it might help others facing something similar.
_x000D_
_x000D_
<table style="width: 100%; margin-top: 10px; font-size: 0.8em;" border="1px">_x000D_
<tr align="center" >_x000D_
<th style="padding:2.5px; width: 10%;" rowspan="2">Item No</th>_x000D_
<th style="padding:2.5px; width: 55%;" rowspan="2">DESCRIPTION</th>_x000D_
<th style="padding:2.5px;" rowspan="2">Quantity</th>_x000D_
<th style="padding:2.5px;" colspan="2">Rate per Item</th>_x000D_
<th style="padding:2.5px;" colspan="2">AMOUNT</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Rs.</th>_x000D_
<th>P.</th>_x000D_
<th>Rs.</th>_x000D_
<th>P.</th>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
No converter found capable of converting from type to type
Turns out, when the table name is different than the model name, you have to change the annotations to:
@Entity
@Table(name = "table_name")
class WhateverNameYouWant {
...
Instead of simply using the @Entity annotation.
What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.
Bootstrap: how do I change the width of the container?
@mcbjam already gave this answer but here's a bit more explanation.
You can easily make the change using a media query in your CSS file without downloading BS. I just did this and it works beautifully.
The media query's "min-width" value will tell CSS to change the width of your container to 1000px only on screens larger than 1200px (or whatever width you choose to include there). This preserves the responsiveness of your site, so when the screen size jumps below that value (smaller monitor, tablet, smartphone, etc.), your site will still adjust to fit the smaller screens.
@media (min-width: 1200px) {
.container {
width: 1000px;
}
}
Copy file from source directory to binary directory using CMake
both option are valid and targeting two different steps of your build:
file(COPY ...
copies the file in configuration step and only in this step. When you rebuild your project without having changed your cmake configuration, this command won't be executed.
add_custom_command
is the preferred choice when you want to copy the file around on each build step.
The right version for your task would be:
add_custom_command(
TARGET foo POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_SOURCE_DIR}/test/input.txt
${CMAKE_CURRENT_BINARY_DIR}/input.txt)
you can choose between PRE_BUILD
, PRE_LINK
, POST_BUILD
best is you read the documentation of add_custom_command
an example on how to use the first version can be found here: Use CMake add_custom_command to generate source for another target
Javascript Iframe innerHTML
Conroy's answer was right. In the case you need only stuff from body tag, just use:
$('#my_iframe').contents().find('body').html();
Checking if a key exists in a JS object
var obj = {
"key1" : "k1",
"key2" : "k2",
"key3" : "k3"
};
if ("key1" in obj)
console.log("has key1 in obj");
=========================================================================
To access a child key of another key
var obj = {
"key1": "k1",
"key2": "k2",
"key3": "k3",
"key4": {
"keyF": "kf"
}
};
if ("keyF" in obj.key4)
console.log("has keyF in obj");
Developing for Android in Eclipse: R.java not regenerating
- Make sure your XML files are fine without any issues
- Make sure your manifest has no errors in it
- Make sure your strings have no problem in them
If any of them have issues, Eclipse might fail to build the R class...
Fix the issues, clean & rebuild..
What does it mean to bind a multicast (UDP) socket?
To bind a UDP socket when receiving multicast means to specify an address and port from which to receive data (NOT a local interface, as is the case for TCP acceptor bind). The address specified in this case has a filtering role, i.e. the socket will only receive datagrams sent to that multicast address & port, no matter what groups are subsequently joined by the socket. This explains why when binding to INADDR_ANY (0.0.0.0) I received datagrams sent to my multicast group, whereas when binding to any of the local interfaces I did not receive anything, even though the datagrams were being sent on the network to which that interface corresponded.
Quoting from UNIX® Network Programming Volume 1, Third Edition: The Sockets Networking API by W.R Stevens.
21.10. Sending and Receiving
[...] We want the receiving socket to bind the multicast group and
port, say 239.255.1.2 port 8888. (Recall that we could just bind the
wildcard IP address and port 8888, but binding the multicast address
prevents the socket from receiving any other datagrams that might
arrive destined for port 8888.) We then want the receiving socket to
join the multicast group. The sending socket will send datagrams to
this same multicast address and port, say 239.255.1.2 port 8888.
Making an asynchronous task in Flask
You can also try using multiprocessing.Process
with daemon=True
; the process.start()
method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.
I experienced similar problem while working with falcon framework and using daemon
process helped.
You'd need to do the following:
from multiprocessing import Process
@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
...
heavy_process = Process( # Create a daemonic process with heavy "my_func"
target=my_func,
daemon=True
)
heavy_process.start()
return Response(
mimetype='application/json',
status=200
)
# Define some heavy function
def my_func():
time.sleep(10)
print("Process finished")
You should get a response immediately and, after 10s you should see a printed message in the console.
NOTE: Keep in mind that daemonic
processes are not allowed to spawn any child processes.
Java String new line
Example
System.out.printf("I %n am %n a %n boy");
Output
I
am
a
boy
Explanation
It's better to use %n
as an OS independent new-line character instead of \n
and it's easier than using System.lineSeparator()
Why to use %n
, because on each OS, new line refers to a different set of character(s);
Unix and modern Mac's : LF (\n)
Windows : CR LF (\r\n)
Older Macintosh Systems : CR (\r)
LF is the acronym of Line Feed and CR is the acronym of Carriage Return. The escape characters are written inside the parenthesis. So on each OS, new line stands for something specific to the system. %n
is OS agnostic, it is portable. It stands for \n
on Unix systems or \r\n
on Windows systems and so on. Thus, Do not use \n
, instead use %n
.
How to make a query with group_concat in sql server
Please run the below query, it doesn't requires STUFF and GROUP BY in your case:
Select
A.maskid
, A.maskname
, A.schoolid
, B.schoolname
, CAST((
SELECT T.maskdetail+','
FROM dbo.maskdetails T
WHERE A.maskid = T.maskid
FOR XML PATH(''))as varchar(max)) as maskdetail
FROM dbo.tblmask A
JOIN dbo.school B ON B.ID = A.schoolid
LEFT JOIN in LINQ to entities?
You can use this not only in entities but also store procedure or other data source:
var customer = (from cus in _billingCommonservice.BillingUnit.CustomerRepository.GetAll()
join man in _billingCommonservice.BillingUnit.FunctionRepository.ManagersCustomerValue()
on cus.CustomerID equals man.CustomerID
// start left join
into a
from b in a.DefaultIfEmpty(new DJBL_uspGetAllManagerCustomer_Result() )
select new { cus.MobileNo1,b.ActiveStatus });
Declaring an unsigned int in Java
We needed unsigned numbers to model MySQL's unsigned TINYINT
, SMALLINT
, INT
, BIGINT
in jOOQ, which is why we have created jOOU, a minimalistic library offering wrapper types for unsigned integer numbers in Java. Example:
import static org.joou.Unsigned.*;
// and then...
UByte b = ubyte(1);
UShort s = ushort(1);
UInteger i = uint(1);
ULong l = ulong(1);
All of these types extend java.lang.Number
and can be converted into higher-order primitive types and BigInteger
. Hope this helps.
(Disclaimer: I work for the company behind these libraries)
Struct memory layout in C
You can start by reading the data structure alignment wikipedia article to get a better understanding of data alignment.
From the wikipedia article:
Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
From 6.54.8 Structure-Packing Pragmas of the GCC documentation:
For compatibility with Microsoft
Windows compilers, GCC supports a set
of #pragma directives which change the
maximum alignment of members of
structures (other than zero-width
bitfields), unions, and classes
subsequently defined. The n value
below always is required to be a small
power of two and specifies the new
alignment in bytes.
#pragma pack(n)
simply sets the new alignment.
#pragma pack()
sets the alignment to the one that was in
effect when compilation started (see
also command line option
-fpack-struct[=] see Code Gen Options).
#pragma pack(push[,n])
pushes the current alignment setting on an
internal stack and then optionally
sets the new alignment.
#pragma pack(pop)
restores the alignment setting to the one saved at
the top of the internal stack (and
removes that stack entry). Note that
#pragma pack([n])
does not influence this internal stack; thus it is
possible to have #pragma pack(push)
followed by multiple #pragma pack(n)
instances and finalized by a single
#pragma pack(pop)
.
Some targets, e.g. i386 and powerpc,
support the ms_struct #pragma
which
lays out a structure as the documented
__attribute__ ((ms_struct))
.
#pragma ms_struct on
turns on the layout for structures declared.
#pragma ms_struct off
turns off the layout for structures declared.
#pragma ms_struct reset
goes back to the default layout.
Using dig to search for SPF records
I believe that I found the correct answer through this dig How To. I was able to look up the SPF records on a specific DNS, by using the following query:
dig @ns1.nameserver1.com domain.com txt
How to check variable type at runtime in Go language
It seems that Go have special form of switch dedicate to this (it is called type switch):
func (e *Easy)SetOption(option Option, param interface{}) {
switch v := param.(type) {
default:
fmt.Printf("unexpected type %T", v)
case uint64:
e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(v)))
case string:
e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(v)))
}
}
What to do with branch after merge
If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.
Save internal file in my own internal folder in Android
The answer of Mintir4 is fine, I would also do the following to load the file.
FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";
while ((s = r.readLine()) != null) {
txt += s;
}
r.close();
How to position absolute inside a div?
One of #a
or #b
needs to be not position:absolute
, so that #box
will grow to accommodate it.
So you can stop #a
from being position:absolute
, and still position #b
over the top of it, like this:
_x000D_
_x000D_
#box {_x000D_
background-color: #000;_x000D_
position: relative; _x000D_
padding: 10px;_x000D_
width: 220px;_x000D_
}_x000D_
_x000D_
.a {_x000D_
width: 210px;_x000D_
background-color: #fff;_x000D_
padding: 5px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
width: 100px; /* So you can see the other one */_x000D_
position: absolute;_x000D_
top: 10px; left: 10px;_x000D_
background-color: red;_x000D_
padding: 5px;_x000D_
}_x000D_
_x000D_
#after {_x000D_
background-color: yellow;_x000D_
padding: 10px;_x000D_
width: 220px;_x000D_
}
_x000D_
<div id="box">_x000D_
<div class="a">Lorem</div>_x000D_
<div class="b">Lorem</div>_x000D_
</div>_x000D_
<div id="after">Hello world</div>
_x000D_
_x000D_
_x000D_
(Note that I've made the widths different, so you can see one behind the other.)
Edit after Justine's comment: Then your only option is to specify the height of #box. This:
#box {
/* ... */
height: 30px;
}
works perfectly, assuming the heights of a and b are fixed. Note that you'll need to put IE into standards mode by adding a doctype at the top of your HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
before that works properly.
Why are there two ways to unstage a file in Git?
This thread is a bit old, but I still want to add a little demonstration since it is still not an intuitive problem:
me$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: to-be-added
# modified: to-be-modified
# deleted: to-be-removed
#
me$ git reset -q HEAD to-be-added
# ok
me$ git reset -q HEAD to-be-modified
# ok
me$ git reset -q HEAD to-be-removed
# ok
# or alternatively:
me$ git reset -q HEAD to-be-added to-be-removed to-be-modified
# ok
me$ git status
# On branch master
# Changes not staged for commit:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: to-be-modified
# deleted: to-be-removed
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# to-be-added
no changes added to commit (use "git add" and/or "git commit -a")
git reset HEAD
(without -q
) gives a warning about the modified file and its exit code is 1 which will be considered as an error in a script.
Edit: git checkout HEAD to-be-modified to-be-removed
also works for unstaging, but removes the change completely from the workspace
Update git 2.23.0: From time to time, the commands change. Now, git status
says:
(use "git restore --staged <file>..." to unstage)
... which works for all three types of change
Curly braces in string in PHP
Example:
$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";
Without curly braces PHP would try to find a variable named $numberth
, that doesn't exist!
Iterating through all nodes in XML file
You can use XmlDocument. Also some XPath can be useful.
Just a simple example
XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
// use node variable here for your beeds
}
Recursive sub folder search and return files in a list python
Your original solution was very nearly correct, but the variable "root" is dynamically updated as it recursively paths around. os.walk() is a recursive generator. Each tuple set of (root, subFolder, files) is for a specific root the way you have it setup.
i.e.
root = 'C:\\'
subFolder = ['Users', 'ProgramFiles', 'ProgramFiles (x86)', 'Windows', ...]
files = ['foo1.txt', 'foo2.txt', 'foo3.txt', ...]
root = 'C:\\Users\\'
subFolder = ['UserAccount1', 'UserAccount2', ...]
files = ['bar1.txt', 'bar2.txt', 'bar3.txt', ...]
...
I made a slight tweak to your code to print a full list.
import os
for root, subFolder, files in os.walk(PATH):
for item in files:
if item.endswith(".txt") :
fileNamePath = str(os.path.join(root,item))
print(fileNamePath)
Hope this helps!
EDIT: (based on feeback)
OP misunderstood/mislabeled the subFolder variable, as it is actually all the sub folders in "root". Because of this, OP, you're trying to do os.path.join(str, list, str), which probably doesn't work out like you expected.
To help add clarity, you could try this labeling scheme:
import os
for current_dir_path, current_subdirs, current_files in os.walk(RECURSIVE_ROOT):
for aFile in current_files:
if aFile.endswith(".txt") :
txt_file_path = str(os.path.join(current_dir_path, aFile))
print(txt_file_path)
How do I make a dictionary with multiple keys to one value?
If you're going to be adding to this dictionary frequently you'd want to take a class based approach, something similar to @Latty's answer in this SO question 2d-dictionary-with-many-keys-that-will-return-the-same-value.
However, if you have a static dictionary, and you need only access values by multiple keys then you could just go the very simple route of using two dictionaries. One to store the alias key association and one to store your actual data:
alias = {
'a': 'id1',
'b': 'id1',
'c': 'id2',
'd': 'id2'
}
dictionary = {
'id1': 1,
'id2': 2
}
dictionary[alias['a']]
If you need to add to the dictionary you could write a function like this for using both dictionaries:
def add(key, id, value=None)
if id in dictionary:
if key in alias:
# Do nothing
pass
else:
alias[key] = id
else:
dictionary[id] = value
alias[key] = id
add('e', 'id2')
add('f', 'id3', 3)
While this works, I think ultimately if you want to do something like this writing your own data structure is probably the way to go, though it could use a similar structure.
Javascript get Object property Name
Like the other answers you can do theTypeIs = Object.keys(myVar)[0];
to get the first key. If you are expecting more keys, you can use
Object.keys(myVar).forEach(function(k) {
if(k === "typeA") {
// do stuff
}
else if (k === "typeB") {
// do more stuff
}
else {
// do something
}
});
How do I delete files programmatically on Android?
I see you've found your answer, however it didn't work for me. Delete kept returning false, so I tried the following and it worked (For anybody else for whom the chosen answer didn't work):
System.out.println(new File(path).getAbsoluteFile().delete());
The System out can be ignored obviously, I put it for convenience of confirming the deletion.
How to provide user name and password when connecting to a network share
I liked Mark Brackett's answer so much that I did my own quick implementation. Here it is if anyone else needs it in a hurry:
public class NetworkConnection : IDisposable
{
string _networkName;
public NetworkConnection(string networkName,
NetworkCredential credentials)
{
_networkName = networkName;
var netResource = new NetResource()
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName
};
var userName = string.IsNullOrEmpty(credentials.Domain)
? credentials.UserName
: string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);
var result = WNetAddConnection2(
netResource,
credentials.Password,
userName,
0);
if (result != 0)
{
throw new Win32Exception(result);
}
}
~NetworkConnection()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
WNetCancelConnection2(_networkName, 0, true);
}
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(NetResource netResource,
string password, string username, int flags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string name, int flags,
bool force);
}
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public ResourceScope Scope;
public ResourceType ResourceType;
public ResourceDisplaytype DisplayType;
public int Usage;
public string LocalName;
public string RemoteName;
public string Comment;
public string Provider;
}
public enum ResourceScope : int
{
Connected = 1,
GlobalNetwork,
Remembered,
Recent,
Context
};
public enum ResourceType : int
{
Any = 0,
Disk = 1,
Print = 2,
Reserved = 8,
}
public enum ResourceDisplaytype : int
{
Generic = 0x0,
Domain = 0x01,
Server = 0x02,
Share = 0x03,
File = 0x04,
Group = 0x05,
Network = 0x06,
Root = 0x07,
Shareadmin = 0x08,
Directory = 0x09,
Tree = 0x0a,
Ndscontainer = 0x0b
}
MySQL Great Circle Distance (Haversine formula)
I have had to work this out in some detail, so I'll share my result. This uses a zip
table with latitude
and longitude
tables. It doesn't depend on Google Maps; rather you can adapt it to any table containing lat/long.
SELECT zip, primary_city,
latitude, longitude, distance_in_mi
FROM (
SELECT zip, primary_city, latitude, longitude,r,
(3963.17 * ACOS(COS(RADIANS(latpoint))
* COS(RADIANS(latitude))
* COS(RADIANS(longpoint) - RADIANS(longitude))
+ SIN(RADIANS(latpoint))
* SIN(RADIANS(latitude)))) AS distance_in_mi
FROM zip
JOIN (
SELECT 42.81 AS latpoint, -70.81 AS longpoint, 50.0 AS r
) AS p
WHERE latitude
BETWEEN latpoint - (r / 69)
AND latpoint + (r / 69)
AND longitude
BETWEEN longpoint - (r / (69 * COS(RADIANS(latpoint))))
AND longpoint + (r / (69 * COS(RADIANS(latpoint))))
) d
WHERE distance_in_mi <= r
ORDER BY distance_in_mi
LIMIT 30
Look at this line in the middle of that query:
SELECT 42.81 AS latpoint, -70.81 AS longpoint, 50.0 AS r
This searches for the 30 nearest entries in the zip
table within 50.0 miles of the lat/long point 42.81/-70.81 . When you build this into an app, that's where you put your own point and search radius.
If you want to work in kilometers rather than miles, change 69
to 111.045
and change 3963.17
to 6378.10
in the query.
Here's a detailed writeup. I hope it helps somebody. http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/
HttpRequest maximum allowable size in tomcat?
The full answer
1. The default (fresh install of tomcat)
When you download tomcat from their official website (of today that's tomcat version 9.0.26), all the apps you installed to tomcat can handle HTTP requests of unlimited size, given that the apps themselves do not have any limits on request size.
However, when you try to upload an app in tomcat's manager app, that app has a default war file limit of 50MB. If you're trying to install Jenkins for example which is 77 MB as ot today, it will fail.
2. Configure tomcat's per port http request size limit
Tomcat itself has size limit for each port, and this is defined in conf\server.xml
. This is controlled by maxPostSize
attribute of each Connector
(port). If this attribute does not exist, which it is by default, there is no limit on the request size.
To add a limit to a specific port, set a byte size for the attribute. For example, the below config for the default 8080 port limits request size to 200 MB. This means that all the apps installed under port 8080 now has the size limit of 200MB
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxPostSize="209715200" />
3. Configure app level size limit
After passing the port level size limit, you can still configure app level limit. This also means that app level limit should be less than port level limit. The limit can be done through annotation within each servlet, or in the web.xml file. Again, if this is not set at all, there is no limit on request size.
To set limit through java annotation
@WebServlet("/uploadFiles")
@MultipartConfig( fileSizeThreshold = 0, maxFileSize = 209715200, maxRequestSize = 209715200)
public class FileUploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// ...
}
}
To set limit through web.xml
<web-app>
...
<servlet>
...
<multipart-config>
<file-size-threshold>0</file-size-threshold>
<max-file-size>209715200</max-file-size>
<max-request-size>209715200</max-request-size>
</multipart-config>
...
</servlet>
...
</web-app>
4. Appendix - If you see file upload size error when trying to install app through Tomcat's Manager app
Tomcat's Manager app (by default localhost:8080/manager) is nothing but a default web app. By default that app has a web.xml
configuration of request limit of 50MB. To install (upload) app with size greater than 50MB through this manager app, you have to change the limit. Open the manager app's web.xml file from webapps\manager\WEB-INF\web.xml
and follow the above guide to change the size limit and finally restart tomcat.
port forwarding in windows
nginx is useful for forwarding HTTP on many platforms including Windows. It's easy to setup and extend with more advanced configuration. A basic configuration could look something like this:
events {}
http {
server {
listen 192.168.1.111:4422;
location / {
proxy_pass http://192.168.2.33:80/;
}
}
}
Delete files older than 3 months old in a directory using .NET
I use the following in a console app, running as a service, to get directory info from the App.Settings file. Number of days to keep the files is also configurable, multiplied by -1 for use in the AddDays() method of DateTime.Now.
static void CleanBackupFiles()
{
string gstrUncFolder = ConfigurationManager.AppSettings["DropFolderUNC"] + "";
int iDelAge = Convert.ToInt32(ConfigurationManager.AppSettings["NumDaysToKeepFiles"]) * -1;
string backupdir = string.Concat(@"\", "Backup", @"\");
string[] files = Directory.GetFiles(string.Concat(gstrUncFolder, backupdir));
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi.CreationTime < DateTime.Now.AddDays(iDelAge))
{
fi.Delete();
}
}
}
get Context in non-Activity class
If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:
class YourNonActivityClass{
// variable to hold context
private Context context;
//save the context recievied via constructor in a local variable
public YourNonActivityClass(Context context){
this.context=context;
}
}
You can create instance of this class from the activity as follows:
new YourNonActivityClass(this);
How can I fix the Microsoft Visual Studio error: "package did not load correctly"?
I had a similar problem.
After checking ActivityLog.xml and it said that it could not create an instance for the Extension/package name from a specific folder. I traced that path and I didn't find that folder it is looking for.
So I installed the extension again, I looked for the dll, and copied the containing folder contents to the folder Visual Studio is looking for.
So to recap:
- Check if the folder in the error exists
- If not, create a new folder with the same name
- Look for the dll in the error in the Visual Studio folder, if not found, install the extension again
- If the error resists, search inside the Visual Studio folder in Program Files (x86) for the dll and open the containing folder
- Copy all the contents
- Paste inside the new folder you have created with the name mentioned inside the ActivityLog.xml
SQL Server using wildcard within IN
I firstly added one off static table with ALL possibilities of my wildcard results
(this company has a 4 character nvarchar code as their localities and they wildcard their locals)
i.e. they may have 456? which would give them 456[1] to 456[Z] i.e 0-9 & a-z
I had to write a script to pull the current user (declare them) and pull the masks for the declared user.
Create some temporary tables just basic ones to rank the row numbers for this current user
loop through each result (YOUR Or this Or that etc...)
Insert into the test Table.
Here is the script I used:
Drop Table #UserMasks
Drop Table #TESTUserMasks
Create Table #TESTUserMasks (
[User] [Int] NOT NULL,
[Mask] [Nvarchar](10) NOT NULL)
Create Table #UserMasks (
[RN] [Int] NOT NULL,
[Mask] [Nvarchar](10) NOT NULL)
DECLARE @User INT
SET @User = 74054
Insert Into #UserMasks
select ROW_NUMBER() OVER ( PARTITION BY ProntoUserID ORDER BY Id DESC) AS RN,
REPLACE(mask,'?','') Mask
from dbo.Access_Masks
where prontouserid = @User
DECLARE @TopFlag INT
SET @TopFlag = 1
WHILE (@TopFlag <=(select COUNT(*) from #UserMasks))
BEGIN
Insert Into #TestUserMasks
select (@User),Code from dbo.MaskArrayLookupTable
where code like (select Mask + '%' from #UserMasks Where RN = @TopFlag)
SET @TopFlag = @TopFlag + 1
END
GO
select * from #TESTUserMasks
Angular 2 Sibling Component Communication
Shared service is a good solution for this issue. If you want to store some activity information too, you can add Shared Service to your main modules (app.module) provider list.
@NgModule({
imports: [
...
],
bootstrap: [
AppComponent
],
declarations: [
AppComponent,
],
providers: [
SharedService,
...
]
});
Then you can directly provide it to your components,
constructor(private sharedService: SharedService)
With Shared Service you can either use functions or you can create a Subject to update multiple places at once.
@Injectable()
export class SharedService {
public clickedItemInformation: Subject<string> = new Subject();
}
In your list component you can publish clicked item information,
this.sharedService.clikedItemInformation.next("something");
and then you can fetch this information at your detail component:
this.sharedService.clikedItemInformation.subscribe((information) => {
// do something
});
Obviously, the data that list component shares can be anything. Hope this helps.
Eclipse : Maven search dependencies doesn't work
Eclipse artifact searching depends on repository's index file. It seems you did not download the index file.
Go to Window -> Prefrences -> Maven and check "Download repository index updates on start". Restart Eclipse and then look at the progress view. An index file should be downloading.
After downloading completely, artifact searching will be ready to use.
UPDATE
You also need to rebuild your Maven repository index in 'maven repository view'.
In this view , open 'Global Repositories', right-click 'central', check 'Full Index Enable',
and then, click 'Rebuild Index' in the same menu.
A 66M index file will be downloaded.
Select by partial string from a pandas DataFrame
There are answers before this which accomplish the asked feature, anyway I would like to show the most generally way:
df.filter(regex=".*STRING_YOU_LOOK_FOR.*")
This way let's you get the column you look for whatever the way is wrote.
( Obviusly, you have to write the proper regex expression for each case )
sql how to cast a select query
I interpreted the question as using cast on a subquery. Yes, you can do that:
select cast((<subquery>) as <newtype>)
If you do so, then you need to be sure that the returns one row and one value. And, since it returns one value, you could put the cast in the subquery instead:
select (select cast(<val> as <newtype>) . . .)
Convert JS date time to MySQL datetime
While JS does possess enough basic tools to do this, it's pretty clunky.
/**
* You first need to create a formatting function to pad numbers to two digits…
**/
function twoDigits(d) {
if(0 <= d && d < 10) return "0" + d.toString();
if(-10 < d && d < 0) return "-0" + (-1*d).toString();
return d.toString();
}
/**
* …and then create the method to output the date string as desired.
* Some people hate using prototypes this way, but if you are going
* to apply this to more than one Date object, having it as a prototype
* makes sense.
**/
Date.prototype.toMysqlFormat = function() {
return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};
Retrieving Property name from lambda expression
I created an extension method on ObjectStateEntry to be able to flag properties (of Entity Framework POCO classes) as modified in a type safe manner, since the default method only accepts a string. Here's my way of getting the name from the property:
public static void SetModifiedProperty<T>(this System.Data.Objects.ObjectStateEntry state, Expression<Func<T>> action)
{
var body = (MemberExpression)action.Body;
string propertyName = body.Member.Name;
state.SetModifiedProperty(propertyName);
}
Sort Dictionary by keys
For Swift 3, the following sort returnes sorted dictionary by keys:
let unsortedDictionary = ["4": "four", "2": "two", "1": "one", "3": "three"]
let sortedDictionary = unsortedDictionary.sorted(by: { $0.0.key < $0.1.key })
print(sortedDictionary)
// ["1": "one", "2": "two", "3": "three", "4": "four"]
write a shell script to ssh to a remote machine and execute commands
There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?
You can do this with ssh, for example:
#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done
When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.
You can add the StrictHostKeyChecking=no
option to ssh:
ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls"
This will disable the host key check and automatically add the host key to the list of known hosts. If you do not want to have the host added to the known hosts file, add the option -o UserKnownHostsFile=/dev/null
.
Note that this disables certain security checks, for example protection against man-in-the-middle attack. It should therefore not be applied in a security sensitive environment.
exit application when click button - iOS
You can use exit method to quit an ios app :
exit(0);
You should say same alert message and ask him to quit
Another way is by using [[NSThread mainThread] exit]
However you should not do this way
According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.
How to deploy a war file in Tomcat 7
This has been working for me:
- Create your war file (mysite.war) locally.
- Rename it locally to something besides .war, like mysite.www
- With tomcat still running, upload mysite.www to webapps directory.
- After it finishes uploading, delete the previous version mysite.war
- List the directory, watching for the directory /mysite to disappear.
- Rename mysite.www to be mysite.war
- List the directory, watching for the new /mysite to be created.
If you try uploading the new file as a war file, with tomcat still running, it will attempt to expand it before it is all there. It will fail. Having failed, it will not try again. Thus, uploading a www file, then renaming it, allows the whole war file to be present before tomcat notices it.
Hint, don't forget to check that the war file's owner is tomcat (Use chown)
slideToggle JQuery right to left
I would suggest you use the below css
.showhideoverlay {
width: 100%;
height: 100%;
right: 0px;
top: 0px;
position: fixed;
background: #000;
opacity: 0.75;
}
You can then use a simple toggle function:
$('a.open').click(function() {
$('div.showhideoverlay').toggle("slow");
});
This will display the overlay menu from right to left. Alternatively, you can use the positioning for changing the effect from top or bottom, i.e. use bottom: 0;
instead of top: 0;
- you will see menu sliding from right-bottom corner.
How to use glOrtho() in OpenGL?
glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:
OpenGL documentation (my bold)
The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).
The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:
Parallel projections have lines of projection that are parallel both in reality and in the projection plane.
Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".
Difference between SelectedItem, SelectedValue and SelectedValuePath
Every control that uses Collections to store data have SelectedValue, SelectedItem property. Examples of these controls are ListBox, Dropdown, RadioButtonList, CheckBoxList.
To be more specific if you literally want to retrieve Text of Selected Item then you can write:
ListBox1.SelectedItem.Text;
Your ListBox1 can also return Text using SelectedValue property if value has set to that before. But above is more effective way to get text.
Now, the value is something that is not visible to user but it is used mostly to store in database. We don't insert Text of ListBox1, however we can insert it also, but we used to insert value of selected item. To get value we can use
ListBox1.SelectedValue
Source
Use table row coloring for cells in Bootstrap
You can override the default css rules with this:
.table tbody tr > td.success {
background-color: #dff0d8 !important;
}
.table tbody tr > td.error {
background-color: #f2dede !important;
}
.table tbody tr > td.warning {
background-color: #fcf8e3 !important;
}
.table tbody tr > td.info {
background-color: #d9edf7 !important;
}
.table-hover tbody tr:hover > td.success {
background-color: #d0e9c6 !important;
}
.table-hover tbody tr:hover > td.error {
background-color: #ebcccc !important;
}
.table-hover tbody tr:hover > td.warning {
background-color: #faf2cc !important;
}
.table-hover tbody tr:hover > td.info {
background-color: #c4e3f3 !important;
}
!important
is needed as bootstrap actually colours the cells individually (afaik it's not possible to just apply background-color to a tr). I couldn't find any colour variables in my version of bootstrap but that's the basic idea anyway.
How to generate a random string of 20 characters
You may use the class java.util.Random with method
char c = (char)(rnd.nextInt(128-32))+32
20x to get Bytes, which you interpret as ASCII. If you're fine with ASCII.
32 is the offset, from where the characters are printable in general.
PHP - Copy image to my server direct from URL
$url = "http://www.example/images/image.gif";
$save_name = "image.gif";
$save_directory = "/var/www/example/downloads/";
if(is_writable($save_directory)) {
file_put_contents($save_directory . $save_name, file_get_contents($url));
} else {
exit("Failed to write to directory "{$save_directory}");
}
How do I check if a Sql server string is null or empty
Here's a solution, but I don't know if it's the best....
Select
Coalesce(Case When Len(listing.Offer_Text) = 0 Then Null Else listing.Offer_Text End, company.Offer_Text, '') As Offer_Text,
from tbl_directorylisting listing
Inner Join tbl_companymaster company
On listing.company_id= company.company_id
sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()
during train test split you might have done a mistake
x_train,x_test,y_train,y_test=sklearn.model_selection.train_test_split(X,Y,test_size)
The above code is correct
You might have done like below which is wrong
x_train,y_train,x_test,y_test=sklearn.model_selection.train_test_split(X,Y,test_size)
Scale an equation to fit exact page width
I just had the situation that I wanted this only for lines exceeding \linewidth
, that is: Squeezing long lines slightly.
Since it took me hours to figure this out, I would like to add it here.
I want to emphasize that scaling fonts in LaTeX is a deadly sin!
In nearly every situation, there is a better way (e.g. multline
of the mathtools
package). So use it conscious.
In this particular case, I had no influence on the code base apart the preamble and some lines slightly overshooting the page border when I compiled it as an eBook-scaled pdf.
\usepackage{environ} % provides \BODY
\usepackage{etoolbox} % provides \ifdimcomp
\usepackage{graphicx} % provides \resizebox
\newlength{\myl}
\let\origequation=\equation
\let\origendequation=\endequation
\RenewEnviron{equation}{
\settowidth{\myl}{$\BODY$} % calculate width and save as \myl
\origequation
\ifdimcomp{\the\linewidth}{>}{\the\myl}
{\ensuremath{\BODY}} % True
{\resizebox{\linewidth}{!}{\ensuremath{\BODY}}} % False
\origendequation
}
Before
After
Laravel Password & Password_Confirmation Validation
I have used in this way. Its Working fine!
$rules = [
'password' => [
'required',
'string',
'min:6',
'max:12', // must be at least 8 characters in length
],
'confirm_password' => 'required|same:password|min:6'
];