Programs & Examples On #Srs

SRS stands for Software Requirement Specification which is a complete document specifying functionality of the software being developed along with its use cases.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.

Example python implementation:

import sys

inner_loop = 0

def collatz_sequence(N, cache):
    global inner_loop

    l = [ ]
    stop = False
    n = N

    tails = [ ]

    while not stop:
        inner_loop += 1
        tmp = n
        l.append(n)
        if n <= 1:
            stop = True  
        elif n in cache:
            stop = True
        elif n % 2:
            n = 3*n + 1
        else:
            n = n // 2
        tails.append((tmp, len(l)))

    for key, offset in tails:
        if not key in cache:
            cache[key] = l[offset:]

    return l

def gen_sequence(l, cache):
    for elem in l:
        yield elem
        if elem in cache:
            yield from gen_sequence(cache[elem], cache)
            raise StopIteration

if __name__ == "__main__":
    le_cache = {}

    for n in range(1, 4711, 5):
        l = collatz_sequence(n, le_cache)
        print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))

    print("inner_loop = {}".format(inner_loop))

Forward X11 failed: Network error: Connection refused

PuTTY can't find where your X server is, because you didn't tell it. (ssh on Linux doesn't have this problem because it runs under X so it just uses that one.) Fill in the blank box after "X display location" with your Xming server's address.

Alternatively, try MobaXterm. It has an X server builtin.

How to fire an event when v-model changes?

Just to add to the correct answer above, in Vue.JS v1.0 you can write

<a v-on:click="doSomething">

So in this example it would be

 v-on:change="foo"

See: http://v1.vuejs.org/guide/syntax.html#Arguments

resize2fs: Bad magic number in super-block while trying to open

os: rhel7

After gparted, # xfs_growfs /dev/mapper/rhel-root did the trick on a living system.

$ df -h
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/rhel-root   47G   47G   20M 100% /
devtmpfs               1.9G     0  1.9G   0% /dev
tmpfs                  1.9G     0  1.9G   0% /dev/shm
tmpfs                  1.9G  9.3M  1.9G   1% /run
tmpfs                  1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/sda1             1014M  205M  810M  21% /boot
tmpfs                  379M  8.0K  379M   1% /run/user/42
tmpfs                  379M     0  379M   0% /run/user/1000


# lvresize -l +100%FREE /dev/mapper/rhel-root
  Size of logical volume rhel/root changed from <47.00 GiB (12031 extents) to <77.00 GiB (19711 extents).
  Logical volume rhel/root successfully resized.


# xfs_growfs /dev/mapper/rhel-root
meta-data=/dev/mapper/rhel-root  isize=512    agcount=7, agsize=1900032 blks
         =                       sectsz=512   attr=2, projid32bit=1
         =                       crc=1        finobt=0 spinodes=0
data     =                       bsize=4096   blocks=12319744, imaxpct=25
         =                       sunit=0      swidth=0 blks
naming   =version 2              bsize=4096   ascii-ci=0 ftype=1
log      =internal               bsize=4096   blocks=3711, version=2
         =                       sectsz=512   sunit=0 blks, lazy-count=1
realtime =none                   extsz=4096   blocks=0, rtextents=0
data blocks changed from 12319744 to 20184064


# df -h
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/rhel-root   77G   47G   31G  62% /
devtmpfs               1.9G     0  1.9G   0% /dev
tmpfs                  1.9G     0  1.9G   0% /dev/shm
tmpfs                  1.9G  9.3M  1.9G   1% /run
tmpfs                  1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/sda1             1014M  205M  810M  21% /boot
tmpfs                  379M  8.0K  379M   1% /run/user/42
tmpfs                  379M     0  379M   0% /run/user/1000

How to use multiple conditions (With AND) in IIF expressions in ssrs

Could you try this out?

=IIF((Fields!OpeningStock.Value=0) AND (Fields!GrossDispatched.Value=0) AND 
(Fields!TransferOutToMW.Value=0) AND (Fields!TransferOutToDW.Value=0) AND 
(Fields!TransferOutToOW.Value=0) AND (Fields!NetDispatched.Value=0) AND (Fields!QtySold.Value=0) 
AND (Fields!StockAdjustment.Value=0) AND (Fields!ClosingStock.Value=0),True,False)

Note: Setting Hidden to False will make the row visible

Line break in SSRS expression

This works for me:

(In Visual Studio)

  1. Open the .rdl file in Designer (right-click on file in Solution Explorer > View Designer)
  2. Right-click on the Textbox you are working with, choose Expression
  3. In the Set expression for: Value box enter your expression like:

    ="first line of text. Param1 value: " & Parameters!Param1.Value & Environment.NewLine() 
    & "second line of text. Field value: " & Fields!Field1.Value & Environment.NewLine() 
    & "third line of text."
    

Jenkins: Failed to connect to repository

Not mentionned here so far, but this can come also from stash. We encountered the same issue, the root cause for our problem was that the stash instance we use for jenkins did crash. Restarting stash solved it in our case.

SSRS expression to format two decimal places does not show zeros

Actually, I needed the following...get rid of the decimals without rounding so "12.23" needs to show as "12". In SSRS, do not format the number as a percent. Leave the formatting as default (no formatting applied) then in the expression do the following: =Fix(Fields!PctAmt.Value*100))

Multiply the number by 100 then apply the FIX function in SSRS which returns only the integer portion of a number.

Disable password authentication for SSH

The one-liner to disable SSH password authentication:

sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config && service ssh restart

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

IIS - 401.3 - Unauthorized

Since you're dealing with static content...

On the folder that acts as the root of your website- if you right click > properties > security, does "Users" show up in the list? if not click "Add..." and type it in, be sure to click "Apply" when you're done.

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

Add column to SQL query results

why dont you add a "source" column to each of the queries with a static value like

select 'source 1' as Source, column1, column2...
from table1

UNION ALL

select 'source 2' as Source, column1, column2...
from table2

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

in my case: 1. in IIS Manager, in left tree, left click the computer name, in right dialog click ISAPI and CGT limitation, in open dialog, select ASP.NET v4.0.30319 and select enable. There is two ASP.Net v4.0, one for 32bit, another for 64 bit. select depending on your OS bit. 2. in left tree select app pool, in right dialog, select the app pool your website used. double click that pool, in open dialog, .net framke item select .net framework v.4.0.30319. and pipe..item select integate. Maybe there is some wrong translation above because my OS is not English version.

How do I format date and time on ssrs report?

If the date and time is in its own cell (aka textbox), then you should look at applying the format to the entire textbox. This will create cleaner exports to other formats; in particular, the value will export as a datetime value to Excel instead of a string.

Use the properties pane or dialog to set the format for the textbox to "MM/dd/yyyy hh:mm tt"

I would only use Ian's answer if the datetime is being concatenated with another string.

How do I display todays date on SSRS report?

to display date and time, try this:

=Format(Now(), "dd/MM/yyyy hh:mm tt")

How to combine results of two queries into a single dataset

The problem is that unless your tables are related you can't determine how to join them, so you'd have to arbitrarily join them, resulting in a cartesian product:

select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
cross join Table2

If you had, for example, the following data:

col1  col2
a     1
b     2

col3  col4
y     98
z     99

You would end up with the following:

col1  col2  col3  col4
a     1     y     98
a     1     z     99
b     2     y     98
b     2     z     99

Is this what you're looking for? If not, and you have some means of relating the tables, then you'd need to include that in joining the two tables together, e.g.:

select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
inner join Table2
on Table1.JoiningField = Table2.JoiningField

That would pull things together for you into however the data is related, giving you your result.

IIS_IUSRS and IUSR permissions in IIS8

IIS_IUSRS group has prominence only if you are using ApplicationPool Identity. Even though you have this group looks empty at run time IIS adds to this group to run a worker process according to microsoft literature.

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

The issue is because your data source is not setup properly, to do that please verify your data source connection, in order to do that first navigate to Report Service Configuration Manager through

clicking on the start -> Start All -> Microsoft SQL Server ->Configuration Tool -> “Report Service Configuration Manager”

The open Report Manager URL and then navigate to the Data Source folder, see in the picture below

Then Create a Data Source or configure the one that is already there by right click on your database source and select "Manage" as is shown below

Now on the properties tab, on your left menu, fill out the data source with your connection string and username and password, after that click on test connection, and if the connection was successful, then click "Apply"

Navigate to the folder that contains your report in this case "SurveyLevelReport"

And Finally set your Report to the Data Source that you set up previously, and click Apply

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

I just got this error and i came to know that it is about the local variable alias

at the end of the stored procedure i had like

select @localvariable1,@localvariable2

it was working fine in sql but when i ran this in ssrs it was always throwing error but after I gave alias it is fixed

select @localvariable1 as A,@localvariable2 as B

SSRS custom number format

You can use

 =Format(Fields!myField.Value,"F2") 

How to pass multiple values to single parameter in stored procedure

This can not be done easily. There's no way to make an NVARCHAR parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.

Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:

CREATE TABLE #TempTable (ID INT)
WHILE LEN(@PortfolioID) > 0
BEGIN
    IF NOT <@PortfolioID contains Comma>
    BEGIN
        INSERT INTO #TempTable VALUES CAST(@PortfolioID as INT)
        SET @PortfolioID = ''
    END ELSE
    BEGIN
         INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
         SET @PortfolioID = <Everything after the next comma>
    END
END

Then, change your condition to

WHERE PortfolioId IN (SELECT ID FROM #TempTable)

EDIT
You may be interested in the documentation for multi value parameters in SSRS, which states:

You can define a multivalue parameter for any report parameter that you create. However, if you want to pass multiple parameter values back to a data source by using the query, the following requirements must be satisfied:

The data source must be SQL Server, Oracle, Analysis Services, SAP BI NetWeaver, or Hyperion Essbase.

The data source cannot be a stored procedure. Reporting Services does not support passing a multivalue parameter array to a stored procedure.

The query must use an IN clause to specify the parameter.

This I found here.

HTTP Error 503, the service is unavailable

After some try and error I found out, that the app pool was configured to use my domain account as identity and I remembered that I changed the password of my domain account shorty before. Resetting the application pool’s identity (using my new password) fixed the problem and the app pool could be restarted without any problems.

Right pad a string with variable number of spaces

The easiest way to right pad a string with spaces (without them being trimmed) is to simply cast the string as CHAR(length). MSSQL will sometimes trim whitespace from VARCHAR (because it is a VARiable-length data type). Since CHAR is a fixed length datatype, SQL Server will never trim the trailing spaces, and will automatically pad strings that are shorter than its length with spaces. Try the following code snippet for example.

SELECT CAST('Test' AS CHAR(20))

This returns the value 'Test '.

SSRS Query execution failed for dataset

In addition to the above answers, it could be due to a missing SQL stored-procedure or SQL function. For example, this could be due to the function not migrating from a non-prod region to the production (prod) region.

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

Try to go back to the internet information services, right clink on the intranet you created and select edit permission.

When the wwwroot pop up windows open, select the sharing tab and click "share" on the drop down menu select the users and their permission level or just select everyone and for permission read and Right

SSRS chart does not show all labels on Horizontal axis

Go to Horizontal axis properties,choose 'Category' in AXIS type,choose "Disabled" in SIDE Margin option

Create Log File in Powershell

You might just want to use the new TUN.Logging PowerShell module, this can also send a log mail. Just use the Start-Log and/or Start-MailLog cmdlets to start logging and then just use Write-HostLog, Write-WarningLog, Write-VerboseLog, Write-ErrorLog etc. to write to console and log file/mail. Then call Send-Log and/or Stop-Log at the end and voila, you got your logging. Just install it from the PowerShell Gallery via

Install-Module -Name TUN.Logging

Or just follow the link: https://www.powershellgallery.com/packages/TUN.Logging

Documentation of the module can be found here: https://github.com/echalone/TUN/blob/master/PowerShell/Modules/TUN.Logging/TUN.Logging.md

How do I set the visibility of a text box in SSRS using an expression?

the rdl file content:

<Visibility><Hidden>=Parameters!casetype.Value=300</Hidden></Visibility>

so the text box will hidden, if your expression is true.

SSRS the definition of the report is invalid

A very cryptic message for what my issue was.

I had changed the names of the parameters, but did not update these names in the dataset.

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

The solution provided by Emanuele worked for me. I could see the report when I accessed it directly from the server but when I used a ReportViewer control on my aspx page, I was unable to see the report. Upon inspecting the rendered HTML, I found a div by the id "ReportViewerGeneral_ctl09" (ReportViewerGeneral is the server id of the report viewer control) which had it's overflow property set to auto.

<div id="ReportViewerGeneral_ctl09" style="height: 100%; width: 100%; overflow: auto; position: relative; ">...</div>

I used the procedure explained by Emanuele to change this to visible as follows:

function pageLoad() {
    var element = document.getElementById("ReportViewerGeneral_ctl09");

    if (element) {
        element.style.overflow = "visible";
    }
}

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

Cannot read configuration file due to insufficient permissions

I had this same issue and none of these solutions worked for me. I kept getting the same error and one about "Failed to start monitoring changes" in the event viewer.

The only thing that worked was to copy the folder and rename it back. It must have been a corrupted folder in Windows that IIS/ASP.NET could not access.

IIS AppPoolIdentity and file system write access permissions

  1. Right click on folder.

  2. Click Properties

  3. Click Security Tab. You will see something like this:

enter image description here

  1. Click "Edit..." button in above screen. You will see something like this:

enter image description here

  1. Click "Add..." button in above screen. You will see something like this:

enter image description here

  1. Click "Locations..." button in above screen. You will see something like this. Now, go to the very of top of this tree structure and select your computer name, then click OK.

enter image description here

  1. Now type "iis apppool\your_apppool_name" and click "Check Names" button. If the apppool exists, you will see your apppool name in the textbox with underline in it. Click OK button.

enter image description here

  1. Check/uncheck whatever access you need to grant to the account

  2. Click Apply button and then OK.

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

SSRS Field Expression to change the background color of the Cell

=IIF(Fields!Column.Value = "Approved", "Green", "No Color")

Access to the path is denied

  1. Change the setting from built-in account to custom account and enter the other server's username and password.

  2. Keep the setting as integrated (instead of classic mode).

Transform only one axis to log10 scale with ggplot2

I think I got it at last by doing some manual transformations with the data before visualization:

d <- diamonds
# computing logarithm of prices
d$price <- log10(d$price)

And work out a formatter to later compute 'back' the logarithmic data:

formatBack <- function(x) 10^x 
# or with special formatter (here: "dollar")
formatBack <- function(x) paste(round(10^x, 2), "$", sep=' ') 

And draw the plot with given formatter:

m <- ggplot(d, aes(y = price, x = color))
m + geom_boxplot() + scale_y_continuous(formatter='formatBack')

alt text

Sorry to the community to bother you with a question I could have solved before! The funny part is: I was working hard to make this plot work a month ago but did not succeed. After asking here, I got it.

Anyway, thanks to @DWin for motivation!

Empty or Null value display in SSRS text boxes

I would disagree with converting it on the server side. If you do that it's going to come back as a string type rather than a date type with all that entails (it will sort as a string for example)

My principle when dealing with dates is to keep them typed as a date for as long as you possibly can.

If your facing a performance bottleneck on the report server there are better ways to handle it than compromising your logic.

Reporting Services permissions on SQL Server R2 SSRS

In my case after running IE as an administrator, i had to add the url of the report manager to the Local Internet Zones in Internet Explorer, not Trusted Sites.

Which tool to build a simple web front-end to my database

The most rapid option is to hand out MS Access or SQL Sever Management Studio (there's a free express edition) along with a read only account.

PHP is simple and has a well earned reputation for getting stuff done. PHP is excellent for copying and pasting code, and you can iterate insanely fast in PHP. PHP can lead to hard-to-maintain applications, and it can be difficult to set up a visual debugger.

Given that you use SQL Server, ASP.NET is also a good option. This is somewhat harder to setup; you'll need an IIS server, with a configured application. Iterations are a bit slower. ASP.NET is easier to maintain and Visual Studio is the best visual debugger around.

How to give ASP.NET access to a private key in a certificate in the certificate store?

Complementing the answers this is a guide to find the private key of the certificate and add the permissions.

This is the guide to get FindPrivateKey.exe found in the guide for find the private key of the certificate.

IIS7 folder permissions for web application

If it's any help to anyone, give permission to "IIS_IUSRS" group.

Note that if you can't find "IIS_IUSRS", try prepending it with your server's name, like "MySexyServer\IIS_IUSRS".

SSRS - Checking whether the data is null

Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).

Either way works, I like to put that logic in the query so the report has to do less.

Fast query runs slow in SSRS

I had the same scenario occuring..Very basic report, the SP (which only takes in 1 param) was taking 5 seconds to bring back 10K records, yet the report would take 6 minutes to run. According to profiler and the RS ExecutionLogStorage table, the report was spending all it's time on the query. Brian S.'s comment led me to the solution..I simply added WITH RECOMPILE before the AS statement in the SP, and now the report time pretty much matches the SP execution time.

T-SQL Format integer to 2-digit string

You can use T-SQL's built in format function:

declare @number int  = 1
select format (@number, '0#')

Parsing XML in Python using ElementTree example

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

When to use RDLC over RDL reports?

If we have fewer number of reports which are less complex and consumed by asp.net web pages. It's better to go with rdlc,reason is we can avoid maintaing reports on RS instance. but we have to fetch the data from DB manually and bind it to rdlc.

Cons:designing rdlc in visual studio is little difficult compared to SSrs designer.

Pro:Maintenance is easy. while exporting the report from we page,observed that performance gain compared to server side reports.

Passing parameter via url to sql server reporting service

Try changing "Reports" to "ReportServer" in your url. For that just access this http://host/ReportServer/ and from there you can go to the report pages. There append your parmaters like this &<parameter>=<value>

For more detailed information:

http://dobrzanski.net/2008/08/11/reporting-services-problem-with-passing-parameters-directly-in-the-url/

https://www.mssqltips.com/sqlservertip/1336/pass-parameters-and-options-with-a-url-in-sql-reporting-services/

How to programmatically modify WCF app.config endpoint address setting?

Is this on the client side of things??

If so, you need to create an instance of WsHttpBinding, and an EndpointAddress, and then pass those two to the proxy client constructor that takes these two as parameters.

// using System.ServiceModel;
WSHttpBinding binding = new WSHttpBinding();
EndpointAddress endpoint = new EndpointAddress(new Uri("http://localhost:9000/MyService"));

MyServiceClient client = new MyServiceClient(binding, endpoint);

If it's on the server side of things, you'll need to programmatically create your own instance of ServiceHost, and add the appropriate service endpoints to it.

ServiceHost svcHost = new ServiceHost(typeof(MyService), null);

svcHost.AddServiceEndpoint(typeof(IMyService), 
                           new WSHttpBinding(), 
                           "http://localhost:9000/MyService");

Of course you can have multiple of those service endpoints added to your service host. Once you're done, you need to open the service host by calling the .Open() method.

If you want to be able to dynamically - at runtime - pick which configuration to use, you could define multiple configurations, each with a unique name, and then call the appropriate constructor (for your service host, or your proxy client) with the configuration name you wish to use.

E.g. you could easily have:

<endpoint address="http://mydomain/MyService.svc"
        binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IASRService"
        contract="ASRService.IASRService" 
        name="WSHttpBinding_IASRService">
        <identity>
            <dns value="localhost" />
        </identity>
</endpoint>

<endpoint address="https://mydomain/MyService2.svc"
        binding="wsHttpBinding" bindingConfiguration="SecureHttpBinding_IASRService"
        contract="ASRService.IASRService" 
        name="SecureWSHttpBinding_IASRService">
        <identity>
            <dns value="localhost" />
        </identity>
</endpoint>

<endpoint address="net.tcp://mydomain/MyService3.svc"
        binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IASRService"
        contract="ASRService.IASRService" 
        name="NetTcpBinding_IASRService">
        <identity>
            <dns value="localhost" />
        </identity>
</endpoint>

(three different names, different parameters by specifying different bindingConfigurations) and then just pick the right one to instantiate your server (or client proxy).

But in both cases - server and client - you have to pick before actually creating the service host or the proxy client. Once created, these are immutable - you cannot tweak them once they're up and running.

Marc

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

As mentioned, you can use:

=Format(Fields!Price.Value, "C")

A digit after the "C" will specify precision:

=Format(Fields!Price.Value, "C0")
=Format(Fields!Price.Value, "C1")

You can also use Excel-style masks like this:

=Format(Fields!Price.Value, "#,##0.00")

Haven't tested the last one, but there's the idea. Also works with dates:

=Format(Fields!Date.Value, "yyyy-MM-dd")

How to get named excel sheets while exporting from SSRS

The Rectangle method

The simplest and most reliable way I've found of achieving worksheets/page-breaks is with use of the rectangle tool.

Group your page within rectangles or a single rectangle that fills the page in a sub-report, as follows:

  • The quickest way I've found of placing the rectangle is to draw it around the objects you wish to place in the rectangle.

  • Right click and in the layout menu, send the rectangle to back.

  • Select all your objects and drag them slightly, but be sure they land in the same place they were. They will all now be in the rectangle.

In the rectangle properties you can set the page-break to occur at the start or end of the rectangle and name of the page can be based on an expression.

The worksheets will be named the same as the name of the page.

Duplicate names will have a number in brackets suffix.

Note: Ensure that the names are valid worksheet names.

DataSet panel (Report Data) in SSRS designer is gone

With a .rdl, .rdlc or similar file selected, you can either:

  • Click View -> Report Data or...
  • Use the keyboard shortcut CTRL + ALT + D

Example

How to get rid of blank pages in PDF exported from SSRS

I recently inherited a report that I needed to make a few changes. After following all the recommendations above, it did not help. The report historically had this extra page, and nobody could figure out why.

I right clicked on the tablix and selected properties. There was a checkbox checked that said add a page break after. After removing this, it prints on one page now.

enter image description here

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

This worked for me- -go to the report manager, check site settings-> Security -> New Role Assignment-> add the user

-Also, go to Datasets in report manager -> your report dataset -> Security -> New Role Assignment -> add the user with the required role.

Thanks!

How to load external scripts dynamically in Angular?

a sample can be

script-loader.service.ts file

import {Injectable} from '@angular/core';
import * as $ from 'jquery';

declare let document: any;

interface Script {
  src: string;
  loaded: boolean;
}

@Injectable()
export class ScriptLoaderService {
public _scripts: Script[] = [];

/**
* @deprecated
* @param tag
* @param {string} scripts
* @returns {Promise<any[]>}
*/
load(tag, ...scripts: string[]) {
scripts.forEach((src: string) => {
  if (!this._scripts[src]) {
    this._scripts[src] = {src: src, loaded: false};
  }
});

let promises: any[] = [];
scripts.forEach((src) => promises.push(this.loadScript(tag, src)));

return Promise.all(promises);
}

 /**
 * Lazy load list of scripts
 * @param tag
 * @param scripts
 * @param loadOnce
 * @returns {Promise<any[]>}
 */
loadScripts(tag, scripts, loadOnce?: boolean) {
loadOnce = loadOnce || false;

scripts.forEach((script: string) => {
  if (!this._scripts[script]) {
    this._scripts[script] = {src: script, loaded: false};
  }
});

let promises: any[] = [];
scripts.forEach(
    (script) => promises.push(this.loadScript(tag, script, loadOnce)));

return Promise.all(promises);
}

/**
 * Lazy load a single script
 * @param tag
 * @param {string} src
 * @param loadOnce
 * @returns {Promise<any>}
 */
loadScript(tag, src: string, loadOnce?: boolean) {
loadOnce = loadOnce || false;

if (!this._scripts[src]) {
  this._scripts[src] = {src: src, loaded: false};
}

return new Promise((resolve, reject) => {
  // resolve if already loaded
  if (this._scripts[src].loaded && loadOnce) {
    resolve({src: src, loaded: true});
  }
  else {
    // load script tag
    let scriptTag = $('<script/>').
        attr('type', 'text/javascript').
        attr('src', this._scripts[src].src);

    $(tag).append(scriptTag);

    this._scripts[src] = {src: src, loaded: true};
    resolve({src: src, loaded: true});
  }
 });
 }
 }

and usage

first inject

  constructor(
  private _script: ScriptLoaderService) {
  }

then

ngAfterViewInit()  {
this._script.loadScripts('app-wizard-wizard-3',
['assets/demo/default/custom/crud/wizard/wizard.js']);

}

or

    this._script.loadScripts('body', [
  'assets/vendors/base/vendors.bundle.js',
  'assets/demo/default/base/scripts.bundle.js'], true).then(() => {
  Helpers.setLoading(false);
  this.handleFormSwitch();
  this.handleSignInFormSubmit();
  this.handleSignUpFormSubmit();
  this.handleForgetPasswordFormSubmit();
});

How to analyze information from a Java core dump?

jhat is one of the best i have used so far.To take a core dump,I think you better use jmap and jps instead of gcore(i haven't used it).Check the link to see how to use jhat. http://www.lshift.net/blog/2006/03/08/java-memory-profiling-with-jmap-and-jhat

How to do a https request with bad certificate?

Generally, The DNS Domain of the URL MUST match the Certificate Subject of the certificate.

In former times this could be either by setting the domain as cn of the certificate or by having the domain set as a Subject Alternative Name.

Support for cn was deprecated for a long time (since 2000 in RFC 2818) and Chrome browser will not even look at the cn anymore so today you need to have the DNS Domain of the URL as a Subject Alternative Name.

RFC 6125 which forbids checking the cn if SAN for DNS Domain is present, but not if SAN for IP Address is present. RFC 6125 also repeats that cn is deprecated which was already said in RFC 2818. And the Certification Authority Browser Forum to be present which in combination with RFC 6125 essentially means that cn will never be checked for DNS Domain name.

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

First is you have to understand the difference between MyISAM and InnoDB Engines. And this is clearly stated on this link. You can use this sql statement if you want to convert InnoDB to MyISAM:

 ALTER TABLE t1 ENGINE=MyISAM;

How can I get the last 7 characters of a PHP string?

last 7 characters of a string:

$rest = substr( "abcdefghijklmnop", -7); // returns "jklmnop"

Difference between 2 dates in seconds

$timeFirst  = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;

You will then be able to use the seconds to find minutes, hours, days, etc.

How to make a Qt Widget grow with the window size?

I found it was impossible to assign a layout to the centralwidget until I had added at least one child beneath it. Then I could highlight the tiny icon with the red 'disabled' mark and then click on a layout in the Designer toolbar at top.

Force IE10 to run in IE10 Compatibility View?

I had the same problem. The problem is a bug in MSIE 10, so telling people to fix their issues isn't helpful. Neither is telling visitors to your site to add your site to compatibility view, bleh. In my case, the problem was that the following code displayed no text:

document.write ('<P>'); 
document.write ('Blah, blah, blah... ');
document.write ('</P>');

After much trial and error, I determined that removing the <P> and </P> tags caused the text to appear properly on the page (thus, the problem IS with document mode rather than browser mode, at least in my case). Removing the <P> tags when userAgent is MSIE is not a "fix" I want to put into my pages.

The solution, as others have said, is:

<!DOCTYPE HTML whatever doctype you're using....> 
<HTML>
 <HEAD>
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8">
  <TITLE>Blah...

Yes, the meta tag has to be the FIRST tag after HEAD.

How to add composite primary key to table

In Oracle, you could do this:

create table D (
  ID numeric(1),
  CODE varchar(2),
  constraint PK_D primary key (ID, CODE)
);

What port is used by Java RMI connection?

You typically set the port at the server using the rmiregistry command. You can set the port on the command line, or it will default to 1099

Append text to input field

_x000D_
_x000D_
    $('#input-field-id').val($('#input-field-id').val() + 'more text');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input id="input-field-id" />
_x000D_
_x000D_
_x000D_

Xcode 'CodeSign error: code signing is required'

Have you updated the firmware version of the iPhone you are testing on?

Send JavaScript variable to PHP variable

PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:

<script type="text/javascript">
  var foo = '<?php echo $foo ?>';
</script>

To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):

var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});

On your server, you would need to receive the variable sent in the post:

$variable = $_POST['variable'];

Javascript to set hidden form value on drop down change

If you have HTML like this, for example:

<select id='myselect'>
    <option value='1'>A</option>
    <option value='2'>B</option>
    <option value='3'>C</option>
    <option value='4'>D</option>
</select>
<input type='hidden' id='myhidden' value=''>

All you have to do is bind a function to the change event of the select, and do what you need there:

<script type='text/javascript'>
$(function() {
    $('#myselect').change(function() {
        // if changed to, for example, the last option, then
        // $(this).find('option:selected').text() == D
        // $(this).val() == 4
        // get whatever value you want into a variable
        var x = $(this).val();
        // and update the hidden input's value
        $('#myhidden').val(x);
    });
});
</script>

All things considered, if you're going to be doing a lot of jQuery programming, always have the documentation open. It is very easy to find what you need there if you give it a chance.

Android : Fill Spinner From Java Code Programmatically

Here is an example to fully programmatically:

  • init a Spinner.
  • fill it with data via a String List.
  • resize the Spinner and add it to my View.
  • format the Spinner font (font size, colour, padding).
  • clear the Spinner.
  • add new values to the Spinner.
  • redraw the Spinner.

I am using the following class vars:

Spinner varSpinner;
List<String> varSpinnerData;

float varScaleX;
float varScaleY;    

A - Init and render the Spinner (varRoot is a pointer to my main Activity):

public void renderSpinner() {


    List<String> myArraySpinner = new ArrayList<String>();

    myArraySpinner.add("red");
    myArraySpinner.add("green");
    myArraySpinner.add("blue");     

    varSpinnerData = myArraySpinner;

    Spinner mySpinner = new Spinner(varRoot);               

    varSpinner = mySpinner;

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
    mySpinner.setAdapter(spinnerArrayAdapter);

B - Resize and Add the Spinner to my View:

    FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT, 
            FrameLayout.LayoutParams.WRAP_CONTENT);
    myParamsLayout.gravity = Gravity.NO_GRAVITY;             

    myParamsLayout.leftMargin = (int) (100 * varScaleX);
    myParamsLayout.topMargin = (int) (350 * varScaleY);             
    myParamsLayout.width = (int) (300 * varScaleX);;
    myParamsLayout.height = (int) (60 * varScaleY);;


    varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);

C - Make the Click handler and use this to set the font.

    mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {

            Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);

            ((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
            ((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
            ((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);


        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

}   

D - Update the Spinner with new data:

private void updateInitSpinners(){

     String mySelected = varSpinner.getSelectedItem().toString();
     Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


     varSpinnerData.clear();

     varSpinnerData.add("Hello World");
     varSpinnerData.add("Hello World 2");

     ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
     varSpinner.invalidate();
     varSpinner.setSelection(1);

}

}

What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.

UPDATE:

This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:

private void updateInitSpinners(){

    String mySelected = varSpinner.getSelectedItem().toString();
    Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


    varSpinnerData.clear();

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    varSpinner.setAdapter(spinnerArrayAdapter);  


    varSpinnerData.add("Hello World");
    varSpinnerData.add("Hello World 2");

    ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
    varSpinner.invalidate();
    varSpinner.setSelection(0);

}

}

Hope this helps......

Read file line by line using ifstream in C++

Expanding on the accepted answer, if the input is:

1,NYC
2,ABQ
...

you will still be able to apply the same logic, like this:

#include <fstream>

std::ifstream infile("thefile.txt");
if (infile.is_open()) {
    int number;
    std::string str;
    char c;
    while (infile >> number >> c >> str && c == ',')
        std::cout << number << " " << str << "\n";
}
infile.close();

How do you create a hidden div that doesn't create a line break or horizontal space?

Use style="display: none;". Also, you probably don't need to have the DIV, just setting the style to display: none on the checkbox would probably be sufficient.

Adding a column to a data.frame

You can add a column to your data using various techniques. The quotes below come from the "Details" section of the relevant help text, [[.data.frame.

Data frames can be indexed in several modes. When [ and [[ are used with a single vector index (x[i] or x[[i]]), they index the data frame as if it were a list.

my.dataframe["new.col"] <- a.vector
my.dataframe[["new.col"]] <- a.vector

The data.frame method for $, treats x as a list

my.dataframe$new.col <- a.vector

When [ and [[ are used with two indices (x[i, j] and x[[i, j]]) they act like indexing a matrix

my.dataframe[ , "new.col"] <- a.vector

Since the method for data.frame assumes that if you don't specify if you're working with columns or rows, it will assume you mean columns.


For your example, this should work:

# make some fake data
your.df <- data.frame(no = c(1:4, 1:7, 1:5), h_freq = runif(16), h_freqsq = runif(16))

# find where one appears and 
from <- which(your.df$no == 1)
to <- c((from-1)[-1], nrow(your.df)) # up to which point the sequence runs

# generate a sequence (len) and based on its length, repeat a consecutive number len times
get.seq <- mapply(from, to, 1:length(from), FUN = function(x, y, z) {
            len <- length(seq(from = x[1], to = y[1]))
            return(rep(z, times = len))
         })

# when we unlist, we get a vector
your.df$group <- unlist(get.seq)
# and append it to your original data.frame. since this is
# designating a group, it makes sense to make it a factor
your.df$group <- as.factor(your.df$group)


   no     h_freq   h_freqsq group
1   1 0.40998238 0.06463876     1
2   2 0.98086928 0.33093795     1
3   3 0.28908651 0.74077119     1
4   4 0.10476768 0.56784786     1
5   1 0.75478995 0.60479945     2
6   2 0.26974011 0.95231761     2
7   3 0.53676266 0.74370154     2
8   4 0.99784066 0.37499294     2
9   5 0.89771767 0.83467805     2
10  6 0.05363139 0.32066178     2
11  7 0.71741529 0.84572717     2
12  1 0.10654430 0.32917711     3
13  2 0.41971959 0.87155514     3
14  3 0.32432646 0.65789294     3
15  4 0.77896780 0.27599187     3
16  5 0.06100008 0.55399326     3

Saving an Excel sheet in a current directory with VBA

Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:

workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"

Only works if your file structure contains one instance of the text used to replace. YMMV.

How to get local server host and port in Spring Boot?

IP Address

You can get network interfaces with NetworkInterface.getNetworkInterfaces(), then the IP addresses off the NetworkInterface objects returned with .getInetAddresses(), then the string representation of those addresses with .getHostAddress().

Port

If you make a @Configuration class which implements ApplicationListener<EmbeddedServletContainerInitializedEvent>, you can override onApplicationEvent to get the port number once it's set.

@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
    int port = event.getEmbeddedServletContainer().getPort();
}

Convert UIImage to NSData and convert back to UIImage in Swift?

Use imageWithData: method, which gets translated to Swift as UIImage(data:)

let image : UIImage = UIImage(data: imageData)

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Tar error: Unexpected EOF in archive

In my case, I had started untar before the uploading of the tar file was complete.

Can you split/explode a field in a MySQL query?

There's an easier way, have a link table, i.e.:

Table 1: clients, client info, blah blah blah

Table 2: courses, course info, blah blah

Table 3: clientid, courseid

Then do a JOIN and you're off to the races.

jQuery callback on image load (even when the image is cached)

You can solve your problem using JAIL plugin that also allows you to lazy load images (improving the page performance) and passing the callback as parameter

$('img').asynchImageLoader({callback : function(){...}});

The HTML should look like

<img name="/global/images/sample1.jpg" src="/global/images/blank.gif" width="width" height="height" />

How to track down a "double free or corruption" error

Three basic rules:

  1. Set pointer to NULL after free
  2. Check for NULL before freeing.
  3. Initialise pointer to NULL in the start.

Combination of these three works quite well.

Getting or changing CSS class property with Javascript using DOM style

Maybe better document.querySelectorAll(".col1") because getElementsByClassName doesn't works in IE 8 and querySelectorAll does (althought CSS2 selectors only).

https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

Search for value in DataGridView in a column

It's better also to separate your logic in another method, or maybe in another class.

This method will help you retreive the DataGridViewCell object in which the text was found.

    /// <summary>
    /// Check if a given text exists in the given DataGridView at a given column index
    /// </summary>
    /// <param name="searchText"></param>
    /// <param name="dataGridView"></param>
    /// <param name="columnIndex"></param>
    /// <returns>The cell in which the searchText was found</returns>
    private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
    {
        DataGridViewCell cellWhereTextIsMet = null;

        // For every row in the grid (obviously)
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            // I did not test this case, but cell.Value is an object, and objects can be null
            // So check if the cell is null before using .ToString()
            if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
            {
                // the searchText is equals to the text in this cell.
                cellWhereTextIsMet = row.Cells[columnIndex];
                break;
            }
        }

        return cellWhereTextIsMet;
    }

    private void button_click(object sender, EventArgs e)
    {
        DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
        if (cell != null)
        {
            // Value exists in the grid
            // you can do extra stuff on the cell
            cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
        }
        else
        {
            // Value does not exist in the grid
        }
    }

In C/C++ what's the simplest way to reverse the order of bits in a byte?

#define BITS_SIZE 8

int
reverseBits ( int a )
{
  int rev = 0;
  int i;

  /* scans each bit of the input number*/
  for ( i = 0; i < BITS_SIZE - 1; i++ )
  {
    /* checks if the bit is 1 */
    if ( a & ( 1 << i ) )
    {
      /* shifts the bit 1, starting from the MSB to LSB
       * to build the reverse number 
      */
      rev |= 1 << ( BITS_SIZE - 1 ) - i;
    }
  }

  return rev;
}

String concatenation in Jinja

If stuffs is a list of strings, just this would work:

{{ stuffs|join(", ") }}

Link to join filter documentation, link to filters in general documentation.

p.s.

More reader friendly way {{ my ~ ', ' ~ string }}

How to increase size of DOSBox window?

Here's how to change the dosbox.conf file in Linux to increase the size of the window. I actually DID what follows, so I can say it works (in 32-bit PCLinuxOS fullmontyKDE, anyway). The question's answer is in the .conf file itself.

You find this file in Linux at /home/(username)/.dosbox . In Konqueror or Dolphin, you must first check 'Hidden files' or you won't see the folder. Open it with KWrite superuser or your fav editor.

  1. Save the file with another name like 'dosbox-0.74original.conf' to preserve the original file in case you need to restore it.
  2. Search on 'resolution' and carefully read what the conf file says about changing it. There are essentially two variables: resolution and output. You want to leave fullresolution alone for now. Your question was about WINDOW, not full. So look for windowresolution, see what the comments in conf file say you can do. The best suggestion is to use a bigger-window resolution like 900x800 (which is what I used on a 1366x768 screen), but NOT the actual resolution of your machine (which would make the window fullscreen, and you said you didn't want that). Be specific, replacing the 'windowresolution=original' with 'windowresolution=900x800' or other dimensions. On my screen, that doubled the window size just as it does with the max Font tab in Windows Properties (for the exe file; as you'll see below the ==== marks, 32-bit Windows doesn't need Dosbox).

Then, search on 'output', and as the instruction in the conf file warns, if and only if you have 'hardware scaling', change the default 'output=surface' to something else; he then lists the optional other settings. I changed it to 'output=overlay'. There's one other setting to test: aspect. Search the file for 'aspect', and change the 'false' to 'true' if you want an even bigger window. When I did this, the window took up over half of the screen. With 'false' left alone, I had a somewhat smaller window (I use widescreen monitors, whether laptop or desktop, maybe that's why).

So after you've made the changes, save the file with the original name of dosbox-0.74.conf . Then, type dosbox at the command line or create a Launcher (in KDE, this is a right click on the desktop) with the command dosbox. You still have to go through the mount command (i.e., mount c~ c:\123 if that's the location and file you'll execute). I'm sure there's a way to make a script, but haven't yet learned how to do that.

Delayed function calls

There is no standard way to delay a call to a function other than to use a timer and events.

This sounds like the GUI anti pattern of delaying a call to a method so that you can be sure the form has finished laying out. Not a good idea.

Invalid use side-effecting operator Insert within a function

Functions cannot be used to modify base table information, use a stored procedure.

PostgreSQL wildcard LIKE for any of a list of words

One 'elegant' solution would be to use full text search: http://www.postgresql.org/docs/9.0/interactive/textsearch.html. Then you would use full text search queries.

Is Java RegEx case-insensitive?

You can also match case insensitive regexs and make it more readable by using the Pattern.CASE_INSENSITIVE constant like:

Pattern mypattern = Pattern.compile(MYREGEX, Pattern.CASE_INSENSITIVE);
Matcher mymatcher= mypattern.matcher(mystring);

How does the Python's range function work?

It is looping, probably the problem is in the part of the print...

If you can't find the logic where the system prints, just add the folling where you want the content out:

for i in range(len(vs)):
    print vs[i]
    print fs[i]
    print rs[i]

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

Here's a simple elvis operator equivalent:

function elvis(object, path) {
    return path ? path.split('.').reduce(function (nestedObject, key) {
        return nestedObject && nestedObject[key];
    }, object) : object;
}

> var o = { a: { b: 2 }, c: 3 };
> elvis(o)

{ a: { b: 2 }, c: 3 }

> elvis(o, 'a');

{ b: 2 }

> elvis(o, 'a.b');

2

> elvis(o, 'x');

undefined

How to compute the sum and average of elements in an array?

Let's imagine we have an array of integers like this:

var values = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

The average is obtained with the following formula

A= (1/n)Sxi ( with i = 1 to n ) ... So: x1/n + x2/n + ... + xn/n

We divide the current value by the number of values and add the previous result to the returned value.

The reduce method signature is

reduce(callback[,default_previous_value])

The reduce callback function takes the following parameters:

  • p : Result of the previous calculation
  • c : Current value (from the current index)
  • i : Current array element's index value
  • a : The current reduced Array

The second reduce's parameter is the default value ... (Used in case the array is empty ).

So the average reduce method will be:

var avg = values.reduce(function(p,c,i,a){return p + (c/a.length)},0);

If you prefer you can create a separate function

function average(p,c,i,a){return p + (c/a.length)};
function sum(p,c){return p + c)};

And then simply refer to the callback method signature

var avg = values.reduce(average,0);
var sum= values.reduce(sum,0);

Or Augment the Array prototype directly..

Array.prototype.sum = Array.prototype.sum || function (){
  return this.reduce(function(p,c){return p+c},0);
};

It's possible to divide the value each time the reduce method is called..

Array.prototype.avg = Array.prototype.avg || function () {
  return this.reduce(function(p,c,i,a){return p+(c/a.length)},0);
};

Or even better , using the previously defined Array.protoype.sum()

method, optimize the process my calling the division only once :)

Array.prototype.avg = Array.prototype.avg || function () {
  return this.sum()/this.length; 
};

Then on any Array object of the scope:

[2, 6].avg();// -> 4
[2, 6].sum();// -> 8

NB: an empty array with return a NaN wish is more correct than 0 in my point of view and can be useful in specific use cases.

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

Make sure [qry_all_details] exists and is runnable. I suspect it or any query it uses, is missing the parameter.

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

This is old post and I am sorry but even installing of KB2999226 will not help if you don't have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) update package. Without it the installation of KB2999226 returns error "The update is not applicable to your computer". Typically you will get this problem if you have some offline envinroment for example dev virtual machines without access to the WSUS or Windows Update services and old ISO images of Windows 8.1, Server 2012 R2.

Temporarily switch working copy to a specific Git commit

In addition to the other answers here showing you how to git checkout <the-hash-you-want> it's worth knowing you can switch back to where you were using:

git checkout @{-1}

This is often more convenient than:

git checkout what-was-that-original-branch-called-again-question-mark

As you might anticipate, git checkout @{-2} will take you back to the branch you were at two git checkouts ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.


Sadly for productivity, git checkout @{1} does not take you to the branch you will be on in future, which is a shame.

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

Always use mongoose.Types.ObjectId('your id')for conditions in your query it will validate the id field before running your query as a result your app will not crash.

Can we have multiple <tbody> in same <table>?

Yes. I use them for dynamically hiding/revealing the relevant part of a table, e.g. a course. Viz.

<table>
  <tbody id="day1" style="display:none">
    <tr><td>session1</td><tr>
    <tr><td>session2</td><tr>
  </tbody>
  <tbody id="day2">
    <tr><td>session3</td><tr>
    <tr><td>session4</td><tr>
  </tbody>
  <tbody id="day3" style="display:none">
    <tr><td>session5</td><tr>
    <tr><td>session6</td><tr>
  </tbody>
</table>

A button can be provided to toggle between everything or just the current day by manipulating tbodies without processing many rows individually.

Implement an input with a mask

Below i describe my method. I set event on input in input, to call Masking() method, which will return an formatted string of that we insert in input.

Html:

<input name="phone" pattern="+373 __ ___ ___" class="masked" required>

JQ: Here we set event on input:

$('.masked').on('input', function () {
    var input = $(this);
    input.val(Masking(input.val(), input.attr('pattern')));
});

JS: Function, which will format string by pattern;

function Masking (value, pattern) {
var out = '';
var space = ' ';
var any = '_';

for (var i = 0, j = 0; j < value.length; i++, j++) {
    if (value[j] === pattern[i]) {
        out += value[j];
    }
    else if(pattern[i] === any && value[j] !== space) {
        out += value[j];
    }
    else if(pattern[i] === space && value[j] !== space) {
        out += space;
        j--;
    }
    else if(pattern[i] !== any && pattern[i] !== space) {
        out += pattern[i];
        j--;
    }
}

return out;
}

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

Please try to avoid using takePersistableUriPermission method because it raised runtime exception for me. /** * Select from gallery. */

public void selectFromGallery() {
    if (Build.VERSION.SDK_INT < AppConstants.KITKAT_API_VERSION) {

        Intent intent = new Intent(); 
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        ((Activity)mCalledContext).startActivityForResult(intent,AppConstants.GALLERY_INTENT_CALLED);

    } else {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        ((Activity)mCalledContext).startActivityForResult(intent, AppConstants.GALLERY_AFTER_KITKAT_INTENT_CALLED);
    }
}

OnActivity for result to handle the image data:

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    //gallery intent result handling before kit-kat version
    if(requestCode==AppConstants.GALLERY_INTENT_CALLED 
            && resultCode == RESULT_OK) {

        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String filePath = cursor.getString(columnIndex);
        cursor.close();
        photoFile = new File(filePath);
        mImgCropping.startCropImage(photoFile,AppConstants.REQUEST_IMAGE_CROP);

    }
    //gallery intent result handling after kit-kat version
    else if (requestCode == AppConstants.GALLERY_AFTER_KITKAT_INTENT_CALLED 
            && resultCode == RESULT_OK) {

        Uri selectedImage = data.getData();
        InputStream input = null;
        OutputStream output = null;

        try {
            //converting the input stream into file to crop the 
            //selected image from sd-card.
            input = getApplicationContext().getContentResolver().openInputStream(selectedImage);
            try {
                photoFile = mImgCropping.createImageFile();
            } catch (IOException e) {
                e.printStackTrace();
            }catch(Exception e) {
                e.printStackTrace();
            }
            output = new FileOutputStream(photoFile);

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = input.read(bytes)) != -1) {
                try {
                    output.write(bytes, 0, read);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

Combine two or more columns in a dataframe into a new column with a new name

Some examples with NAs and their removal using apply

n = c(2, NA, NA) 
s = c("aa", "bb", NA) 
b = c(TRUE, FALSE, NA) 
c = c(2, 3, 5) 
d = c("aa", NA, "cc") 
e = c(TRUE, NA, TRUE) 
df = data.frame(n, s, b, c, d, e)

paste_noNA <- function(x,sep=", ") {
gsub(", " ,sep, toString(x[!is.na(x) & x!="" & x!="NA"] ) ) }

sep=" "
df$x <- apply( df[ , c(1:6) ] , 1 , paste_noNA , sep=sep)
df

Android: Clear the back stack

This code work for me in kotlin:

 val intent = Intent(this, MainActivity::class.java)
 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
 startActivity(intent)
 finish()

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.

Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/

Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run

pip install module-name.whl 

I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.

People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"

How to copy std::string into std::vector<char>?

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

mysql said: Cannot connect: invalid settings. xampp

it may be another mysqld instance running and stoped it with:

sudo service mysql stop

Worked for me.

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

ImportError: No module named _ssl

On Solaris 11, I had to modify setup.py to include /opt/csw/include/openssl in the SSL include search path.

Uwe

Generating an array of letters in the alphabet

4 ways get English alphabet in Console:

public void ShowEnglishAlphabet()
{
    var firstLetter = 'a';
    var endLetter = 'z';
    for (var letter = firstLetter; letter <= endLetter; letter++)
    {
        Console.WriteLine($"{letter}-{letter.ToString().ToUpper()}");
    }
}

public void ShowEnglishAlphabetFromUnicodeTableDecNumber()
{
    var firstLetter = 97;
    var endLetter = 122;
    for (var letterNumberUnicodeTable = firstLetter; 
    letterNumberUnicodeTable <= endLetter; letterNumberUnicodeTable++)
    {
        Console.WriteLine($"{(char)letterNumberUnicodeTable}- 
        {((char)letterNumberUnicodeTable).ToString().ToUpper()}");
    }
}

public void ShowEnglishAlphabetUnicodeTableEscapeSequence()
{
    var firstLetter = '\u0061';
    var endLetter = '\u007A';
    for (var letterNumberUnicodeTable = firstLetter; 
    letterNumberUnicodeTable <= endLetter; letterNumberUnicodeTable++)
    {
        Console.WriteLine($"{letterNumberUnicodeTable}- 
        {letterNumberUnicodeTable.ToString().ToUpper()}");
    }
}   

public void ShowEnglishAlphabetUnicodeTableLinq()
{
    var alphabets = Enumerable.Range('a', 26).Select(letter => 
    ((char)letter).ToString()).ToList();
    foreach (var letter in alphabets)
    {
        Console.WriteLine($"{letter}-{letter.ToUpper()}");
    }
}

RunAs A different user when debugging in Visual Studio

I'm using the following method based on @Watki02's answer:

  1. Shift r-click the application to debug
  2. Run as different user
  3. Attach the debugger to the application

That way you can keep your visual studio instance as your own user whilst debugging from the other.

Android - Pulling SQlite database android device

If you want your database file

See the DDMS > File explore

find your db file from your package name

then Click on pull a file from device (Rooted device only)

How to analyze disk usage of a Docker container

After 1.13.0, Docker includes a new command docker system df to show docker disk usage.

$ docker system df
TYPE            TOTAL        ACTIVE     SIZE        RECLAIMABLE
Images          5            1          2.777 GB    2.647 GB (95%)
Containers      1            1          0 B         0B
Local Volumes   4            1          3.207 GB    2.261 (70%)

To show more detailed information on space usage:

$ docker system df --verbose

Javascript: 'window' is not defined

The window object represents an open window in a browser. Since you are not running your code within a browser, but via Windows Script Host, the interpreter won't be able to find the window object, since it does not exist, since you're not within a web browser.

Should I use JSLint or JSHint JavaScript validation?

I'd make a third suggestion, Google Closure Compiler (and also the Closure Linter). You can try it out online here.

The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.

SVN 405 Method Not Allowed

The quickest way for me to fix it was to duplicate the affected folder, and commit it with an alternative name. Then svn mv duplicateFolder originalFolder. Pretty easy.

So, take folder1 and make a folder1Copy:

svn delete folder1
svn add folder1Copy

Commit and update:

svn mv folder1Copy/ folder1/

Commit again and it's fixed.

How to get the real and total length of char * (char array)?

This may sound Evil™ and I haven't tested it, but how about initializing all values in an array at allocation to '\0' and then using strlen() ? This would give you your so-called real value since it would stop counting at the first '\0' it encounters.

Well, now that I think about it though, please don't Ever™ do this. Unless, you want to land in a pile of dirty memory.

Also, for the allocated memory or the total memory you may use the following functions if your environment provides them:

How to print a linebreak in a python function?

You can print a native linebreak using the standard os library

import os
with open('test.txt','w') as f:
    f.write(os.linesep)

Pass all variables from one shell script to another?

There's actually an easier way than exporting and unsetting or sourcing again (at least in bash, as long as you're ok with passing the environment variables manually):

let a.sh be

#!/bin/bash
secret="winkle my tinkle"
echo Yo, lemme tell you \"$secret\", b.sh!
Message=$secret ./b.sh

and b.sh be

#!/bin/bash
echo I heard \"$Message\", yo

Observed output is

[rob@Archie test]$ ./a.sh
Yo, lemme tell you "winkle my tinkle", b.sh!
I heard "winkle my tinkle", yo

The magic lies in the last line of a.sh, where Message, for only the duration of the invocation of ./b.sh, is set to the value of secret from a.sh. Basically, it's a little like named parameters/arguments. More than that, though, it even works for variables like $DISPLAY, which controls which X Server an application starts in.

Remember, the length of the list of environment variables is not infinite. On my system with a relatively vanilla kernel, xargs --show-limits tells me the maximum size of the arguments buffer is 2094486 bytes. Theoretically, you're using shell scripts wrong if your data is any larger than that (pipes, anyone?)

Find and Replace Inside a Text File from a Bash Command

I found this thread among others and I agree it contains the most complete answers so I'm adding mine too:

  1. sed and ed are so useful...by hand. Look at this code from @Johnny:

    sed -i -e 's/abc/XYZ/g' /tmp/file.txt
    
  2. When my restriction is to use it in a shell script, no variable can be used inside in place of "abc" or "XYZ". The BashFAQ seems to agree with what I understand at least. So, I can't use:

    x='abc'
    y='XYZ'
    sed -i -e 's/$x/$y/g' /tmp/file.txt
    #or,
    sed -i -e "s/$x/$y/g" /tmp/file.txt
    

    but, what can we do? As, @Johnny said use a while read... but, unfortunately that's not the end of the story. The following worked well with me:

    #edit user's virtual domain
    result=
    #if nullglob is set then, unset it temporarily
    is_nullglob=$( shopt -s | egrep -i '*nullglob' )
    if [[ is_nullglob ]]; then
       shopt -u nullglob
    fi
    while IFS= read -r line; do
       line="${line//'<servername>'/$server}"
       line="${line//'<serveralias>'/$alias}"
       line="${line//'<user>'/$user}"
       line="${line//'<group>'/$group}"
       result="$result""$line"'\n'
    done < $tmp
    echo -e $result > $tmp
    #if nullglob was set then, re-enable it
    if [[ is_nullglob ]]; then
       shopt -s nullglob
    fi
    #move user's virtual domain to Apache 2 domain directory
    ......
    
  3. As one can see if nullglob is set then, it behaves strangely when there is a string containing a * as in:

    <VirtualHost *:80>
     ServerName www.example.com
    

    which becomes

    <VirtualHost ServerName www.example.com
    

    there is no ending angle bracket and Apache2 can't even load.

  4. This kind of parsing should be slower than one-hit search and replace but, as you already saw, there are four variables for four different search patterns working out of one parse cycle.

The most suitable solution I can think of with the given assumptions of the problem.

Round to 5 (or other number) in Python

I don't know of a standard function in Python, but this works for me:

Python 2

def myround(x, base=5):
    return int(base * round(float(x)/base))

Python3

def myround(x, base=5):
    return base * round(x/base)

It is easy to see why the above works. You want to make sure that your number divided by 5 is an integer, correctly rounded. So, we first do exactly that (round(float(x)/5) where float is only needed in Python2), and then since we divided by 5, we multiply by 5 as well. The final conversion to int is because round() returns a floating-point value in Python 2.

I made the function more generic by giving it a base parameter, defaulting to 5.

Split string in Lua?

You can use this method:

function string:split(delimiter)
  local result = { }
  local from  = 1
  local delim_from, delim_to = string.find( self, delimiter, from  )
  while delim_from do
    table.insert( result, string.sub( self, from , delim_from-1 ) )
    from  = delim_to + 1
    delim_from, delim_to = string.find( self, delimiter, from  )
  end
  table.insert( result, string.sub( self, from  ) )
  return result
end

delimiter = string.split(stringtodelimite,pattern) 

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

You can save it using the Save As dialog using ".something".

subsetting a Python DataFrame

Regarding some points mentioned in previous answers, and to improve readability:

No need for data.loc or query, but I do think it is a bit long.

The parentheses are also necessary, because of the precedence of the & operator vs. the comparison operators.

I like to write such expressions as follows - less brackets, faster to type, easier to read. Closer to R, too.

q_product = df.Product == p_id
q_start = df.Time > start_time
q_end = df.Time < end_time

df.loc[q_product & q_start & q_end, c('Time,Product')]

# c is just a convenience
c = lambda v: v.split(',') 

"This project is incompatible with the current version of Visual Studio"

I Resolved the issue by deleting the files in the below folder

%localappdata%\Microsoft\VisualStudio\12.0\ComponentModelCache

Source: https://forums.xamarin.com/discussion/70388/how-to-fix-incompatible-issue-after-visual-studio-2015-update-3

Saving changes after table edit in SQL Server Management Studio

Many changes you can make very easily and visually in the table editor in SQL Server Management Studio actually require SSMS to drop the table in the background and re-create it from scratch. Even simple things like reordering the columns cannot be expressed in standard SQL DDL statement - all SSMS can do is drop and recreate the table.

This operation can be a) very time consuming on a large table, or b) might even fail for various reasons (like FK constraints and stuff). Therefore, SSMS in SQL Server 2008 introduced that new option the other answers have already identified.

It might seem counter-intuitive at first to prevent such changes - and it's certainly a nuisance on a dev server. But on a production server, this option and its default value of preventing such changes becomes a potential life-saver!

How can I view an object with an alert()

This is what I use:

var result = [];
for (var l in someObject){
  if (someObject.hasOwnProperty(l){
    result.push(l+': '+someObject[l]);
  }
}
alert(result.join('\n'));

If you want to show nested objects too, you could use something recursive:

function alertObject(obj){
 var result = [];
 function traverse(obj){
 for (var l in obj){
   if (obj.hasOwnProperty(l)){
     if (obj[l] instanceof Object){
       result.push(l+'=>[object]');
       traverse(obj[l]);
     } else {
       result.push(l+': '+obj[l]);
     }
   }
  }
 }
 traverse(obj);
 return result;
}

git-upload-pack: command not found, when cloning remote Git repo

Make sure git-upload-pack is on the path from a non-login shell. (On my machine it's in /usr/bin).

To see what your path looks like on the remote machine from a non-login shell, try this:

ssh you@remotemachine echo \$PATH

(That works in Bash, Zsh, and tcsh, and probably other shells too.)

If the path it gives back doesn't include the directory that has git-upload-pack, you need to fix it by setting it in .bashrc (for Bash), .zshenv (for Zsh), .cshrc (for tcsh) or equivalent for your shell.

You will need to make this change on the remote machine.

If you're not sure which path you need to add to your remote PATH, you can find it with this command (you need to run this on the remote machine):

which git-upload-pack

On my machine that prints /usr/bin/git-upload-pack. So in this case, /usr/bin is the path you need to make sure is in your remote non-login shell PATH.

Bootstrap Dropdown menu is not working

I tried all the above answers and the only version who works for me is the jquery 1.11.1. I tried with all the other versions 1.3.2, 1.4.4, 1.8.2, 3.3.1 and navbar dropdown doesn't work.

<script src="jquery/jquery-1.11.1.min.js"></script>

from unix timestamp to datetime

if you're using React I found 'react-moment' library more easy to handle for Front-End related tasks, just import <Moment> component and add unix prop:

import Moment from 'react-moment'

 // get date variable
 const {date} = this.props 

 <Moment unix>{date}</Moment>

MySQL JDBC Driver 5.1.33 - Time Zone Issue

This worked for me.

on DBeaver 6.0 : Go to Connection Settings > Driver Properties > Server Time Zone > Set UTC.

Also, in spring boot config, had to set below property.

jdbc:mysql://localhost:/?serverTimezone=UTC

What are the differences between using the terminal on a mac vs linux?

If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.

Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.

If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.

There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd on Mac and ifconfig works differently.

The following table is useful for knowing the various unix shells.

sh      The original Bourne shell   Present on every unix system 
ksh     Original Korn shell         Richer shell programming environment than sh 
csh     Original C-shell            C-like syntax; early versions buggy 
tcsh    Enhanced C-shell            User-friendly and less buggy csh implementation 
bash    GNU Bourne-again shell      Enhanced and free sh implementation 
zsh     Z shell                     Enhanced, user-friendly ksh-like shell

You may also find these guides helpful:

http://homepage.mac.com/rgriff/files/TerminalBasics.pdf

http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html

On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile on OSX) file with aliases, some examples below. I now placed all my aliases in a separate .bash_aliases file and include it with:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

in the .bashrc or .bash_profile file.

Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto. The first time I did this (without knowing) I redefined ls to be invalid which was a bit alarming until I removed --auto-color !

You may also find https://unix.stackexchange.com/q/127799/10043 useful

# ~/.bash_aliases
# ls variants
#alias l='ls -CF' 
alias la='ls -A' 
alias l='ls -alFtr' 
alias lsd='ls -d .*' 
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i' 
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed' 
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status' 
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'

Sending HTTP Post request with SOAP action using org.apache.http

The soapAction must passed as a http-header parameter - when used, it's not part of the http-body/payload.

Look here for an example with apache httpclient: http://svn.apache.org/repos/asf/httpcomponents/oac.hc3x/trunk/src/examples/PostSOAP.java

Logging levels - Logback - rule-of-thumb to assign log levels

Not different for other answers, my framework have almost the same levels:

  1. Error: critical logical errors on application, like a database connection timeout. Things that call for a bug-fix in near future
  2. Warn: not-breaking issues, but stuff to pay attention for. Like a requested page not found
  3. Info: used in functions/methods first line, to show a procedure that has been called or a step gone ok, like a insert query done
  4. log: logic information, like a result of an if statement
  5. debug: variable contents relevant to be watched permanently

Padding In bootstrap

The suggestion from @Dawood is good if that works for you.

If you need more fine-tuning than that, one option is to use padding on the text elements, here's an example: http://jsfiddle.net/panchroma/FtBwe/

CSS

p, h2 {
    padding-left:10px;
}

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Try this in the console:

JSON.parse(undefined)

Here is what you will get:

Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

In other words, your app is attempting to parse undefined, which is not valid JSON.

There are two common causes for this. The first is that you may be referencing a non-existent property (or even a non-existent variable if not in strict mode).

window.foobar = '{"some":"data"}';
JSON.parse(window.foobarn)  // oops, misspelled!

The second common cause is failure to receive the JSON in the first place, which could be caused by client side scripts that ignore errors and send a request when they shouldn't.

Make sure both your server-side and client-side scripts are running in strict mode and lint them using ESLint. This will give you pretty good confidence that there are no typos.

How to set OnClickListener on a RadioButton in Android?

Since this question isn't specific to Java, I would like to add how you can do it in Kotlin:

radio_group_id.setOnCheckedChangeListener({ radioGroup, optionId -> {
        when (optionId) {
            R.id.radio_button_1 -> {
                // do something when radio button 1 is selected
            }
            // add more cases here to handle other buttons in the RadioGroup
        }
    }
})

Here radio_group_id is the assigned android:id of the concerned RadioGroup. To use it this way you would need to import kotlinx.android.synthetic.main.your_layout_name.* in your activity's Kotlin file. Also note that in case the radioGroup lambda parameter is unused, it can be replaced with _ (an underscore) since Kotlin 1.1.

Python Requests and persistent sessions

Upon trying all the answers above, I found that using "RequestsCookieJar" instead of the regular CookieJar for subsequent requests fixed my problem.

import requests
import json

# The Login URL
authUrl = 'https://whatever.com/login'

# The subsequent URL
testUrl = 'https://whatever.com/someEndpoint'

# Logout URL
testlogoutUrl = 'https://whatever.com/logout'

# Whatever you are posting
login_data =  {'formPosted':'1', 
               'login_email':'[email protected]', 
               'password':'pw'
               }

# The Authentication token or any other data that we will receive from the Authentication Request. 
token = ''

# Post the login Request
loginRequest = requests.post(authUrl, login_data)
print("{}".format(loginRequest.text))

# Save the request content to your variable. In this case I needed a field called token. 
token = str(json.loads(loginRequest.content)['token'])  # or ['access_token']
print("{}".format(token))

# Verify Successful login
print("{}".format(loginRequest.status_code))

# Create your Requests Cookie Jar for your subsequent requests and add the cookie
jar = requests.cookies.RequestsCookieJar()
jar.set('LWSSO_COOKIE_KEY', token)

# Execute your next request(s) with the Request Cookie Jar set
r = requests.get(testUrl, cookies=jar)
print("R.TEXT: {}".format(r.text))
print("R.STCD: {}".format(r.status_code))

# Execute your logout request(s) with the Request Cookie Jar set
r = requests.delete(testlogoutUrl, cookies=jar)
print("R.TEXT: {}".format(r.text))  # should show "Request Not Authorized"
print("R.STCD: {}".format(r.status_code))  # should show 401

PHP header redirect 301 - what are the implications?

Make sure you die() after your redirection, and make sure you do your redirect AS SOON AS POSSIBLE while your script executes. It makes sure that no more database queries (if some) are not wasted for nothing. That's the one tip I can give you

For search engines, 301 is the best response code

How to join two JavaScript Objects, without using JQUERY

There are couple of different solutions to achieve this:

1 - Native javascript for-in loop:

const result = {};
let key;

for (key in obj1) {
  if(obj1.hasOwnProperty(key)){
    result[key] = obj1[key];
  }
}

for (key in obj2) {
  if(obj2.hasOwnProperty(key)){
    result[key] = obj2[key];
  }
}

2 - Object.keys():

const result = {};

Object.keys(obj1)
  .forEach(key => result[key] = obj1[key]);

Object.keys(obj2)
  .forEach(key => result[key] = obj2[key]);

3 - Object.assign():
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)

const result = Object.assign({}, obj1, obj2);

4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):

Defined in several sections of the specification: Array Initializer, Argument Lists

Using this new syntax you could join/merge different objects into one object like this:

const result = {
  ...obj1,
  ...obj2,
};

5 - jQuery.extend(target, obj1, obj2):

Merge the contents of two or more objects together into the first object.

const target = {};

$.extend(target, obj1, obj2);

6 - jQuery.extend(true, target, obj1, obj2):

Run a deep merge of the contents of two or more objects together into the target. Passing false for the first argument is not supported.

const target = {};

$.extend(true, target, obj1, obj2);

7 - Lodash _.assignIn(object, [sources]): also named as _.extend:

const result = {};

_.assignIn(result, obj1, obj2);

8 - Lodash _.merge(object, [sources]):

const result = _.merge(obj1, obj2);

There are a couple of important differences between lodash's merge function and Object.assign:

1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign only merges the first level. For instance:

_.isEqual(_.merge({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
}), {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // true

BUT:

const result = Object.assign({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
});
_.isEqual(result, {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // false
// AND
_.isEqual(result, {
  x: {
    y: {
      key2: 'value2',
    },
  },
}); // true

2- Another difference has to do with how Object.assign and _.merge interpret the undefined value:

_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false

BUT:

_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true

Update 1:

When using for in loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype or even Object.prototype. To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key) to mke sure the key is actually part of the object you are iterating over.


Update 2:

I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.


Update 3:
I added the difference between Object.assign and _.merge.

Extract file name from path, no matter what the os/path format

In both Python 2 and 3, using the module pathlib2:

import posixpath  # to generate unix paths
from pathlib2 import PurePath, PureWindowsPath, PurePosixPath

def path2unix(path, nojoin=True, fromwinpath=False):
    """From a path given in any format, converts to posix path format
    fromwinpath=True forces the input path to be recognized as a Windows path (useful on Unix machines to unit test Windows paths)"""
    if not path:
        return path
    if fromwinpath:
        pathparts = list(PureWindowsPath(path).parts)
    else:
        pathparts = list(PurePath(path).parts)
    if nojoin:
        return pathparts
    else:
        return posixpath.join(*pathparts)

Usage:

In [9]: path2unix('lala/lolo/haha.dat')
Out[9]: ['lala', 'lolo', 'haha.dat']

In [10]: path2unix(r'C:\lala/lolo/haha.dat')
Out[10]: ['C:\\', 'lala', 'lolo', 'haha.dat']

In [11]: path2unix(r'C:\lala/lolo/haha.dat') # works even with malformatted cases mixing both Windows and Linux path separators
Out[11]: ['C:\\', 'lala', 'lolo', 'haha.dat']

With your testcase:

In [12]: testcase = paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c',
    ...: ...     'a/b/../../a/b/c/', 'a/b/../../a/b/c']

In [14]: for t in testcase:
    ...:     print(path2unix(t)[-1])
    ...:
    ...:
c
c
c
c
c
c
c

The idea here is to convert all paths into the unified internal representation of pathlib2, with different decoders depending on the platform. Fortunately, pathlib2 includes a generic decoder called PurePath that should work on any path. In case this does not work, you can force the recognition of windows path using fromwinpath=True. This will split the input string into parts, the last one is the leaf you are looking for, hence the path2unix(t)[-1].

If the argument nojoin=False, the path will be joined back, so that the output is simply the input string converted to a Unix format, which can be useful to compare subpaths across platforms.

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

Call parent method from child class c#

One way to do this would be to pass the instance of ParentClass to the ChildClass on construction

public ChildClass
{
    private ParentClass parent;

    public ChildClass(ParentClass parent)
    {
        this.parent = parent;
    }

    public void LoadData(DateTable dt)
    {
       // do something
       parent.CurrentRow++; // or whatever.
       parent.UpdateProgressBar(); // Call the method
    }
}

Make sure to pass the reference to this when constructing ChildClass inside parent:

if(loadData){

     ChildClass childClass = new ChildClass(this); // here

     childClass.LoadData(this.Datatable);

}

Caveat: This is probably not the best way to organise your classes, but it directly answers your question.

EDIT: In the comments you mention that more than 1 parent class wants to use ChildClass. This is possible with the introduction of an interface, eg:

public interface IParentClass
{
    void UpdateProgressBar();
    int CurrentRow{get; set;}
}

Now, make sure to implement that interface on both (all?) Parent Classes and change child class to this:

public ChildClass
{
    private IParentClass parent;

    public ChildClass(IParentClass parent)
    {
        this.parent = parent;
    }

    public void LoadData(DateTable dt)
    {
       // do something
       parent.CurrentRow++; // or whatever.
       parent.UpdateProgressBar(); // Call the method
    }
}

Now anything that implements IParentClass can construct an instance of ChildClass and pass this to its constructor.

Find nginx version?

If you don't know where it is, locate nginx first.

ps -ef | grep nginx

Then you will see something like this:

root      4801     1  0 May23 ?        00:00:00 nginx: master process /opt/nginx/sbin/nginx -c /opt/nginx/conf/nginx.conf
root     12427 11747  0 03:53 pts/1    00:00:00 grep --color=auto nginx
nginx    24012  4801  0 02:30 ?        00:00:00 nginx: worker process                              
nginx    24013  4801  0 02:30 ?        00:00:00 nginx: worker process

So now you already know where nginx is. You can use the -v or -V. Something like:

/opt/nginx/sbin/nginx -v

What is the purpose of the "final" keyword in C++11 for functions?

Supplement to Mario Knezovic 's answer:

class IA
{
public:
  virtual int getNum() const = 0;
};

class BaseA : public IA
{
public:
 inline virtual int getNum() const final {return ...};
};

class ImplA : public BaseA {...};

IA* pa = ...;
...
ImplA* impla = static_cast<ImplA*>(pa);

//the following line should cause compiler to use the inlined function BaseA::getNum(), 
//instead of dynamic binding (via vtable or something).
//any class/subclass of BaseA will benefit from it

int n = impla->getNum();

The above code shows the theory, but not actually tested on real compilers. Much appreciated if anyone paste a disassembled output.

How do I reference a cell within excel named range?

Add a column to the left so that B10 to B20 is your named range Age.

Set A10 to A20 so that A10 = 1, A11= 2,... A20 = 11 and give the range A10 to A20 a name e.g. AgeIndex.

The 5th element can be then found by using an array formula:

=sum( Age * (1 * (AgeIndex = 5) )

As it's an array formula you'll need to press Ctrl + Shift + Return to make it work and not just return. Doing that, the formula will be turned into an array formula:

{=sum( Age * (1 * (AgeIndex = 5) )}

Twitter API - Display all tweets with a certain hashtag?

The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.

Remove Array Value By index in jquery

Your syntax is incorrect, you should either specify a hash:

hash = {abc: true, def: true, ghi: true};

Or an array:

arr = ['abc','def','ghi'];

You can effectively remove an item from a hash by simply setting it to null:

hash['def'] = null;
hash.def = null;

Or removing it entirely:

delete hash.def;

To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:

arr.splice(arr.indexOf("def"), 1);

This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:

arr.filter(function(item) { return item !== 'def'; });

This will create a new array with only elements that are not 'def'.

It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.

How to access random item in list?

I have been using this ExtensionMethod for a while:

public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int count)
{
    if (count <= 0)
      yield break;
    var r = new Random();
    int limit = (count * 10);
    foreach (var item in list.OrderBy(x => r.Next(0, limit)).Take(count))
      yield return item;
}

Remove plot axis values

Change the axis_colour to match the background and if you are modifying the background dynamically you will need to update the axis_colour simultaneously. * The shared picture shows the graph/plot example using mock data ()

### Main Plotting Function ###
plotXY <- function(time, value){

    ### Plot Style Settings ###

    ### default bg is white, set it the same as the axis-colour 
    background <- "white"

    ### default col.axis is black, set it the same as the background to match
    axis_colour <- "white"

    plot_title <- "Graph it!"
    xlabel <- "Time"
    ylabel <- "Value"
    label_colour <- "black"
    label_scale <- 2
    axis_scale <- 2
    symbol_scale <- 2
    title_scale <- 2
    subtitle_scale <- 2
    # point style 16 is a black dot
    point <- 16 
    # p - points, l - line, b - both
    plot_type <- "b"

    plot(time, value, main=plot_title, cex=symbol_scale, cex.lab=label_scale, cex.axis=axis_scale, cex.main=title_scale, cex.sub=subtitle_scale, xlab=xlabel, ylab=ylabel, col.lab=label_colour, col.axis=axis_colour, bg=background, pch=point, type=plot_type)
}

plotXY(time, value)

enter image description here

How to pop an alert message box using PHP?

You could use Javascript:

// This is in the PHP file and sends a Javascript alert to the client
$message = "wrong answer";
echo "<script type='text/javascript'>alert('$message');</script>";

How do I bind the enter key to a function in tkinter?

Another alternative is to use a lambda:

ent.bind("<Return>", (lambda event: name_of_function()))

Full code:

from tkinter import *
from tkinter.messagebox import showinfo

def reply(name):
    showinfo(title="Reply", message = "Hello %s!" % name)


top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")

Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)

top.mainloop()

As you can see, creating a lambda function with an unused variable "event" solves the problem.

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

What is the purpose of using -pedantic in GCC/G++ compiler?

GCC compilers always try to compile your program if this is at all possible. However, in some cases, the C and C++ standards specify that certain extensions are forbidden. Conforming compilers such as gcc or g++ must issue a diagnostic when these extensions are encountered. For example, the gcc compiler’s -pedantic option causes gcc to issue warnings in such cases. Using the stricter -pedantic-errors option converts such diagnostic warnings into errors that will cause compilation to fail at such points. Only those non-ISO constructs that are required to be flagged by a conforming compiler will generate warnings or errors.

grep for special characters in Unix

The one that worked for me is:

grep -e '->'

The -e means that the next argument is the pattern, and won't be interpreted as an argument.

From: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/

gcc/g++: "No such file or directory"

this works for me, sudo apt-get install libx11-dev

Show all tables inside a MySQL database using PHP?

<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
//Try This code is running perfectly !!!!!!!!!!


How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

How to find locked rows in Oracle

Oracle's locking concept is quite different from that of the other systems.

When a row in Oracle gets locked, the record itself is updated with the new value (if any) and, in addition, a lock (which is essentially a pointer to transaction lock that resides in the rollback segment) is placed right into the record.

This means that locking a record in Oracle means updating the record's metadata and issuing a logical page write. For instance, you cannot do SELECT FOR UPDATE on a read only tablespace.

More than that, the records themselves are not updated after commit: instead, the rollback segment is updated.

This means that each record holds some information about the transaction that last updated it, even if the transaction itself has long since died. To find out if the transaction is alive or not (and, hence, if the record is alive or not), it is required to visit the rollback segment.

Oracle does not have a traditional lock manager, and this means that obtaining a list of all locks requires scanning all records in all objects. This would take too long.

You can obtain some special locks, like locked metadata objects (using v$locked_object), lock waits (using v$session) etc, but not the list of all locks on all objects in the database.

Show/hide div if checkbox selected

You would need to always consider the state of all checkboxes!

You could increase or decrease a number on checking or unchecking, but imagine the site loads with three of them checked.

So you always need to check all of them:

<script type="text/javascript">
<!--
function showMe (it, box) {
  // consider all checkboxes with same name
  var checked = amountChecked(box.name);

  var vis = (checked >= 3) ? "block" : "none";
  document.getElementById(it).style.display = vis;
}

function amountChecked(name) {
  var all = document.getElementsByName(name);

  // count checked
  var result = 0;
  all.forEach(function(el) {
    if (el.checked) result++;
  });

  return result;
}
//-->
</script>

How to select top n rows from a datatable/dataview in ASP.NET

I just used Midhat's answer but appended CopyToDataTable() on the end.

The code below is an extension to the answer that I used to quickly enable some paging.

int pageNum = 1;
int pageSize = 25;

DataTable dtPage = dt.Rows.Cast<System.Data.DataRow>().Skip((pageNum - 1) * pageSize).Take(pageSize).CopyToDataTable();

How do I read the first line of a file using cat?

Use the below command to get the first row from a CSV file or any file formats.

head -1 FileName.csv

Is there a C++ decompiler?

I haven't seen any decompilers that generate C++ code. I've seen a few experimental ones that make a reasonable attempt at generating C code, but they tended to be dependent on matching the code-generation patterns of a particular compiler (that may have changed, it's been awhile since I last looked into this). Of course any symbolic information will be gone. Google for "decompiler".

Python dict how to create key or append an element to key?

dictionary['key'] = dictionary.get('key', []) + list_to_append

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

Encountered this error while using maven-shade-plugin, the solution was including:

META-INF/spring.schemas

and

META-INF/spring.handlers

transformers in the maven-shade-plugin when building...

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>shade</goal>
                </goals>
                <configuration>
                    <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.handlers</resource>
                        </transformer>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.schemas</resource>
                        </transformer>
                    </transformers>
                </configuration>
            </execution>
        </executions>
    </plugin>

(Credits: Idea to avoid that spring.handlers/spring.schemas get overwritten when merging multiple spring dependencies in a single jar)

Android : Capturing HTTP Requests with non-rooted android device

I just installed Drony, is not shareware and it does no require root on cellphone with Android 3.x or above

https://play.google.com/store/apps/details?id=org.sandroproxy.drony

It intercepts the requests and are shown on a LOG

Month name as a string

Use this :

Calendar cal=Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMM");
String month_name = month_date.format(cal.getTime());

Month name will contain the full month name,,if you want short month name use this

 SimpleDateFormat month_date = new SimpleDateFormat("MMM");
 String month_name = month_date.format(cal.getTime());

Graph visualization library in JavaScript

JsVIS was pretty nice, but slow with larger graphs, and has been abandoned since 2007.

prefuse is a set of software tools for creating rich interactive data visualizations in Java. flare is an ActionScript library for creating visualizations that run in the Adobe Flash Player, abandoned since 2012.

How to preview a part of a large pandas DataFrame, in iPython notebook?

I found the following approach to be the most effective for sampling a DataFrame:

print(df[A:B]) ## 'A' and 'B' are the first and last records in range

For example, print(df[10:15]) will print rows 10 through 15 - inclusive - from your data set.

Python: How to create a unique file name?

The uuid module would be a good choice, I prefer to use uuid.uuid4().hex as random filename because it will return a hex string without dashes.

import uuid
filename = uuid.uuid4().hex

The outputs should like this:

>>> import uuid
>>> uuid.uuid()
UUID('20818854-3564-415c-9edc-9262fbb54c82')
>>> str(uuid.uuid4())
'f705a69a-8e98-442b-bd2e-9de010132dc4'
>>> uuid.uuid4().hex
'5ad02dfb08a04d889e3aa9545985e304'  # <-- this one

CSS3 transition doesn't work with display property

You cannot use height: 0 and height: auto to transition the height. auto is always relative and cannot be transitioned towards. You could however use max-height: 0 and transition that to max-height: 9999px for example.

Sorry I couldn't comment, my rep isn't high enough...

Programmatically add custom event in the iPhone Calendar

Yes there still is no API for this (2.1). But it seemed like at WWDC a lot of people were already interested in the functionality (including myself) and the recommendation was to go to the below site and create a feature request for this. If there is enough of an interest, they might end up moving the ICal.framework to the public SDK.

https://developer.apple.com/bugreporter/

Using Jquery Ajax to retrieve data from Mysql

For retrieving data using Ajax + jQuery, you should write the following code:

 <html>
 <script type="text/javascript" src="jquery-1.3.2.js"> </script>

 <script type="text/javascript">

 $(document).ready(function() {

    $("#display").click(function() {                

      $.ajax({    //create an ajax request to display.php
        type: "GET",
        url: "display.php",             
        dataType: "html",   //expect html to be returned                
        success: function(response){                    
            $("#responsecontainer").html(response); 
            //alert(response);
        }

    });
});
});

</script>

<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
   <tr>
       <td> <input type="button" id="display" value="Display All Data" /> </td>
   </tr>
</table>
<div id="responsecontainer" align="center">

</div>
</body>
</html>

For mysqli connection, write this:

<?php 
$con=mysqli_connect("localhost","root",""); 

For displaying the data from database, you should write this :

<?php
include("connection.php");
mysqli_select_db("samples",$con);
$result=mysqli_query("select * from student",$con);

echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";

while($data = mysqli_fetch_row($result))
{   
    echo "<tr>";
    echo "<td align=center>$data[0]</td>";
    echo "<td align=center>$data[1]</td>";
    echo "<td align=center>$data[2]</td>";
    echo "<td align=center>$data[3]</td>";
    echo "<td align=center>$data[4]</td>";
    echo "</tr>";
}
echo "</table>";
?>

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)

When on Ubuntu 18.04 using Python3.6 I have solved the problem doing both:

with open(filename, encoding="utf-8") as lines:

and if you are running the tool as command line:

export LC_ALL=C.UTF-8

Note that if you are in Python2.7 you have do to handle this differently. First you have to set the default encoding:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

and then to load the file you must use io.open to set the encoding:

import io
with io.open(filename, 'r', encoding='utf-8') as lines:

You still need to export the env

export LC_ALL=C.UTF-8

How to implement Enums in Ruby?

If you're worried about typos with symbols, make sure your code raises an exception when you access a value with a non-existent key. You can do this by using fetch rather than []:

my_value = my_hash.fetch(:key)

or by making the hash raise an exception by default if you supply a non-existent key:

my_hash = Hash.new do |hash, key|
  raise "You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}"
end

If the hash already exists, you can add on exception-raising behaviour:

my_hash = Hash[[[1,2]]]
my_hash.default_proc = proc do |hash, key|
  raise "You tried to access using #{key.inspect} when the only keys we have are #{hash.keys.inspect}"
end

Normally, you don't have to worry about typo safety with constants. If you misspell a constant name, it'll usually raise an exception.

Remove carriage return from string

I just had the same issue in my code today and tried which worked like a charm.

.Replace("\r\n")

mysql stored-procedure: out parameter

I know this is an old thread, but if anyone is looking for an answer of why their procedures doesn't work in the workbench and think the only result is "Query canceled" or anything like that without clues:

the output with errors or problems is hiddenl. I do not know why, I do understand it's annoying, but it is there. just move your cursor above the line above the message, it will turn in an double arrow (up and down) you can then click and drag that line up, then you will see a console with the message you missed!

How to access the GET parameters after "?" in Express?

Use req.query, for getting he value in query string parameter in the route. Refer req.query. Say if in a route, http://localhost:3000/?name=satyam you want to get value for name parameter, then your 'Get' route handler will go like this :-

app.get('/', function(req, res){
    console.log(req.query.name);
    res.send('Response send to client::'+req.query.name);

});

Cannot find "Package Explorer" view in Eclipse

The simplest, and best long-term solution

Go to the main menu on top of Eclipse and locate Window next to Run and expand it.

 Window->Reset Perspective... to restore all views to their defaults

It will reset the default setting.

Validate form field only on submit or user input

If you want to show error messages on form submission, you can use condition form.$submitted to check if an attempt was made to submit the form. Check following example.

<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
  <input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user name.</div>
  </div>

  <input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user address.</div>
    <div ng-message="maxlength">Should be less than 30 chars</div>
  </div>

  <button type="submit">
    Create user
  </button>
</form>

Constraint Layout Vertical Align Center

It's possible to set the center aligned view as an anchor for other views. In the example below "@+id/stat_2" centered horizontally in parent and it serves as an anchor for other views in this layout.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/stat_1"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:gravity="center"
        android:maxLines="1"
        android:text="10"
        android:textColor="#777"
        android:textSize="22sp"
        app:layout_constraintTop_toTopOf="@+id/stat_2"
        app:layout_constraintEnd_toStartOf="@+id/divider_1" />

    <TextView
        android:id="@+id/stat_detail_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Streak"
        android:textColor="#777"
        android:textSize="12sp"
        app:layout_constraintTop_toBottomOf="@+id/stat_1"
        app:layout_constraintStart_toStartOf="@+id/stat_1"
        app:layout_constraintEnd_toEndOf="@+id/stat_1" />

    <View
        android:id="@+id/divider_1"
        android:layout_width="1dp"
        android:layout_height="0dp"
        android:layout_marginEnd="16dp"
        android:background="#ccc"
        app:layout_constraintTop_toTopOf="@+id/stat_2"
        app:layout_constraintEnd_toStartOf="@+id/stat_2"
        app:layout_constraintBottom_toBottomOf="@+id/stat_detail_2" />

    <TextView
        android:id="@+id/stat_2"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:maxLines="1"
        android:text="243"
        android:textColor="#777"
        android:textSize="22sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent" />

    <TextView
        android:id="@+id/stat_detail_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="Calories Burned"
        android:textColor="#777"
        android:textSize="12sp"
        app:layout_constraintTop_toBottomOf="@+id/stat_2"
        app:layout_constraintStart_toStartOf="@+id/stat_2"
        app:layout_constraintEnd_toEndOf="@+id/stat_2" />

    <View
        android:id="@+id/divider_2"
        android:layout_width="1dp"
        android:layout_height="0dp"
        android:layout_marginStart="16dp"
        android:background="#ccc"
        app:layout_constraintBottom_toBottomOf="@+id/stat_detail_2"
        app:layout_constraintStart_toEndOf="@+id/stat_2"
        app:layout_constraintTop_toTopOf="@+id/stat_2" />

    <TextView
        android:id="@+id/stat_3"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:gravity="center"
        android:maxLines="1"
        android:text="3200"
        android:textColor="#777"
        android:textSize="22sp"
        app:layout_constraintTop_toTopOf="@+id/stat_2"
        app:layout_constraintStart_toEndOf="@+id/divider_2" />

    <TextView
        android:id="@+id/stat_detail_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="Steps"
        android:textColor="#777"
        android:textSize="12sp"
        app:layout_constraintTop_toBottomOf="@+id/stat_3"
        app:layout_constraintStart_toStartOf="@+id/stat_3"
        app:layout_constraintEnd_toEndOf="@+id/stat_3" />

</android.support.constraint.ConstraintLayout>

Here's how it works on smallest smartphone (3.7 480x800 Nexus One) vs largest smartphone (5.5 1440x2560 Pixel XL)

Result view

The module ".dll" was loaded but the entry-point was not found

I found the answer: I need to add a new application to the service components in my computer and then add the right DLL's.

Thanks! If anyone has the same problem, I'll be happy to help.

Default Activity not found in Android Studio

I have tried all solutions, but not working at all. than I have tried to disable Instant run in my android studio.

Go to Android Studio Settings or Preferences (for MAC) -> Build,Execution,Deployment -> Instant Run.

uncheck the Instant run functionality and than after click sync project with gradle files from file menu

now run your build...

Change date format in a Java string

You can also use substring()

String date_s = "2011-01-18 00:00:00.0";
date_s.substring(0,10);

If you want a space in front of the date, use

String date_s = " 2011-01-18 00:00:00.0";
date_s.substring(1,11);

How to create a timer using tkinter?

I just created a simple timer using the MVP pattern (however it may be overkill for that simple project). It has quit, start/pause and a stop button. Time is displayed in HH:MM:SS format. Time counting is implemented using a thread that is running several times a second and the difference between the time the timer has started and the current time.

Source code on github

Create Elasticsearch curl query for not null and not empty("")

You can use not filter on top of missing.

"query": {
  "filtered": {
     "query": {
        "match_all": {}
     },
     "filter": {
        "not": {
           "filter": {
              "missing": {
                 "field": "searchField"
              }
           }
        }
     }
  }
}

How to use jquery $.post() method to submit form values

Yor $.post has no data. You need to pass the form data. You can use serialize() to post the form data. Try this

$("#post-btn").click(function(){
    $.post("process.php", $('#reg-form').serialize() ,function(data){
        alert(data);
    });
});

Color different parts of a RichTextBox string

I think modifying a "selected text" in a RichTextBox isn't the right way to add colored text. So here a method to add a "color block" :

        Run run = new Run("This is my text");
        run.Foreground = new SolidColorBrush(Colors.Red); // My Color
        Paragraph paragraph = new Paragraph(run);
        MyRichTextBlock.Document.Blocks.Add(paragraph);

From MSDN :

The Blocks property is the content property of RichTextBox. It is a collection of Paragraph elements. Content in each Paragraph element can contain the following elements:

  • Inline

  • InlineUIContainer

  • Run

  • Span

  • Bold

  • Hyperlink

  • Italic

  • Underline

  • LineBreak

So I think you have to split your string depending on parts color, and create as many Run objects as needed.

How to change the minSdkVersion of a project?

This is what worked for me:

In the build.gradle file, setting the minSdkVersion under defaultConfig:

enter image description here

Good Luck...

How to set image for bar button with swift?

I have achieved that programatically with this code:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        //set image for button
        button.setImage(UIImage(named: "fb.png"), forState: UIControlState.Normal)
        //add function for button
        button.addTarget(self, action: "fbButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
        //set frame
        button.frame = CGRectMake(0, 0, 53, 31)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    func fbButtonPressed() {

        println("Share to fb")
    }
}

And result will be:

enter image description here

Same way you can set button for left side too this way:

self.navigationItem.leftBarButtonItem = barButton

And result will be:

enter image description here

And if you want same transaction as navigation controller have when you go back with default back button then you can achieve that with custom back button with this code:

func backButtonPressed(sender:UIButton) {
    navigationController?.popViewControllerAnimated(true)
}

For swift 3.0:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button = UIButton.init(type: .custom)
        //set image for button
        button.setImage(UIImage(named: "fb.png"), for: UIControlState.normal)
        //add function for button
        button.addTarget(self, action: #selector(ViewController.fbButtonPressed), for: UIControlEvents.touchUpInside)
        //set frame
        button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    func fbButtonPressed() {

        print("Share to fb")
    }
}

For swift 4.0:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button = UIButton(type: .custom)
        //set image for button
        button.setImage(UIImage(named: "fb.png"), for: .normal)
        //add function for button
        button.addTarget(self, action: #selector(fbButtonPressed), for: .touchUpInside)
        //set frame
        button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    @objc func fbButtonPressed() {

        print("Share to fb")
    }
}

How do I uninstall nodejs installed from pkg (Mac OS X)?

I ran:

lsbom -f -l -s -pf /var/db/receipts/org.nodejs.pkg.bom \
| while read i; do
  sudo rm /usr/local/${i}
done
sudo rm -rf /usr/local/lib/node \
     /usr/local/lib/node_modules \
     /var/db/receipts/org.nodejs.*

Coded into gist 2697848

Update It seems the receipts .bom file name may have changed so you may need to replace org.nodejs.pkg.bom with org.nodejs.node.pkg.bom in the above. The gist has been updated accordingly.

How to put Google Maps V2 on a Fragment using ViewPager

This is the Kotlin way:

In fragment_map.xml you should have:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

In your MapFragment.kt you should have:

    private fun setupMap() {
        (childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?)!!.getMapAsync(this)
    }

Call setupMap() in onCreateView.

The way to check a HDFS directory's size?

hadoop version 2.3.33:

hadoop fs -dus  /path/to/dir  |   awk '{print $2/1024**3 " G"}' 

enter image description here

Get integer value from string in swift

I'd use:

var stringNumber = "1234"
var numberFromString = stringNumber.toInt()
println(numberFromString)

Note toInt():

If the string represents an integer that fits into an Int, returns the corresponding integer.

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

You can use GNU Parallel for this as it works as a mutex when called as sem. So, in concrete terms, you can use:

sem --id SCRIPTSINGLETON yourScript

If you want a timeout too, use:

sem --id SCRIPTSINGLETON --semaphoretimeout -10 yourScript

Timeout of <0 means exit without running script if semaphore is not released within the timeout, timeout of >0 mean run the script anyway.

Note that you should give it a name (with --id) else it defaults to the controlling terminal.

GNU Parallel is a very simple install on most Linux/OSX/Unix platforms - it is just a Perl script.

What is difference between INNER join and OUTER join

Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
Left outer join - A left outer join will give all rows in A, plus any common rows in B.
Full outer join - A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa. check this

How do I convert datetime.timedelta to minutes, hours in Python?

There's no built-in formatter for timedelta objects, but it's pretty easy to do it yourself:

days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

Or, equivalently, if you're in Python 2.7+ or 3.2+:

seconds = duration.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

Now you can print it however you want:

'{} minutes, {} hours'.format(minutes, hours)

For example:

def convert_timedelta(duration):
    days, seconds = duration.days, duration.seconds
    hours = days * 24 + seconds // 3600
    minutes = (seconds % 3600) // 60
    seconds = (seconds % 60)
    return hours, minutes, seconds
td = datetime.timedelta(2, 7743, 12345)
hours, minutes, seconds = convert_timedelta(td)
print '{} minutes, {} hours'.format(minutes, hours)

This will print:

9 minutes, 50 hours

If you want to get "10 minutes, 1 hour" instead of "10 minutes, 1 hours", you need to do that manually too:

print '{} minute{}, {} hour{}'.format(minutes, 's' if minutes != 1 else '',
                                      hours, 's' if minutes != 1 else '')

Or you may want to write an english_plural function to do the 's' bits for you, instead of repeating yourself.

From your comments, it sounds like you actually want to keep the days separate. That's even easier:

def convert_timedelta(duration):
    days, seconds = duration.days, duration.seconds
    hours = seconds // 3600
    minutes = (seconds % 3600) // 60
    seconds = (seconds % 60)
    return days, hours, minutes, seconds

If you want to convert this to a single value to store in a database, then convert that single value back to format it, do this:

def dhms_to_seconds(days, hours, minutes, seconds):
    return (((days * 24) + hours) * 60 + minutes) * 60 + seconds

def seconds_to_dhms(seconds):
    days = seconds // (3600 * 24)
    hours = (seconds // 3600) % 24
    minutes = (seconds // 60) % 60
    seconds = seconds % 60
    return days, hours, minutes, seconds

So, putting it together:

def store_timedelta_in_database(thingy, duration):
    seconds = dhms_to_seconds(*convert_timedelta(duration))
    db.execute('INSERT INTO foo (thingy, duration) VALUES (?, ?)',
               thingy, seconds)
    db.commit()

def print_timedelta_from_database(thingy):
    cur = db.execute('SELECT duration FROM foo WHERE thingy = ?', thingy)
    seconds = int(cur.fetchone()[0])
    days, hours, minutes, seconds = seconds_to_dhms(seconds)
    print '{} took {} minutes, {} hours, {} days'.format(thingy, minutes, hours, days)

Json.NET serialize object with root name

[Newtonsoft.Json.JsonObject(Title = "root")]
public class TestMain

this is the only attrib you need to add to get your code working.

Extract data from XML Clob using SQL from Oracle Database

Try

SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]') 
FROM traptabclob;

Here is a sqlfiddle demo

brew install mysql on macOS

Homebrew

  1. First, make sure you have homebrew installed
  2. Run brew doctor and address anything homebrew wants you to fix
  3. Run brew install mysql
  4. Run brew services restart mysql
  5. Run mysql.server start
  6. Run mysql_secure_installation

Laravel Eloquent where field is X or null

Using coalesce() converts null to 0:

$query = Model::where('field1', 1)
    ->whereNull('field2')
    ->where(DB::raw('COALESCE(datefield_at,0)'), '<', $date)
;

Convert timestamp long to normal date format

Let me propose this solution for you. So in your managed bean, do this

public String convertTime(long time){
    Date date = new Date(time);
    Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    return format.format(date);
}

so in your JSF page, you can do this (assuming foo is the object that contain your time)

<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />

If you have multiple pages that want to utilize this method, you can put this in an abstract class and have your managed bean extend this abstract class.

EDIT: Return time with TimeZone

unfortunately, I think SimpleDateFormat will always format the time in local time, so we can't use SimpleDateFormat anymore. So to display time in different TimeZone, we can do this

public String convertTimeWithTimeZome(long time){
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(time);
    return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " " 
            + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":"
            + cal.get(Calendar.MINUTE));

}

A better solution is to utilize JodaTime. In my opinion, this API is much better than Calendar (lighter weight, faster and provide more functionality). Plus Calendar.Month of January is 0, that force developer to add 1 to the result, and you have to format the time yourself. Using JodaTime, you can fix all of that. Correct me if I am wrong, but I think JodaTime is incorporated in JDK7

Refreshing all the pivot tables in my excel workbook with a macro

ActiveWorkbook.RefreshAll refreshes everything, not only the pivot tables but also the ODBC queries. I have a couple of VBA queries that refer to Data connections and using this option crashes as the command runs the Data connections without the detail supplied from the VBA

I recommend the option if you only want the pivots refreshed

Sub RefreshPivotTables()     
  Dim pivotTable As PivotTable     
  For Each pivotTable In ActiveSheet.PivotTables         
    pivotTable.RefreshTable     
  Next 
End Sub 

What is the difference between visibility:hidden and display:none?

There is a big difference when it comes to child nodes. For example: If you have a parent div and a nested child div. So if you write like this:

<div id="parent" style="display:none;">
    <div id="child" style="display:block;"></div>
</div>

In this case none of the divs will be visible. But if you write like this:

<div id="parent" style="visibility:hidden;">
    <div id="child" style="visibility:visible;"></div>
</div>

Then the child div will be visible whereas the parent div will not be shown.

How do I right align div elements?

Old answers. An update: use flexbox, pretty much works in all browsers now.

_x000D_
_x000D_
<div style="display: flex; justify-content: flex-end">_x000D_
  <div>I'm on the right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And you can get even fancier, simply:

_x000D_
_x000D_
<div style="display: flex; justify-content: space-around">_x000D_
  <div>Left</div>_x000D_
  <div>Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And fancier:

_x000D_
_x000D_
<div style="display: flex; justify-content: space-around">_x000D_
   <div>Left</div>_x000D_
   <div>Middle</div>_x000D_
  <div>Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Display QImage with QtGui

Drawing an image using a QLabel seems like a bit of a kludge to me. With newer versions of Qt you can use a QGraphicsView widget. In Qt Creator, drag a Graphics View widget onto your UI and name it something (it is named mainImage in the code below). In mainwindow.h, add something like the following as private variables to your MainWindow class:

QGraphicsScene *scene;
QPixmap image;

Then just edit mainwindow.cpp and make the constructor something like this:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    image.load("myimage.png");
    scene = new QGraphicsScene(this);
    scene->addPixmap(image);
    scene->setSceneRect(image.rect());

    ui->mainImage->setScene(scene);
}

Collections sort(List<T>,Comparator<? super T>) method example

You probably want something like this:

Collections.sort(students, new Comparator<Student>() {
                     public int compare(Student s1, Student s2) {
                           if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
                               return s1.getName().compareTo(s2.getName());
                           } else {
                             return s1.getAge().compareTo(s2.getAge());
                          }
                      }
);

This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.

C# Copy a file to another location with a different name

File.Copy(@"C:\oldFile.txt", @"C:\newFile.txt", true);

Please do not forget to overwrite the previous file! Make sure you add the third param., by adding the third param, you allow the file to be overwritten. Else you could use a try catch for the exception.

Regards, G

How to make a owl carousel with arrows instead of next previous

Complete tutorial here

Demo link

enter image description here

JavaScript

$('.owl-carousel').owlCarousel({
    margin: 10,
    nav: true,
    navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
    responsive: {
        0: {
            items: 1
        },
        600: {
            items: 3
        },
        1000: {
            items: 5
        }
    }
});

CSS Style for navigation

.owl-carousel .nav-btn{
  height: 47px;
  position: absolute;
  width: 26px;
  cursor: pointer;
  top: 100px !important;
}

.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}

.owl-carousel .prev-slide{
  background: url(nav-icon.png) no-repeat scroll 0 0;
  left: -33px;
}
.owl-carousel .next-slide{
  background: url(nav-icon.png) no-repeat scroll -24px 0px;
  right: -33px;
}
.owl-carousel .prev-slide:hover{
 background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}   

Bootstrap 3 jquery event for active tab change

Eric Saupe knows how to do it

_x000D_
_x000D_
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {_x000D_
  var target = $(e.target).attr("href") // activated tab_x000D_
  alert(target);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="myTab" class="nav nav-tabs">_x000D_
  <li class="active"><a href="#home" data-toggle="tab">Home</a></li>_x000D_
  <li class=""><a href="#profile" data-toggle="tab">Profile</a></li>_x000D_
</ul>_x000D_
<div id="myTabContent" class="tab-content">_x000D_
  <div class="tab-pane fade active in" id="home">_x000D_
    home tab!_x000D_
  </div>_x000D_
  <div class="tab-pane fade" id="profile">_x000D_
    profile tab!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to easily consume a web service from PHP

HI I got this from this site : http://forums.asp.net/t/887892.aspx?Consume+an+ASP+NET+Web+Service+with+PHP

The web service has method Add which takes two params:

<?php
    $client = new SoapClient("http://localhost/csharp/web_service.asmx?wsdl");

     print_r( $client->Add(array("a" => "5", "b" =>"2")));
?>

How do I pass multiple parameters in Objective-C?

You need to delimit each parameter name with a ":" at the very least. Technically the name is optional, but it is recommended for readability. So you could write:

- (NSMutableArray*)getBusStops:(NSString*)busStop :(NSSTimeInterval*)timeInterval;

or what you suggested:

- (NSMutableArray*)getBusStops:(NSString*)busStop forTime:(NSSTimeInterval*)timeInterval;

Why would $_FILES be empty when uploading files to PHP?

It is important to add enctype="multipart/form-data" to your form, example

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

Numpy: Get random set of rows from 2D array

This is a similar answer to the one Hezi Rasheff provided, but simplified so newer python users understand what's going on (I noticed many new datascience students fetch random samples in the weirdest ways because they don't know what they are doing in python).

You can get a number of random indices from your array by using:

indices = np.random.choice(A.shape[0], amount_of_samples, replace=False)

You can then use fancy indexing with your numpy array to get the samples at those indices:

A[indices]

This will get you the specified number of random samples from your data.

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

If you're looking for a way to show the hidden items in you array, you got to pass maxArrayLength: Infinity

console.log(util.inspect(value, { maxArrayLength: Infinity }));

Object does not support item assignment error

The error seems clear: model objects do not support item assignment. MyModel.objects.latest('id')['foo'] = 'bar' will throw this same error.

It's a little confusing that your model instance is called projectForm...

To reproduce your first block of code in a loop, you need to use setattr

for k,v in session_results.iteritems():
    setattr(projectForm, k, v)

Adding default parameter value with type hint in Python

I recently saw this one-liner:

def foo(name: str, opts: dict=None) -> str:
    opts = {} if not opts else opts
    pass

Getting error "The package appears to be corrupt" while installing apk file

In my case by making build, from Build> Build apks, it worked.

How to activate the Bootstrap modal-backdrop?

Just append a div with that class to body, then remove it when you're done:

// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);

// Remove it (later)
$(".modal-backdrop").remove();

Live Example:

_x000D_
_x000D_
$("input").click(function() {_x000D_
  var bd = $('<div class="modal-backdrop"></div>');_x000D_
  bd.appendTo(document.body);_x000D_
  setTimeout(function() {_x000D_
    bd.remove();_x000D_
  }, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
_x000D_
_x000D_

Delete a database in phpMyAdmin

How to delete a database in phpMyAdmin?

From the Operations tab of the database, look for (and click) the text Drop the database (DROP).

How do I make an HTTP request in Swift?

Another option is the Alamofire lib that offers Chainable Request / Response methods.

https://github.com/Alamofire/Alamofire

Making a Request

import Alamofire

Alamofire.request(.GET, "http://httpbin.org/get")

Response Handling

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .response { request, response, data, error in
              print(request)
              print(response)
              print(error)
          }

Xcode 9 Swift Language Version (SWIFT_VERSION)

This Solution works when nothing else works:

I spent more than a week to convert the whole project and came to a solution below:

First, de-integrate the cocopods dependency from the project and then start converting the project to the latest swift version.

Go to Project Directory in the Terminal and Type:

pod deintegrate

This will de-integrate cocopods from the project and No traces of CocoaPods will be left in the project. But at the same time, it won't delete the xcworkspace and podfiles. It's ok if they are present.

Now you have to open xcodeproj(not xcworkspace) and you will get lots of errors because you have called cocoapods dependency methods in your main projects.

So to remove those errors you have two options:

  1. Comment down all the code you have used from cocoapods library.
  2. Create a wrapper class which has dummy methods similar to cocopods library, and then call it.

Once all the errors get removed you can convert the code to the latest swift version.

Sometimes if you are getting weird errors then try cleaning derived data and try again.

How to convert byte[] to InputStream?

Should be easy to find in the javadocs...

byte[] byteArr = new byte[] { 0xC, 0xA, 0xF, 0xE };
InputStream is = new ByteArrayInputStream(byteArr);

case in sql stored procedure on SQL Server

(SELECT CASE WHEN (SELECT  Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 )=0 THEN 'Pending'
WHEN (SELECT  Salary FROM tbl_Salary WHERE Code=102 AND Month=1 AND Year=2020 AND )<>0 THEN (SELECT CASE  WHEN ISNULL(ChequeNo,0) IS NOT NULL   THEN 'Deposit' ELSE 'Pending' END AS Deposite FROM tbl_EEsi WHERE  AND (Month= 1) AND (Year = 2020) AND )END AS Stat)

How can I refresh c# dataGridView after update ?

Rebind your DatagridView to the source.

DataGridView dg1 = new DataGridView();
dg1.DataSource = src1;

// Update Data in src1

dg1.DataSource = null;
dg1.DataSource = src1;

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

How to check whether an object has certain method/property?

via Reflection

 var property = object.GetType().GetProperty("YourProperty")
 property.SetValue(object,some_value,null);

Similar is for methods

error: This is probably not a problem with npm. There is likely additional logging output above

I'm on Ubuntu 18.04. I fixed this problem by increasing the inotify max_user_watches using this command:

echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

This type of issue crops up for me now that I've moved to Python 3. I had no idea Python 2 was simply steam rolling any issues with file encoding.

I found this nice explanation of the differences and how to find a solution after none of the above worked for me.

http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html

In short, to make Python 3 behave as similarly as possible to Python 2 use:

with open(filename, encoding="latin-1") as datafile:
    # work on datafile here

However, read the article, there is no one size fits all solution.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

I got into this issue when I get the following error:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

when I was using slf4j-api-1.7.5.jar in my libs.

Inspite I tried with the whole suggested complement jars, like slf4j-log4j12-1.7.5.jar, slf4j-simple-1.7.5 the error message still persisted. The problem finally was solved when I added slf4j-jdk14-1.7.5.jar to the java libs.

Get the whole slf4j package at http://www.slf4j.org/download.html

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

private string ConvertTime(double miliSeconds)
{
    var timeSpan = TimeSpan.FromMilliseconds(totalMiliSeconds);
    // Converts the total miliseconds to the human readable time format
    return timeSpan.ToString(@"hh\:mm\:ss\:fff");
}

//Test

    [TestCase(1002, "00:00:01:002")]
    [TestCase(700011, "00:11:40:011")]
    [TestCase(113879834, "07:37:59:834")]
    public void ConvertTime_ResturnsCorrectString(double totalMiliSeconds, string expectedMessage)
    {
        // Arrange
        var obj = new Class();;

        // Act
        var resultMessage = obj.ConvertTime(totalMiliSeconds);

        // Assert
        Assert.AreEqual(expectedMessage, resultMessage);
    }

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

JavaScript Array Push key value

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

php hide ALL errors

The best way is to build your script in a way it cannot create any errors! When there is something that can create a Notice or an Error there is something wrong with your script and the checking of variables and environment!

If you want to hide them anyway: error_reporting(0);

How to get the number of columns in a matrix?

While size(A,2) is correct, I find it's much more readable to first define

rows = @(x) size(x,1); 
cols = @(x) size(x,2);

and then use, for example, like this:

howManyColumns_in_A = cols(A)
howManyRows_in_A    = rows(A)

It might appear as a small saving, but size(.., 1) and size(.., 2) must be some of the most commonly used functions, and they are not optimally readable as-is.

how to execute php code within javascript

You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).

If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.

Why do you want to do this?

How to execute a remote command over ssh with arguments?

I'm using the following to execute commands on the remote from my local computer:

ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2

Passing arrays as url parameter

Easiest way would be to use the serialize function.

It serializes any variable for storage or transfer. You can read about it in the php manual - serialize

The variable can be restored by using unserialize

So in the passing to the URL you use:

$url = urlencode(serialize($array))

and to restore the variable you use

$var = unserialize(urldecode($_GET['array']))

Be careful here though. The maximum size of a GET request is limited to 4k, which you can easily exceed by passing arrays in a URL.

Also, its really not quite the safest way to pass data! You should probably look into using sessions instead.

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

break x if ((int)strcmp(y, "hello")) == 0

On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!

How do I debug Windows services in Visual Studio?

Try Visual Studio's very own post-build event command line.

Try to add this in post-build:

@echo off
sc query "ServiceName" > nul
if errorlevel 1060 goto install
goto stop

:delete
echo delete
sc delete "ServiceName" > nul
echo %errorlevel%
goto install

:install
echo install
sc create "ServiceName" displayname= "Service Display Name" binpath= "$(TargetPath)" start= auto > nul
echo %errorlevel%
goto start

:start
echo start
sc start "ServiceName" > nul
echo %errorlevel%
goto end

:stop
echo stop
sc stop "ServiceName" > nul
echo %errorlevel%
goto delete

:end

If the build error with a message like Error 1 The command "@echo off sc query "ServiceName" > nul so on, Ctrl + C then Ctrl + V the error message into Notepad and look at the last sentence of the message.

It could be saying exited with code x. Look for the code in some common error here and see how to resolve it.

1072 -- Marked for deletion ? Close all applications that maybe using the service including services.msc and Windows event log.
1058 -- Can't be started because disabled or has no enabled associated devices ? just delete it.
1060 -- Doesn't exist ? just delete it.
1062 -- Has not been started ? just delete it.
1053 -- Didn't respond to start or control ? see event log (if logged to event log). It may be the service itself throwing an exception.
1056 -- Service is already running ? stop the service, and then delete.

More on error codes here.

And if the build error with message like this,

Error    11    Could not copy "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". Exceeded retry count of 10. Failed.    ServiceName
Error    12    Unable to copy file "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". The process cannot access the file 'bin\Debug\ServiceName.exe' because it is being used by another process.    ServiceName

open cmd, and then try to kill it first with taskkill /fi "services eq ServiceName" /f

If all is well, F5 should be sufficient to debug it.

Starting a shell in the Docker Alpine container

Usually, an Alpine Linux image doesn't contain bash, Instead you can use /bin/ash, /bin/sh, ash or only sh.

/bin/ash

docker run -it --rm alpine /bin/ash

/bin/sh

docker run -it --rm alpine /bin/sh

ash

docker run -it --rm alpine ash

sh

docker run -it --rm alpine sh

I hope this information helps you.

App can't be opened because it is from an unidentified developer

In terminal type the command:

xattr -d com.apple.quarantine [file path here]

Once you click enter it will no longer have that problem. Its annoying that apple adds a quarantine to files automatically. I do not know how to turn this off but there probably is a way...

How to drop unique in MySQL?

 ALTER TABLE [table name] DROP KEY [key name];

this will work.

How to get the path of a running JAR file?

Actually here is a better version - the old one failed if a folder name had a space in it.

  private String getJarFolder() {
    // get name and path
    String name = getClass().getName().replace('.', '/');
    name = getClass().getResource("/" + name + ".class").toString();
    // remove junk
    name = name.substring(0, name.indexOf(".jar"));
    name = name.substring(name.lastIndexOf(':')-1, name.lastIndexOf('/')+1).replace('%', ' ');
    // remove escape characters
    String s = "";
    for (int k=0; k<name.length(); k++) {
      s += name.charAt(k);
      if (name.charAt(k) == ' ') k += 2;
    }
    // replace '/' with system separator char
    return s.replace('/', File.separatorChar);
  }

As for failing with applets, you wouldn't usually have access to local files anyway. I don't know much about JWS but to handle local files might it not be possible to download the app.?

How to draw polygons on an HTML5 canvas?

Here is a function that even supports clockwise/anticlockwise drawing do that you control fills with the non-zero winding rule.

Here is a full article on how it works and more.

// Defines a path for any regular polygon with the specified number of sides and radius, 
// centered on the provide x and y coordinates.
// optional parameters: startAngle and anticlockwise

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
  if (sides < 3) return;
  var a = (Math.PI * 2)/sides;
  a = anticlockwise?-a:a;
  ctx.save();
  ctx.translate(x,y);
  ctx.rotate(startAngle);
  ctx.moveTo(radius,0);
  for (var i = 1; i < sides; i++) {
    ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
  }
  ctx.closePath();
  ctx.restore();
}

// Example using the function.
// Define a path in the shape of a pentagon and then fill and stroke it.
context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle="rgba(227,11,93,0.75)";
context.fill();
context.stroke();

Comparing arrays in C#

Providing that you have LINQ available and don't care too much about performance, the easiest thing is the following:

var arraysAreEqual = Enumerable.SequenceEqual(a1, a2);

In fact, it's probably worth checking with Reflector or ILSpy what the SequenceEqual methods actually does, since it may well optimise for the special case of array values anyway!

How to loop through an array containing objects and access their properties

This might help somebody. Maybe it's a bug in Node.

var arr = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
var c = 0;

This doesn't work:

while (arr[c].name) { c++; } // TypeError: Cannot read property 'name' of undefined

But this works...

while (arr[c]) { c++; } // Inside the loop arr[c].name works as expected.

This works too...

while ((arr[c]) && (arr[c].name)) { c++; }

BUT simply reversing the order does not work. I'm guessing there's some kind of internal optimization here that breaks Node.

while ((arr[c].name) && (arr[c])) { c++; }

Error says the array is undefined, but it's not :-/ Node v11.15.0

how to find seconds since 1970 in java

java.time

Using the java.time framework built into Java 8 and later.

import java.time.LocalDate;
import java.time.ZoneId;

int year = 2011;
int month = 10;
int day = 1;
int date = LocalDate.of(year, month, day);

date.atStartOfDay(ZoneId.of("UTC")).toEpochSecond; # Long = 1317427200

How to list AD group membership for AD users using input list?

The below code will return username group membership using the samaccountname. You can modify it to get input from a file or change the query to get accounts with non expiring passwords etc

$location = "c:\temp\Peace2.txt"
$users = (get-aduser -filter *).samaccountname
$le = $users.length
for($i = 0; $i -lt $le; $i++){
  $output = (get-aduser $users[$i] | Get-ADPrincipalGroupMembership).name
  $users[$i] + " " + $output 
  $z =  $users[$i] + " " + $output 
  add-content $location $z
}

Sample Output:

Administrator Domain Users Administrators Schema Admins Enterprise Admins Domain Admins Group Policy Creator Owners
Guest Domain Guests Guests
krbtgt Domain Users Denied RODC Password Replication Group
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production

Passing parameters in rails redirect_to

routes.rb

 match 'controller_name/action_name' => 'controller_name#action_name', via: [:get, :post], :as => :abc

Any controller you want to redirect with parameters are given below:

redirect_to abc_path(@abc, id: @id), :notice => "message fine" 

Youtube autoplay not working on mobile devices with embedded HTML5 player

The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
    </head>
  <body>
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      width: '100%',
      videoId: 'osz5tVY97dQ',
      playerVars: { 'autoplay': 1, 'playsinline': 1 },
      events: {
        'onReady': onPlayerReady
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
     event.target.mute();
    event.target.playVideo();
  }
</script>
  </body>
</html>

How to print colored text to the terminal?

Here is a simple function I use to print a text message in color without having to remember ANSI codes but rather using standard RGB tuples to define the foreground and background colors.

def print_in_color(txt_msg, fore_tuple, back_tuple, ):
    # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
    # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
    rf,bf,gf = fore_tuple
    rb,gb,bb = back_tuple
    msg = '{0}' + txt_msg
    mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
    print(msg .format(mat))
    print('\33[0m') # Returns default print color to back to black

# Example of use using a message with variables
fore_color = 'cyan'
back_color = 'dark green'
msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255), (0,127,127))

Make multiple-select to adjust its height to fit options without scroll bar

You can do this using the size attribute in the select tag. Supposing you have 8 options, then you would do it like:

<select name='courses' multiple="multiple" size='8'>