Programs & Examples On #Tfs

Team Foundation Server (TFS) is the on-premises version of Visual Studio Team Services (VSTS), providing Git and version control hosting, continuous integration, agile planning (issues, Kanban, Scrum, dashboards) and release management for continuous delivery to the cloud and on-premises.

How to unlock a file from someone else in Team Foundation Server

If you login into the source control with the admin account, you will be able to force undo checkout, or check in with any file you provide.

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.

I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.

Git vs Team Foundation Server

After some investigation between the pro and cons, the company I was involved with also decided to go for TFS. Not because GIT isn't a good version control system, but most importantly for the fully integrated ALM solution that TFS delivers. If only the version control feature was important, the choice may probably have been GIT. The steep GIT learning curve for regular developers may however not be underestimated.

See a detailed explanation in my blog post TFS as a true cross-technology platform.

How to ignore files/directories in TFS for avoiding them to go to central source repository?

For TFS 2013:

Start in VisualStudio-Team Explorer, in the PendingChanges Dialog undo the Changes whith the state [add], which should be ignored.

Visual Studio will detect the Add(s) again. Click On "Detected: x add(s)"-in Excluded Changes

In the opened "Promote Cadidate Changes"-Dialog You can easy exclude Files and Folders with the Contextmenu. Options are:

  • Ignore this item
  • Ignore by extension
  • Ignore by file name
  • Ignore by ffolder (yes ffolder, TFS 2013 Update 4/Visual Studio 2013 Premium Update 4)

Don't forget to Check In the changed .tfignore-File.

For VS 2015/2017:

The same procedure: In the "Excluded Changes Tab" in TeamExplorer\Pending Changes click on Detected: xxx add(s)

The Excluded Changes Tab in TeamExplorer\Pending Changes

The "Promote Candidate Changes" Dialog opens, and on the entries you can Right-Click for the Contextmenu. Typo is fixed now :-)

How can I completely remove TFS Bindings

Next works for me:

  1. Delete all .vssscc (solution binding) and .vspscc (project binding) files
  2. Remove block GlobalSection(TeamFoundationVersionControl) = preSolution from solution file

There could be also information regarding source control in the proj file in tags

<SccProjectName>SAK</SccProjectName> <SccLocalPath>SAK</SccLocalPath> <SccAuxPath>SAK</SccAuxPath> <SccProvider>SAK</SccProvider>

SAK states for "Should Already Know", so it can be kept.

git clone: Authentication failed for <URL>

In my case the error was some old username and password was stored in cache.

So I removed it by going to sourceTree and delete the existing account.

Now for the new clone then it will ask you for the password for the repo. enter image description here

How do I get my solution in Visual Studio back online in TFS?

One method I did with mine, is to "Add to Source Control", and select 'Git'.

The target principal name is incorrect. Cannot generate SSPI context

I had the same problem while using face recognition to logon to Windows 10. The workaround is to hold shift and right-click on the SSMS and use Run As Different User and provide username with password.

Source file 'Properties\AssemblyInfo.cs' could not be found

This can also happen if you have a solution containing the project open in Visual Studio, then use your source control software to change to an older commit that does not contain that project. Normally, this would be obvious as all the project files would disappear as well. But, if it's a new project with very few or no files at all, it could be puzzling to see that just this one file, AssemblyInfo.cs, is missing. And, it's more likely you'd be messing about with an AssemblyInfo.cs when a project is new, so might miss that another file or two is also missing.

The cure is to do any of the following:

  • Fetch the missing AssemblyInfo.cs and any other missing files from another commit, taking care to manage and save your .csproj file so the referenced files don't vanish from the project—perhaps by adding and removing a random .cs file to cause changes to need to be saved (since visual studio thinks the .csproj file has been saved when it hasn't).
  • Close and reopen Visual Studio without saving (if the project file isn't really saved) or remove the project. Removing makes sense if you didn't actually want the project created yet, since it will be created in the later commit.
  • Recreate the AssemblyInfo.cs file manually. Just copy another project, and change the details, especially the GUID so it matches the one from the .sln file.

Git in Visual Studio - add existing project?

Just right click on your solution and select Add to source control. Then select Git.

Now your projects has been added to a local source control. Right click on one of your files and select Commit.

Then enter a commit message and select Commit. Then select Sync to synchronise your project with GitHub. It requires having a Git repository. Go to GitHub, create a new repository, copy the repository link, and add it to your remote source control server. Select Publish.

That's all.

Why doesn't TFS get latest get the latest?

TFS, like some other source control providers, such as Perforce, do this, as the system knows what the last version you successfully got was, so get latest turns into "get changes since x". If you play by its rules and actually check things out before editing them, you don't confuse matters, and "get latest" really does as it says.

As you've seen, you can force it to reassess everything, which has a much greater bandwidth usage, but behaves closer to how SourceSafe used to.

Find in Files: Search all code in Team Foundation Server

If you install TFS 2008 PowerTools you will get a "Find in Source Control" action in the Team Explorer right click menu.

TFS2008 Power Tools

How to get tf.exe (TFS command line client)?

You need to install Team Explorer, it's best to install the version of Team Explorer that matches the version of TFS you are using e.g. if you're using TFS 2010 then install Team Explorer 2010.

2012 version http://www.microsoft.com/en-gb/download/details.aspx?id=30656

2013 version http://www.microsoft.com/en-us/download/details.aspx?id=40776

2019 version https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=TeamExplorer&rel=16

You also might be interested in the TFS power tools. They add some extra command line features (using tfpt.exe) and also add some extra IDE features.

What is Shelving in TFS?

@JaredPar: Yes you can use Shelvesets for reviews but keep in mind that shelvesets can be overwritten by yourself/others and therefore are not long term stable. Therefore for regulatory relevant reviews you should never use a Shelveset as base but rather a checkin (Changeset). For an informal review it is ok but not for a formal (E.g. FTA relevant) review!

How to retrieve the hash for the current commit in Git?

in your home-dir in file ".gitconfig" add the following

[alias]
sha = rev-parse HEAD

then you will have an easier command to remember:

$ git sha
59fbfdbadb43ad0b6154c982c997041e9e53b600

Error TF30063: You are not authorized to access ... \DefaultCollection

Just restarting the visual Studio would do the job. As I did this and it worked like a charm

How to connect TFS in Visual Studio code

It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".

Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

Team Build Error: The Path ... is already mapped to workspace

I had a similar issue and to remove the workspace that was causing me a problem, I logged into another machine with TFS client installed and performed the following:

  • On the File menu, point to Source Control, Advanced, and then click Workspaces....
  • In the Manage Workspaces dialog box, tick the Show remote packages checkbox.
  • Under the Name column, select the workspace that you want to remove, and then click Remove.
  • In the Confirmation dialog box, click OK.

How to remove a TFS Workspace Mapping?

The error is genuine. You might have created workspace with same name on different machine. Now you may have changed machine having different machine name.

So here is work-around that will definitely work.Following is work-around.

  1. Go to "Team-Explorer"
  2. Go to "Source-Control"
  3. Go to Workspace drop-down
  4. Click on "Workspaces..."
  5. A pop-up window will appear
  6. Click on "Show remote workspaces"
  7. Now delete the workspace which is conflicting and you can proceed your work.

How to work offline with TFS

I just wanted to include a link to a resolution to an issue I was having with VS2008 and TFS08.

I accidently opened my solution without being connected to my network and was not able to get it "back the way it was" and had to rebind every time I openned.

I found the solution here; http://www.fkollmann.de/v2/post/Visual-Studio-2008-refuses-to-bind-to-TFS-or-to-open-solution-source-controlled.aspx

Basically, you need to open the "Connect to Team Foundation Server" and then "Servers..." once there, Delete/Remove your server and re-add it. This fixed my issue.

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

Get size of all tables in database

 exec  sp_spaceused N'dbo.MyTable'

For all tables ,use..(adding from the comments of Paul)

exec sp_MSForEachTable 'exec sp_spaceused [?]'

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Future readers.

I have had the best luck figuring out these issues....using this method:

private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MyDaoObject.class);

@Transactional
public void save(MyObject item) {


    try {
         /* this is whatever code you have already...this is just an example */
        entityManager.persist(item);
        entityManager.flush();
    }
    catch(Exception ex)
    {
        /* below works in conjunction with concrete logging framework */
        logger.error(ex.getMessage(), ex);
        throw ex;
    }
}

Now, slf4j is just a fascade (interfaces, adapter)..... you need a concrete.

When picking log4j2, you want to persist the

%throwable

So you are not flying blind, you can see %throwable at the below URL (on how you defined %throwable so it shows up in the logging. If you're not using log4j2 as the concrete, you'll have to figure out your logging framework's version of %throwable)

https://www.baeldung.com/log4j2-appenders-layouts-filters

That %throwable, when logged, will have the actual SQL exception in it.

if throwable is giving you a fuss, you can do this (the below is NOT great since it does recursive log calls)

@Transactional
public void save(MyObject item) {


    try {
         /* this is whatever code you have already...this is just an example */
        entityManager.persist(item);
        entityManager.flush();
    catch(Exception ex)
    {
        logger.error(ex.getMessage(), ex);
        //throw ex;
        Throwable thr = ex;
        /* recursive logging warning !!! could perform very poorly, not for production....alternate idea is to use Stringbuilder and log the stringbuilder result */
        while (null != thr) {
            logger.error(thr.getMessage(), thr);
            thr = thr.getCause();
        }
    }
}

How to generate random positive and negative numbers in Java

Generate numbers between 0 and 65535 then just subtract 32768

How can I replace every occurrence of a String in a file with PowerShell?

This worked for me using the current working directory in PowerShell. You need to use the FullName property, or it won't work in PowerShell version 5. I needed to change the target .NET framework version in ALL my CSPROJ files.

gci -Recurse -Filter *.csproj |
% { (get-content "$($_.FullName)")
.Replace('<TargetFramework>net47</TargetFramework>', '<TargetFramework>net462</TargetFramework>') |
 Set-Content "$($_.FullName)"}

How to convert "0" and "1" to false and true

Set return type to numeric - you don't need a char (so don't use it); a numeric value (0/1) can be converted with Convert.ToBoolean(num)

Otherwise: use Kevin's answer

How to refresh materialized view in oracle

EXECUTE dbms_mview.refresh('view name','cf');

PHP Get Highest Value from Array

If you just want the largest value in the array use the max function. This will return the largest value, although not the corresponding key. It does not change the original array.

If you care about the the key you could then do

$key = array_search(max($array), $array)

(Edited to include @binaryLV's suggestion)

Change the spacing of tick marks on the axis of a plot?

And if you don't want R to add decimals or zeros, you can stop it from drawing the x axis or the y axis or both using ...axt. Then, you can add your own ticks and labels:

plot(x, y, xaxt="n")
plot(x, y, yaxt="n")
axis(1 or 2, at=c(1, 5, 10), labels=c("First", "Second", "Third"))

How to pass multiple values through command argument in Asp.net?

Use OnCommand event of imagebutton. Within it do

<asp:Button id="Button1" Text="Click" CommandName="Something" CommandArgument="your command arg" OnCommand="CommandBtn_Click" runat="server"/>

Code-behind:

void CommandBtn_Click(Object sender, CommandEventArgs e) 
{    
    switch(e.CommandName)
    {
        case "Something":
            // Do your code
            break;
        default:              
            break; 

    }
}

No Android SDK found - Android Studio

i have just discovered, android studio 3.0.1 has no sdk during the installation. because during the installation, it doesn't give sdk as part of install able unlike in recent versions of android studio.

Drawing rotated text on a HTML5 canvas

Here's an HTML5 alternative to homebrew: http://www.rgraph.net/ You might be able to reverse engineer their methods....

You might also consider something like Flot (http://code.google.com/p/flot/) or GCharts: (http://www.maxb.net/scripts/jgcharts/include/demo/#1) It's not quite as cool, but fully backwards compatible and scary easy to implement.

MySQL IF ELSEIF in select query

You have what you have used in stored procedures like this for reference, but they are not intended to be used as you have now. You can use IF as shown by duskwuff. But a Case statement is better for eyes. Like this:

select id, 
    (
    CASE 
        WHEN qty_1 <= '23' THEN price
        WHEN '23' > qty_1 && qty_2 <= '23' THEN price_2
        WHEN '23' > qty_2 && qty_3 <= '23' THEN price_3
        WHEN '23' > qty_3 THEN price_4
        ELSE 1
    END) AS total
 from product;

This looks cleaner. I suppose you do not require the inner SELECT anyway..

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

I don't have an exact solution, but I'll post my experiences with this in case they help anyone else.

From my testing, the gray screen is only triggered on slower machines [1]. To date, I have not been able to recreate it on newer hardware [2]. All of my tests have been in IE8 with Adobe Reader 10.1.2. For my tests I turned off SSL and removed all headers that could have disabled caching.

To recreate the gray screen, I followed the following steps:

1) Navigate to a page that links to a PDF
2) Open the PDF in a new window or tab (either via the context menu or target="_blank")
3) In my tests, this PDF will open without error (however I have received user reports indicating failure on the first PDF load)
4) Close the newly opened window or tab
5) Open the PDF (again) in a new window or tab
6) This PDF will not open, but instead only show the "gray screen" mentioned by the first user (all subsequent PDFs that are loaded will also not display -- until all browser windows are closed)

I performed the above test with several different PDF files (both static and dynamic) generated from different sources and the gray screen issue always occurs when following the above steps (on the "slow" computer).

To mitigate the problem in my application, I "tore down" the page that links to the PDF (removed parts piece by piece until the gray screen no longer occurred). In my particular application (built on closure-library) removing all references to goog.userAgent.adobeReader [3] appears to have fixed the issue. This exact solution won't work with jquery or .net MVC but maybe the process can help you isolate the source of the issue. I have not yet taken the time to isolate which particular portion of goog.userAgent.adobeReader triggers the bug in Adobe Reader, but it is likely that jquery might have similar plugin detection code to that used in closure-library.

[1] Machine experiencing gray screen:
Win Server '03 SP3
AMD Sempron 2400+ at 1.6GHz
256MB memory

[2] Machine not experiencing gray screen:
Win XP x64 SP2
AMD Athlon II X4 620 at 2.6 GHz
4GB memory

[3] http://closure-library.googlecode.com/svn/docs/closure_goog_useragent_adobereader.js.source.html

Passing parameters to a JQuery function

Using POST

function DoAction( id, name )
{
    $.ajax({
         type: "POST",
         url: "someurl.php",
         data: "id=" + id + "&name=" + name,
         success: function(msg){
                     alert( "Data Saved: " + msg );
                  }
    });
}

Using GET

function DoAction( id, name )
{
     $.ajax({
          type: "GET",
          url: "someurl.php",
          data: "id=" + id + "&name=" + name,
          success: function(msg){
                     alert( "Data Saved: " + msg );
                   }
     });
}

EDIT:

A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead.

<a href="/someurl.php?id=1&name=Jose" class="ajax-link"> Click </a>
<a href="/someurl.php?id=2&name=Juan" class="ajax-link"> Click </a>
<a href="/someurl.php?id=3&name=Pedro" class="ajax-link"> Click </a>
...
<a href="/someurl.php?id=n&name=xxx" class="ajax-link"> Click </a>

<script type="text/javascript">
$(function() {
   $('.ajax-link').click( function() {
         $.get( $(this).attr('href'), function(msg) {
              alert( "Data Saved: " + msg );
         });
         return false; // don't follow the link!
   });
});
</script>

Nested Git repositories?

Just for completeness:

There is another solution, I would recommend: subtree merging.

In contrast to submodules, it's easier to maintain. You would create each repository the normal way. While in your main repository, you want to merge the master (or any other branch) of another repository in a directory of your main directory.

$ git remote add -f OtherRepository /path/to/that/repo
$ git merge -s ours --no-commit OtherRepository/master
$ git read-tree --prefix=AnyDirectoryToPutItIn/ -u OtherRepository/master
$ git commit -m "Merge OtherRepository project as our subdirectory"`

Then, in order to pull the other repository into your directory (to update it), use the subtree merge strategy:

$ git pull -s subtree OtherRepository master

I'm using this method for years now, it works :-)

More about this way including comparing it with sub modules may be found in this git howto doc.

Why is the GETDATE() an invalid identifier

getdate() for MS-SQL, sysdate for Oracle server

Change div width live with jQuery

Got better solution:

$('#element').resizable({
    stop: function( event, ui ) {
        $('#element').height(ui.originalSize.height);
    }
});

Get individual query parameters from Uri

In a single line of code:

string xyz = Uri.UnescapeDataString(HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("XYZ"));

Check whether $_POST-value is empty

isset is testing whether or not the key you are checking in the hash (or associative array) is "set". Set in this context just means if it knows the value. Nothing is a value. So it is defined as being an empty string.

For that reason, as long as you have an input field named userName, regardless of if they fill it in, this will be true. What you really want to do is check if the userName is equal to an empty string ''

jquery to change style attribute of a div class

$('.handle').css('left', '300px');

$('.handle').css({
    left : '300px'
});

$('.handle').attr('style', 'left : 300px');

or use OrnaJS

How can I get the executing assembly version?

This should do:

Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();

How to convert 2D float numpy array to 2D int numpy array?

If you're not sure your input is going to be a Numpy array, you can use asarray with dtype=int instead of astype:

>>> np.asarray([1,2,3,4], dtype=int)
array([1, 2, 3, 4])

If the input array already has the correct dtype, asarray avoids the array copy while astype does not (unless you specify copy=False):

>>> a = np.array([1,2,3,4])
>>> a is np.asarray(a)  # no copy :)
True
>>> a is a.astype(int)  # copy :(
False
>>> a is a.astype(int, copy=False)  # no copy :)
True

C++ template constructor

You could do this:

class C 
{
public:
    template <typename T> C(T*);
};
template <typename T> T* UseType() 
{
    static_cast<T*>(nullptr);
}

Then to create an object of type C using int as the template parameter to the constructor:

C obj(UseType<int>());

Since you can't pass template parameters to a constructor, this solution essentially converts the template parameter to a regular parameter. Using the UseType<T>() function when calling the constructor makes it clear to someone looking at the code that the purpose of that parameter is to tell the constructor what type to use.

One use case for this would be if the constructor creates a derived class object and assigns it to a member variable that is a base class pointer. (The constructor needs to know which derived class to use, but the class itself doesn't need to be templated since the same base class pointer type is always used.)

Android: No Activity found to handle Intent error? How it will resolve

Intent intent=new Intent(String) is defined for parameter task, whereas you are passing parameter componentname into this, use instead:

Intent i = new Intent(Settings.this, com.scytec.datamobile.vd.gui.android.AppPreferenceActivity.class);
                    startActivity(i);

In this statement replace ActivityName by Name of Class of Activity, this code resides in.

How do you test your Request.QueryString[] variables?

Well for one thing use int.TryParse instead...

int id;
if (!int.TryParse(Request.QueryString["id"], out id))
{
    id = -1;
}

That assumes that "not present" should have the same result as "not an integer" of course.

EDIT: In other cases, when you're going to use request parameters as strings anyway, I think it's definitely a good idea to validate that they're present.

set serveroutput on in oracle procedure

First add next code in your sp:

BEGIN
    dbms_output.enable();
    dbms_output.put_line ('TEST LINE'); 
END;

Compile your code in your Oracle SQL developer. So go to Menu View--> dbms output. Click on Icon Green Plus and select your schema. Run your sp now.

PHP Fatal error: Class 'PDO' not found

I had to run the following on AWS EC2 Linux instance (PHP Version 7.3):

sudo yum install php73-php-pdo php73-php-mysqlnd

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

This should work. I just ran into your issue:

SET IDENTITY_INSERT dbo.tbl_A_archive ON;
INSERT INTO     dbo.tbl_A_archive (IdColumn,OtherColumn1,OtherColumn2,...)
SELECT  *
FROM        SERVER0031.DB.dbo.tbl_A;
SET IDENTITY_INSERT dbo.tbl_A_archive OFF;

Unfortunately it seems you do need a list of the columns including the identity column to insert records which specify the Identity. However, you don't HAVE to list the columns in the SELECT. As @Dave Cluderay suggested this will result in a formatted list for you to copy and paste (if less than 200000 characters).

I added the USE since I'm switching between instances.

USE PES
SELECT SUBSTRING(
    (SELECT ', ' + QUOTENAME(COLUMN_NAME)
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = 'Provider'
        ORDER BY ORDINAL_POSITION
        FOR XML path('')),
    3,
    200000);

Objective C - Assign, Copy, Retain

The Memory Management Programming Guide from the iOS Reference Library has basics of assign, copy, and retain with analogies and examples.

copy Makes a copy of an object, and returns it with retain count of 1. If you copy an object, you own the copy. This applies to any method that contains the word copy where “copy” refers to the object being returned.

retain Increases the retain count of an object by 1. Takes ownership of an object.

release Decreases the retain count of an object by 1. Relinquishes ownership of an object.

Java - removing first character of a string

Use substring() and give the number of characters that you want to trim from front.

String value = "Jamaica";
value = value.substring(1);

Answer: "amaica"

How do I get the unix timestamp in C as an int?

Is just casting the value returned by time()

#include <stdio.h>
#include <time.h>

int main(void) {
    printf("Timestamp: %d\n",(int)time(NULL));
    return 0;
}

what you want?

$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167

To get microseconds since the epoch, from C11 on, the portable way is to use

int timespec_get(struct timespec *ts, int base)

Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime or gettimeofday (marked obsolete in POSIX.1-2008, which recommends clock_gettime).

The code for both functions is nearly identical:

#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>

int main(void) {

    struct timespec tms;

    /* The C11 way */
    /* if (! timespec_get(&tms, TIME_UTC)) { */

    /* POSIX.1-2008 way */
    if (clock_gettime(CLOCK_REALTIME,&tms)) {
        return -1;
    }
    /* seconds, multiplied with 1 million */
    int64_t micros = tms.tv_sec * 1000000;
    /* Add full microseconds */
    micros += tms.tv_nsec/1000;
    /* round up if necessary */
    if (tms.tv_nsec % 1000 >= 500) {
        ++micros;
    }
    printf("Microseconds: %"PRId64"\n",micros);
    return 0;
}

Get only the Date part of DateTime in mssql

We can use this method:

CONVERT(VARCHAR(10), GETDATE(), 120)

Last parameter changes the format to only to get time or date in specific formats.

Why is NULL undeclared?

NULL isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef> or #include <stddef.h> should be sufficient.

The definition of NULL is guaranteed to be available if you include cstddef or stddef.h. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.

Display JSON as HTML

SyntaxHighlighter is a fully functional self-contained code syntax highlighter developed in JavaScript. To get an idea of what SyntaxHighlighter is capable of, have a look at the demo page.

How do I compare two columns for equality in SQL Server?

A solution avoiding CASE WHEN is to use COALESCE.

SELECT
    t1.Col2 AS t1Col2,
    t2.Col2 AS t2Col2,
    COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)) as NULL_IF_SAME
 FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID

NULL_IF_SAME column will give NULL for all rows where t1.col2 = t2.col2 (including NULL). Though this is not more readable than CASE WHEN expression, it is ANSI SQL.

Just for the sake of fun, if one wants to have boolean bit values of 0 and 1 (though it is not very readable, hence not recommended), one can use (which works for all datatypes):

1/ISNULL(LEN(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+2,1) as BOOL_BIT_SAME.

Now if you have one of the numeric data types and want bits, in the above LEN function converts to string first which may be problematic,so instead this should work:

1/(CAST(ISNULL(ABS(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+1,0)as bit)+1) as FAST_BOOL_BIT_SAME_NUMERIC

Above will work for Integers without CAST.

NOTE: also in SQLServer 2012, we have IIF function.

how do I join two lists using linq or lambda expressions

The way to do this using the Extention Methods, instead of the linq query syntax would be like this:

var results = workOrders.Join(plans,
  wo => wo.WorkOrderNumber,
  p => p.WorkOrderNumber,
  (order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn't static. Thus you need an instance of your form to call SetTextboxText.

Removing element from array in component state

You could make the code more readable with a one line helper function:

const removeElement = (arr, i) => [...arr.slice(0, i), ...arr.slice(i+1)];

then use it like so:

this.setState(state => ({ places: removeElement(state.places, index) }));

Unable to allocate array with shape and data type

change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8:

data['label'] = data['label'].astype(np.uint8)

How to increase number of threads in tomcat thread pool?

From Tomcat Documentation

maxConnections When this number has been reached, the server will accept, but not process, one further connection. once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. (The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.) For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO and NIO2 the default is 10000. For APR/native, the default is 8192. Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.

maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.

Bootstrap 3 Navbar Collapse

The big difference between Bootstrap 2 and Bootstrap 3 is that Bootstrap 3 is "mobile first".

That means the default styles are designed for mobile devices and in the case of Navbars, that means it's "collapsed" by default and "expands" when it reaches a certain minimum size.

Bootstrap 3's site actually has a "hint" as to what to do: http://getbootstrap.com/components/#navbar

Customize the collapsing point

Depending on the content in your navbar, you might need to change the point at which your navbar switches between collapsed and horizontal mode. Customize the @grid-float-breakpoint variable or add your own media query.

If you're going to re-compile your LESS, you'll find the noted LESS variable in the variables.less file. It's currently set to "expand" @media (min-width: 768px) which is a "small screen" (ie. a tablet) by Bootstrap 3 terms.

@grid-float-breakpoint: @screen-tablet;

If you want to keep the collapsed a little longer you can adjust it like such:

@grid-float-breakpoint: @screen-desktop; (992px break-point)

or expand sooner

@grid-float-breakpoint: @screen-phone (480px break-point)

If you want to have it expand later, and not deal with re-compiling the LESS, you'll have to overwrite the styles that get applied at the 768px media query and have them return to the previous value. Then re-add them at the appropriate time.

I'm not sure if there's a better way to do it. Recompiling the Bootstrap LESS to your needs is the best (easiest) way. Otherwise, you'll have to find all the CSS media queries that affect your Navbar, overwrite them to default styles @ the 768px width and then revert them back at a higher min-width.

Recompiling the LESS will do all that magic for you just by changing the variable. Which is pretty much the point of LESS/SASS pre-compilers. =)

(note, I did look them all up, it's about 100 lines of code, which is annoy enough for me to drop the idea and just re-compile Bootstrap for a given project and avoid messing something up by accident)

I hope that helps!

Cheers!

How to make a PHP SOAP call using the SoapClient class

If you create the object of SoapParam, This will resolve your problem. Create a class and map it with object type given by WebService, Initialize the values and send in the request. See the sample below.

struct Contact {

    function Contact ($pid, $pname)
    {
      id = $pid;
      name = $pname;
  }
}

$struct = new Contact(100,"John");

$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "Contact","http://soapinterop.org/xsd");

$ContactParam = new SoapParam($soapstruct, "Contact")

$response = $client->Function1($ContactParam);

How to center align the cells of a UICollectionView?

Swift 2.0 Works fine for me!

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        let edgeInsets = (screenWight - (CGFloat(elements.count) * 50) - (CGFloat(elements.count) * 10)) / 2
        return UIEdgeInsetsMake(0, edgeInsets, 0, 0);
    }

Where: screenWight: basically its my collection's width (full screen width) - I made constants: let screenWight:CGFloat = UIScreen.mainScreen().bounds.width because self.view.bounds shows every-time 600 - coz of SizeClasses elements - array of cells 50 - my manual cell width 10 - my distance between cells

What's the best way to test SQL Server connection programmatically?

Here is my version based on the @peterincumbria answer:

using var scope = _serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
return await dbContext.Database.CanConnectAsync(cToken);

I'm using Observable for polling health checking by interval and handling return value of the function. try-catch is not needed here because: enter image description here

Create controller for partial view in ASP.NET MVC

The most important thing is, the action created must return partial view, see below.

public ActionResult _YourPartialViewSection()
{
    return PartialView();
}

How do you access the value of an SQL count () query in a Java program

I have done it this way (example):

String query="SELECT count(t1.id) from t1, t2 where t1.id=t2.id and t2.email='"[email protected]"'";
int count=0;
try {
    ResultSet rs = DatabaseService.statementDataBase().executeQuery(query);
    while(rs.next())
        count=rs.getInt(1);
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    //...
}

How to declare a global variable in C++

Not sure if this is correct in any sense but this seems to work for me.

someHeader.h
inline int someVar;

I don't have linking/multiple definition issues and it "just works"... ;- )

It's quite handy for "quick" tests... Try to avoid global vars tho, because every says so... ;- )

Setting the height of a DIV dynamically

Simplest I could come up...

function resizeResizeableHeight() {
    $('.resizableHeight').each( function() {
        $(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css('padding-top') ) ) ) )
    });
}

Now all you have to do is add the resizableHeight class to everything you want to autosize (to it's parent).

SQL Server Creating a temp table for this query

IF OBJECT_ID('tempdb..#MyTempTable') IS NOT NULL DROP TABLE #MyTempTable

CREATE TABLE #MyTempTable (SiteName varchar(50), BillingMonth varchar(10), Consumption float)

INSERT INTO #MyTempTable (SiteName, BillingMonth, Consumption)
SELECT  tblMEP_Sites.Name AS SiteName, convert(varchar(10),BillingMonth ,101)
AS BillingMonth, SUM(Consumption) AS Consumption
FROM tblMEP_Projects.......

How can I insert data into a MySQL database?

This way worked for me when adding random data to MySql table using a python script.
First install the following packages using the below commands

pip install mysql-connector-python<br>
pip install random
import mysql.connector
import random

from datetime import date


start_dt = date.today().replace(day=1, month=1).toordinal()
end_dt = date.today().toordinal()

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="root",
    database="your_db_name"
)

mycursor = mydb.cursor()

sql_insertion = "INSERT INTO customer (name,email,address,dateJoined) VALUES (%s, %s,%s, %s)"
#insert 10 records(rows)
for x in range(1,11):
    #generate a random date
    random_day = date.fromordinal(random.randint(start_dt, end_dt))
    value = ("customer" + str(x),"customer_email" + str(x),"customer_address" + str(x),random_day)
    mycursor.execute(sql_insertion , value)

mydb.commit()

print("customer records inserted!")


Following is a sample output of the insertion

cid       |  name      |  email           |    address        |  dateJoined  |

1         | customer1  |  customer_email1 | customer_address1 |  2020-11-15  |
2         | customer2  |  customer_email2 | customer_address2 |  2020-10-11  |
3         | customer3  |  customer_email3 | customer_address3 |  2020-11-17  |
4         | customer4  |  customer_email4 | customer_address4 |  2020-09-20  |
5         | customer5  |  customer_email5 | customer_address5 |  2020-02-18  |
6         | customer6  |  customer_email6 | customer_address6 |  2020-01-11  |
7         | customer7  |  customer_email7 | customer_address7 |  2020-05-30  |
8         | customer8  |  customer_email8 | customer_address8 |  2020-04-22  |
9         | customer9  |  customer_email9 | customer_address9 |  2020-01-05  |
10        | customer10 |  customer_email10| customer_address10|  2020-11-12  |



extract column value based on another column pandas dataframe

df[df['B']==3]['A'], assuming df is your pandas.DataFrame.

How do I replicate a \t tab space in HTML?

I need a code that has the same function as the /t escape character

What function do you mean, creating a tabulator space?

No such thing in HTML, you'll have to use HTML elements for that. (A <table> may make sense for tabular data, or a description list <dl> for definitions.)

How to sort 2 dimensional array by column value?

try this

//WITH FIRST COLUMN
arr = arr.sort(function(a,b) {
    return a[0] - b[0];
});


//WITH SECOND COLUMN
arr = arr.sort(function(a,b) {
    return a[1] - b[1];
});

Note: Original answer used a greater than (>) instead of minus (-) which is what the comments are referring to as incorrect.

PHP date() with timezone?

For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.

I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.

Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:

$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');

DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).

memory error in python

Using python 64 bit solves lot of problems.

How to compare arrays in JavaScript?

Even though this has a lot of answers, one that I believe to be of help:

const newArray = [ ...new Set( [...arr1, ...arr2] ) ]

It is not stated in the question how the structure of the array is going to look like, so If you know for sure that you won't have nested arrays nor objects in you array (it happened to me, that's why I came to this answer) the above code will work.

What happens is that we use spread operator ( ... ) to concat both arrays, then we use Set to eliminate any duplicates. Once you have that you can compare their sizes, if all three arrays have the same size you are good to go.

This answer also ignores the order of elements, as I said, the exact situation happened to me, so maybe someone in the same situation might end up here (as I did).


Edit1.

Answering Dmitry Grinko's question: "Why did you use spread operator ( ... ) here - ...new Set ? It doesn't work"

Consider this code:

const arr1 = [ 'a', 'b' ]
const arr2 = [ 'a', 'b', 'c' ]
const newArray = [ new Set( [...arr1, ...arr2] ) ]
console.log(newArray)

You'll get

[ Set { 'a', 'b', 'c' } ]

In order to work with that value you'd need to use some Set properties (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). On the other hand, when you use this code:

const arr1 = [ 'a', 'b' ]
const arr2 = [ 'a', 'b', 'c' ]
const newArray = [ ...new Set( [...arr1, ...arr2] ) ]
console.log(newArray)

You'll get

[ 'a', 'b', 'c' ]

That's the difference, the former would give me a Set, it would work too as I could get the size of that Set, but the latter gives me the array I need, what's more direct to the resolution.

Declaring a custom android UI element using XML

Thanks a lot for the first answer.

As for me, I had just one problem with it. When inflating my view, i had a bug : java.lang.NoSuchMethodException : MyView(Context, Attributes)

I resolved it by creating a new constructor :

public MyView(Context context, AttributeSet attrs) {
     super(context, attrs);
     // some code
}

Hope this will help !

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

I've run into the same problem, I found the solution at http://developer.android.com/tools/devices/emulator.html#vm-windows

Just follow this simple steps:

  1. Start the Android SDK Manager, select Extras and then select Intel Hardware Accelerated Execution Manager.

  2. After the download completes, run [sdk]/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM.exe

  3. Follow the on-screen instructions to complete installation.

Duplicate and rename Xcode project & associated folders

I'm posting this since I have always been struggling when renaming a project in XCode.

Renaming the project is good and simple but this doesn't rename the source folder. Here is a step by step of what I have done that worked great in Xcode 4 and 5 thanks to the links below.

REF links:
Rename Project.
Rename Source Folder and other files.

1- Backup your project.

If you are using git, commit any changes, make a copy of the entire project folder and backup in time machine before making any changes (this step is not required but I highly recommended).

2- Open your project.

3- Slow double click or hit enter on the Project name (blue top icon) and rename it to whatever you like.

NOTE: After you rename the project and press ‘enter’ it will suggest to automatically change all project-name-related entries and will allow you to de-select some of them if you want. Select all of them and click ok.

4- Rename the Scheme

a) Click the menu right next to the stop button and select Manage Schemes.

b) Single-slow-click or hit enter on the old name scheme and rename it to whatever you like.

c) Click ok.

5 - Build and run to make sure it works.

NOTES: At this point all of the important project files should be renamed except the comments in the classes created when the project was created nor the source folder. Next we will rename the folder in the file system.

6- Close the project.

7- Rename the main and the source folder.

8- Right click the project bundle .xcodeproj file and select “Show Package Contents” from the context menu. Open the .pbxproj file with any text editor.

9- Search and replace any occurrence of the original folder name with the new folder name.

10- Save the file.

11- Open XCode project, test it.

12- Done.

EDIT 10/11/19:

There is a tool to rename projects in Xcode I haven't tried it enough to comment on it. https://github.com/appculture/xcode-project-renamer

How to display a Yes/No dialog box on Android?

Kotlin implementation.

You can create a simple function like this:

fun dialogYesOrNo(
        activity: Activity,
        title: String,
        message: String,
        listener: DialogInterface.OnClickListener
    ) {
        val builder = AlertDialog.Builder(activity)
        builder.setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id ->
            dialog.dismiss()
            listener.onClick(dialog, id)
        })
        builder.setNegativeButton("No", null)
        val alert = builder.create()
        alert.setTitle(title)
        alert.setMessage(message)
        alert.show()
    }

and call it like this:

dialogYesOrNo(
  this,
  "Question",
  "Would you like to eat?",
  DialogInterface.OnClickListener { dialog, id ->
    // do whatever you need to do when user presses "Yes"
  }
})

pros and cons between os.path.exists vs os.path.isdir

Just like it sounds like: if the path exists, but is a file and not a directory, isdir will return False. Meanwhile, exists will return True in both cases.

tell pip to install the dependencies of packages listed in a requirement file

simplifily, use:

pip install -r requirement.txt

it can install all listed in requirement file.

Concatenate columns in Apache Spark DataFrame

In Spark 2.3.0, you may do:

spark.sql( """ select '1' || column_a from table_a """)

What does the symbol \0 mean in a string-literal?

char str[]= "Hello\0";

That would be 7 bytes.

In memory it'd be:

48 65 6C 6C 6F 00 00
H  e  l  l  o  \0 \0

Edit:

  • What does the \0 symbol mean in a C string?
    It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message. I'll put an example at the end.

  • What is the length of str array? (Answered before the edit part)
    7

  • and with how much 0s it is ending?
    You array has two "spaces" with zero; str[5]=str[6]='\0'=0

Extra example:
Let's assume you have a function that prints the content of that text array. You could define it as:

char str[40];

Now, you could change the content of that array (I won't get into details on how to), so that it contains the message: "This is just a printing test" In memory, you should have something like:

54 68 69 73 20 69 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

So you print that char array. And then you want a new message. Let's say just "Hello"

48 65 6c 6c 6f 00 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

Notice the 00 on str[5]. That's how the print function will know how much it actually needs to send, despite the actual longitude of the vector and the whole content.

How to add values in a variable in Unix shell scripting?

I don't have a unix system under my hands, but try this:

count7=$((${count7} + ${count1}))

Or maybe you have a shell that doesn't support this expression. I think bash does support it, but sh doesn't.

EDIT: There is another syntax, try:

count7=`expr $count7 + $count1`

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:

services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
    {
        options.YourProperty = yourValue;
    })

How do I pass a string into subprocess.Popen (using the stdin argument)?

On Python 3.7+ do this:

my_data = "whatever you want\nshould match this f"
subprocess.run(["grep", "f"], text=True, input=my_data)

and you'll probably want to add capture_output=True to get the output of running the command as a string.

On older versions of Python, replace text=True with universal_newlines=True:

subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)

android: how to use getApplication and getApplicationContext from non activity / service class

The getApplication() method is located in the Activity class, that's why you can't access it from your helper class.

If you really need to access your application context from your helper, you should hold a reference to the activity's context and pass it on invocation to the helper.

Get The Current Domain Name With Javascript (Not the path, etc.)

If you are not interested in the host name (for example www.beta.example.com) but in the domain name (for example example.com), this works for valid host names:

function getDomainName(hostName)
{
    return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);
}

invalid use of non-static member function

The simplest fix is to make the comparator function be static:

static int comparator (const Bar & first, const Bar & second);
^^^^^^

When invoking it in Count, its name will be Foo::comparator.

The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo.

Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo.

Print range of numbers on same line

Same can be achieved by using stdout.

>>> from sys import stdout
>>> for i in range(1,11):
...     stdout.write(str(i)+' ')
...
1 2 3 4 5 6 7 8 9 10 

Alternatively, same can be done by using reduce() :

>>> xrange = range(1,11)
>>> print reduce(lambda x, y: str(x) + ' '+str(y), xrange)
1 2 3 4 5 6 7 8 9 10
>>>

How can I get the root domain URI in ASP.NET?

C# Example Below:

string scheme = "http://";
string rootUrl = default(string);
if (Request.ServerVariables["HTTPS"].ToString().ToLower() == "on")
{
  scheme = "https://";
}
rootUrl = scheme + Request.ServerVariables["SERVER_NAME"].ToString();

How does MySQL process ORDER BY and LIMIT in a query?

Just as @James says, it will order all records, then get the first 20 rows.

As it is so, you are guaranteed to get the 20 first published articles, the newer ones will not be shown.

In your situation, I recommend that you add desc to order by publish_date, if you want the newest articles, then the newest article will be first.

If you need to keep the result in ascending order, and still only want the 10 newest articles you can ask mysql to sort your result two times.

This query below will sort the result descending and limit the result to 10 (that is the query inside the parenthesis). It will still be sorted in descending order, and we are not satisfied with that, so we ask mysql to sort it one more time. Now we have the newest result on the last row.

select t.article 
from 
    (select article, publish_date 
     from table1
     order by publish_date desc limit 10) t 

order by t.publish_date asc;

If you need all columns, it is done this way:

select t.* 
from 
    (select * 
     from table1  
     order by publish_date desc limit 10) t 

order by t.publish_date asc;

I use this technique when I manually write queries to examine the database for various things. I have not used it in a production environment, but now when I bench marked it, the extra sorting does not impact the performance.

Convert JsonObject to String

There is an inbuilt method to convert a JSONObject to a String. Why don't you use that:

JSONObject json = new JSONObject();

json.toString();

Regex match entire words only

Get all "words" in a string

/([^\s]+)/g

Basically ^/s means break on spaces (or match groups of non-spaces)
Don't forget the g for Greedy

How do I check CPU and Memory Usage in Java?

If you use the runtime/totalMemory solution that has been posted in many answers here (I've done that a lot), be sure to force two garbage collections first if you want fairly accurate/consistent results.

For effiency Java usually allows garbage to fill up all of memory before forcing a GC, and even then it's not usually a complete GC, so your results for runtime.freeMemory() always be somewhere between the "real" amount of free memory and 0.

The first GC doesn't get everything, it gets most of it.

The upswing is that if you just do the freeMemory() call you will get a number that is absolutely useless and varies widely, but if do 2 gc's first it is a very reliable gauge. It also makes the routine MUCH slower (seconds, possibly).

Flutter Countdown Timer

You can use this plugin timer_builder

timer_builder widget that rebuilds itself on scheduled, periodic, or dynamically generated time events.

Examples

Periodic rebuild

import 'package:timer_builder/timer_builder.dart';

class ClockWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return TimerBuilder.periodic(Duration(seconds: 1),
      builder: (context) {
        return Text("${DateTime.now()}");
      }
    );
  }
  
}

Rebuild on a schedule

import 'package:timer_builder/timer_builder.dart';

class StatusIndicator extends StatelessWidget {

  final DateTime startTime;
  final DateTime endTime;
  
  StatusIndicator(this.startTime, this.endTime);
  
  @override
  Widget build(BuildContext context) {
    return TimerBuilder.scheduled([startTime, endTime],
      builder: (context) {
        final now = DateTime.now();
        final started = now.compareTo(startTime) >= 0;
        final ended = now.compareTo(endTime) >= 0;
        return Text(started ? ended ? "Ended": "Started": "Not Started");
      }
    );
  }
  
}

enter image description here

refresh div with jquery

I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this

_x000D_
_x000D_
$("#panel").toggle().toggle();
_x000D_
_x000D_
_x000D_

it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.

How to parse a string in JavaScript?

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

How to run jenkins as a different user

The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.

However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub. What if there are multiple jenkins servers that need to access the same gitolite server?

(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)

So in this case you do need to run the Jenkins daemon as a different user.

There are two steps:

Step 1

The main thing is to update the JENKINS_USER environment variable. Here's a patch showing how to change the user to ptran.

BEGIN PATCH
--- etc/default/jenkins.old     2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
 PIDFILE=/var/run/jenkins/jenkins.pid

 # user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran

 # location of the jenkins war file
 JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old      2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins  2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@

 #DAEMON=$JENKINS_SH
 DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG -   -pidfile=$PIDFILE" 
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE" 

 SU=/bin/su
END PATCH

Step 2

Update ownership of jenkins directories:

chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins

Step 3

Restart jenkins

sudo service jenkins restart

XML to CSV Using XSLT

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'&quot;'" />
  <xsl:param name="break" select="'&#xA;'" />

  <xsl:template match="/">
    <xsl:apply-templates select="projects/project" />
  </xsl:template>

  <xsl:template match="project">
    <xsl:apply-templates />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$break" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="*">
    <!-- remove normalize-space() if you want keep white-space at it is --> 
    <xsl:value-of select="concat($quote, normalize-space(), $quote)" />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$delim" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="text()" />
</xsl:stylesheet>

How can I get selector from jQuery object

Taking in account some answers read here I'd like to propose this:

function getSelectorFromElement($el) {
  if (!$el || !$el.length) {
    return ;
  }

  function _getChildSelector(index) {
    if (typeof index === 'undefined') {
      return '';
    }

    index = index + 1;
    return ':nth-child(' + index + ')';
  }

  function _getIdAndClassNames($el) {
    var selector = '';

    // attach id if exists
    var elId = $el.attr('id');
    if(elId){
      selector += '#' + elId;
    }

    // attach class names if exists
    var classNames = $el.attr('class');
    if(classNames){
      selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
    }

    return selector;
  }

  // get all parents siblings index and element's tag name,
  // except html and body elements
  var selector = $el.parents(':not(html,body)')
    .map(function() {
      var parentIndex = $(this).index();

      return this.tagName + _getChildSelector(parentIndex);
    })
    .get()
    .reverse()
    .join(' ');

  if (selector) {
    // get node name from the element itself
    selector += ' ' + $el[0].nodeName +
      // get child selector from element ifself
      _getChildSelector($el.index());
  }

  selector += _getIdAndClassNames($el);

  return selector;
}

Maybe useful to create a jQuery plugin?

How to do 3 table JOIN in UPDATE query?

Alternative way of achieving same result is not to use JOIN keyword at all.

UPDATE TABLE_A, TABLE_B
SET TABLE_A.column_c = TABLE_B.column_c + 1
WHERE TABLE_A.join_col = TABLE_B.join_col

Bypass popup blocker on window.open when JQuery event.preventDefault() is set

Popup blockers will typically only allow window.open if used during the processing of a user event (like a click). In your case, you're calling window.open later, not during the event, because $.getJSON is asynchronous.

You have two options:

  1. Do something else, rather than window.open.

  2. Make the ajax call synchronous, which is something you should normally avoid like the plague as it locks up the UI of the browser. $.getJSON is equivalent to:

    $.ajax({
      url: url,
      dataType: 'json',
      data: data,
      success: callback
    });
    

    ...and so you can make your $.getJSON call synchronous by mapping your params to the above and adding async: false:

    $.ajax({
        url:      "redirect/" + pageId,
        async:    false,
        dataType: "json",
        data:     {},
        success:  function(status) {
            if (status == null) {
                alert("Error in verifying the status.");
            } else if(!status) {
                $("#agreement").dialog("open");
            } else {
                window.open(redirectionURL);
            }
        }
    });
    

    Again, I don't advocate synchronous ajax calls if you can find any other way to achieve your goal. But if you can't, there you go.

    Here's an example of code that fails the test because of the asynchronous call:

    Live example | Live source (The live links no longer work because of changes to JSBin)

    jQuery(function($) {
      // This version doesn't work, because the window.open is
      // not during the event processing
      $("#theButton").click(function(e) {
        e.preventDefault();
        $.getJSON("http://jsbin.com/uriyip", function() {
          window.open("http://jsbin.com/ubiqev");
        });
      });
    });
    

    And here's an example that does work, using a synchronous call:

    Live example | Live source (The live links no longer work because of changes to JSBin)

    jQuery(function($) {
      // This version does work, because the window.open is
      // during the event processing. But it uses a synchronous
      // ajax call, locking up the browser UI while the call is
      // in progress.
      $("#theButton").click(function(e) {
        e.preventDefault();
        $.ajax({
          url:      "http://jsbin.com/uriyip",
          async:    false,
          dataType: "json",
          success:  function() {
            window.open("http://jsbin.com/ubiqev");
          }
        });
      });
    });
    

Another git process seems to be running in this repository

It may be happening your branch is corrupted create new branch git branch #check branch. I have created a new branch and working .

branch -b "main"
git checkout -b "main"  #main is new branch
git add .
git commit -m "all files"
git remote add origin #**YOUR REPO**  https://github.com/tarun-techmarbles/wp-dump-sql-git-push.git
git push origin main  #push with new branch 

How exactly to use Notification.Builder

in addition to the selected answer here is some sample code for the NotificationCompat.Builder class from Source Tricks :

// Add app running notification  

    private void addNotification() {



    NotificationCompat.Builder builder =  
            new NotificationCompat.Builder(this)  
            .setSmallIcon(R.drawable.ic_launcher)  
            .setContentTitle("Notifications Example")  
            .setContentText("This is a test notification");  

    Intent notificationIntent = new Intent(this, MainActivity.class);  
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
            PendingIntent.FLAG_UPDATE_CURRENT);  
    builder.setContentIntent(contentIntent);  

    // Add as notification  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.notify(FM_NOTIFICATION_ID, builder.build());  
}  

// Remove notification  
private void removeNotification() {  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.cancel(FM_NOTIFICATION_ID);  
}  

How to generate a random string of a fixed length in Go?

Here is my way ) Use math rand or crypto rand as you wish.

func randStr(len int) string {
    buff := make([]byte, len)
    rand.Read(buff)
    str := base64.StdEncoding.EncodeToString(buff)
    // Base 64 can be longer than len
    return str[:len]
}

Getting error: ISO C++ forbids declaration of with no type

Your declaration is int ttTreeInsert(int value);

However, your definition/implementation is

ttTree::ttTreeInsert(int value)
{
}

Notice that the return type int is missing in the implementation. Instead it should be

int ttTree::ttTreeInsert(int value)
{
    return 1; // or some valid int
}

Check if cookies are enabled

Cookies are Client-side and cannot be tested properly using PHP. That's the baseline and every solution is a wrap-around for this problem.

Meaning if you are looking a solution for your cookie problem, you are on the wrong way. Don'y use PHP, use a client language like Javascript.

Can you use cookies using PHP? Yes, but you have to reload to make the settings to PHP 'visible'.

For instance: Is a test possible to see if the browser can set Cookies with plain PHP'. The only correct answer is 'NO'.

Can you read an already set Cookie: 'YES' use the predefined $_COOKIE (A copy of the settings before you started PHP-App).

How to create a library project in Android Studio and an application project that uses the library project

In my case, using MAC OS X 10.11 and Android 2.0, and by doing exactly what Aqib Mumtaz has explained.

But, each time, I had this message : "A problem occurred configuring project ':app'. > Cannot evaluate module xxx : Configuration with name 'default' not found."

I found that the reason of this message is that Android 2.0 doesn't allow to create a library directly. So, I have decided first to create an app projet and then to modify the build.gradle in order to transform it as a library.

This solution doesn't work, because a Library project is very different than an app project.

So, I have resolved my problem like this :

  • First create an standard app (if needed) ;
  • Then choose 'File/Create Module'
  • Go to the finder and move the folder of the module freshly created in your framework directory

Then continue with the solution proposed by Aqib Mumtaz.

As a result, your library source will be shared without needing to duplicate source files each time (it was an heresy for me!)

Hoping that this help you.

sort csv by column

import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)

or use lambda

sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)

How do I build an import library (.lib) AND a DLL in Visual C++?

By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.

Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.

You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.

.htaccess: where is located when not in www base dir

The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.

Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.

How do I get the value of a textbox using jQuery?

There's a .val() method:

If you've got an input with an id of txtEmail you can use the following code to access the value of the text box:

$("#txtEmail").val()

You can also use the val(string) method to set that value:

$("#txtEmail").val("something")

relative path in require_once doesn't work

Use

__DIR__

to get the current path of the script and this should fix your problem.

So:

require_once(__DIR__.'/../class/user.php');

This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.

Edit: slash problem fixed

Run php function on button click

You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:

    <form action="action_page.php">
       First name:<br>
       <input type="text" name="firstname" value="Mickey">
       <br>
       Last name:<br>
       <input type="text" name="lastname" value="Mouse">
       <br><br>
       <input type="submit" value="Submit">
     </form> 

(Original Code from: http://www.w3schools.com/html/html_forms.asp)

So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)

MVC Razor view nested foreach's model

You could add a Category partial and a Product partial, each would take a smaller part of the main model as it's own model, i.e. Category's model type might be an IEnumerable, you would pass in Model.Theme to it. The Product's partial might be an IEnumerable that you pass Model.Products into (from within the Category partial).

I'm not sure if that would be the right way forward, but would be interested in knowing.

EDIT

Since posting this answer, I've used EditorTemplates and find this the easiest way to handle repeating input groups or items. It handles all your validation message problems and form submission/model binding woes automatically.

How to present a modal atop the current view in Swift

The only problem I can see in your code is that you are using CurrentContext instead of OverCurrentContext.

So, replace this:

self.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
self.navigationController.modalPresentationStyle = UIModalPresentationStyle.CurrentContext

for this:

self.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
self.navigationController.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext

Kafka consumer list

Kafka stores all the information in zookeeper. You can see all the topic related information under brokers->topics. If you wish to get all the topics programmatically you can do that using Zookeeper API.

It is explained in detail in below links Tutorialspoint, Zookeeper Programmer guide

Strip HTML from Text JavaScript

A safer way to strip the html with jQuery is to first use jQuery.parseHTML to create a DOM, ignoring any scripts, before letting jQuery build an element and then retrieving only the text.

function stripHtml(unsafe) {
    return $($.parseHTML(unsafe)).text();
}

Can safely strip html from:

<img src="unknown.gif" onerror="console.log('running injections');">

And other exploits.

nJoy!

How to compare DateTime in C#?

using System;
//
public enum TimeUnit : byte {
    Unknown = 0x00, // 
    Nanosecond = 0x01, // ns, not available in DateTime
    Millisecond = 0x02, // ms
    Second = 0x04, // sec
    Minute = 0x08, // min
    Hour = 0x10, // h
    Day = 0x20, // d
    Month = 0x40, // M
    Year = 0x80, // Y
    AllDate = TimeUnit.Year | TimeUnit.Month | TimeUnit.Day,
    AllTime = TimeUnit.Hour | TimeUnit.Minute | TimeUnit.Second,
    UpToNanosecond = TimeUnit.Nanosecond | TimeUnit.Millisecond | TimeUnit.Second | TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToMillisecond = TimeUnit.Millisecond | TimeUnit.Second | TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToSecond = TimeUnit.Second | TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToMinute = TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToHour = TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToDay = TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
    UpToMonth = TimeUnit.Month | TimeUnit.Year,
};
//
public static partial class DateTimeEx {
    //
    private static void _Compare( ref int result, int flags, TimeUnit tu, int a, int b ) {
        var which = (int) tu;
        if ( 0 != ( flags & which ) ) {
            if ( a != b ) result |= which;
        }
    }
    ///<summary>Compare Dates. The returned TimeUnit will have one flag set for every different field. It will NOT indicate which date is bigger or smaller.</summary>
    public static TimeUnit Compare( this DateTime a, DateTime b, TimeUnit unit ) {
        int result = 0;
        var flags = (int) unit;
        //ompare( ref result, flags, TimeUnit.Nanosecond, a.Nano, b.Nanosecond );
        _Compare( ref result, flags, TimeUnit.Millisecond, a.Millisecond, b.Millisecond );
        _Compare( ref result, flags, TimeUnit.Second, a.Second, b.Second );
        _Compare( ref result, flags, TimeUnit.Minute, a.Minute, b.Minute );
        _Compare( ref result, flags, TimeUnit.Hour, a.Hour, b.Hour );
        _Compare( ref result, flags, TimeUnit.Day, a.Day, b.Day );
        _Compare( ref result, flags, TimeUnit.Month, a.Month, b.Month );
        _Compare( ref result, flags, TimeUnit.Year, a.Year, b.Year );
        return (TimeUnit) result;
    }
}
public static class Tests {
    //
    private static void TestCompare() {
        var test = DateTime.UtcNow;
        var ts = test.ToUnixTimestamp( true );
        var test2 = DateTimeEx.ToDateTime( ts, true );
        var ok = 0 == DateTimeEx.Compare( test, test2, TimeUnit.UpToSecond );
        Log.Assert( ok );
        ts = test.ToUnixTimestamp( false );
        test2 = DateTimeEx.ToDateTime( ts, false );
        ok = 0 == DateTimeEx.Compare( test, test2, TimeUnit.UpToSecond );
        Log.Assert( ok );
    }
}

"Too many characters in character literal error"

Here's an example:

char myChar = '|';
string myString = "||";

Chars are delimited by single quotes, and strings by double quotes.

The good news is C# switch statements work with strings!

switch (mytoken)
{
    case "==":
        //Something here.
        break;
    default:
        //Handle when no token is found.
        break;
}

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

Python ValueError: too many values to unpack

Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity into (m, k).

My crystal ball says m.type and m.purity are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)

To fix this, you can iterate explicitly over the items of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.

(In 2.x, itervalues, iterkeys, and iteritems are typically a better idea; the non-iter versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter versions which just set up an iterator.)

Prevent redirect after form is submitted

I found this page 10 years (!) after the original post, and needed the answer as vanilla js instead of AJAX. I figured it out with the help of @gargAman's answer.

Use an appropriate selector to assign your button to a variable, e.g.

document.getElementById('myButton')

then

myButton.addEventListener('click', function(e) {
    e.preventDefault();
    // do cool stuff
});

I should note that my html looks like this (specifically, I am not using type="Submit" in my button and action="" in my form:

  <form method="POST" action="" id="myForm">
    <!-- form fields -->
    <button id="myButton" class="btn-submit">Submit</button>
  </form>

switch() statement usage

In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:

http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/

Personally, when I have 3 or more cases, I usually just go with case/switch.

Is there a real solution to debug cordova apps

If you're using Cordova 3.3 or higher and your device is running Android 4.4 or higher you can use 'Remote Debugging on Android with Chrome'. Full instructions are here:

https://developer.chrome.com/devtools/docs/remote-debugging

In summary:

  • Plug the device into your desktop computer using a USB cable
  • Enable USB debugging on your device (on my device this is under Settings > More > Developer options > USB debugging)

Or, if you're using Cordova 3.3+ and don't have a physical device with 4.4, you can use an emulator that uses Android 4.4+ to run the application through the emulator, on your desktop computer.

  • Run your Cordova application on the device or emulator
  • In Chrome on your desktop computer, enter chrome://inspect/#devices in the address bar
  • Your device/emulator will be displayed along with any other recognised devices that are connected to your computer, and under your device there will be details of the Cordova 'WebView' (basically your Cordova app), which is running on the device/emulator (the way Cordova works is that it basically creates a 'browser' window on your device/emulator, within which there is a 'WebView' which is your running HTML/JavaScript app)
  • Click the 'inspect' link under the 'WebView' section where you see your device/emulator listed. This brings up the Chrome developer tools that now allow you to debug your application.
  • Select the 'sources' tab of the Chrome developer tools to view JavaScript that your Cordova app on the device/emulator is currently running. You can add breakpoints in the JavaScript that allow you to debug your code.
  • Also, you can use the 'console' tab to view any errors (which will be shown in red), or at the bottom of the console you'll see a '>' prompt. Here you can type in any variables or objects (e.g. DOM objects) that you want to inspect the current value of, and the value will be displayed.

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

You should define the __unicode__ method on your model, and the template will call it automatically when you reference the instance.

In a simple to understand explanation, what is Runnable in Java?

A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.

The Runnable Interface requires of the class to implement the method run() like so:

public class MyRunnableTask implements Runnable {
     public void run() {
         // do stuff here
     }
}

And then use it like this:

Thread t = new Thread(new MyRunnableTask());
t.start();

If you did not have the Runnable interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run() method in your class, so you could get errors. That is why you need to implement the interface.

Advanced: Anonymous Type

Note that you do not need to define a class as usual, you can do all of that inline:

Thread t = new Thread(new Runnable() {
    public void run() {
        // stuff here
    }
});
t.start();

This is similar to the above, only you don't create another named class.

Tesseract OCR simple example

Ok. I found the solution here tessnet2 fails to load the Ans given by Adam

Apparently i was using wrong version of tessdata. I was following the the source page instruction intuitively and that caused the problem.

it says

Quick Tessnet2 usage

  1. Download binary here, add a reference of the assembly Tessnet2.dll to your .NET project.

  2. Download language data definition file here and put it in tessdata directory. Tessdata directory and your exe must be in the same directory.

After you download the binary, when you follow the link to download the language file, there are many language files. but none of them are right version. you need to select all version and go to next page for correct version (tesseract-2.00.eng)! They should either update download binary link to version 3 or put the the version 2 language file on the first page. Or at least bold mention the fact that this version issue is a big deal!

Anyway I found it. Thanks everyone.

How to restore/reset npm configuration to default values?

For what it's worth, you can reset to default the value of a config entry with npm config delete <key> (or npm config rm <key>, but the usage of npm config rm is not mentioned in npm help config).

Example:

# set registry value
npm config set registry "https://skimdb.npmjs.com/registry"
# revert change back to default
npm config delete registry

How do I view the SQL generated by the Entity Framework?

SQL Management Studio => Tools => SQL Server profiler

File => New Trace...

Use the Template => Blank

Event selection => T-SQL

Lefthandside check for: SP.StmtComplete

Column filters can be used to select a specific ApplicationName or DatabaseName

Start that profile running then trigger the query.

Click here for Source information

MySQLi count(*) always returns 1

Always try to do an associative fetch, that way you can easy get what you want in multiple case result

Here's an example

$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";

Installing OpenCV on Windows 7 for Python 2.7

I have posted a very simple method to install OpenCV 2.4 for Python in Windows here : Install OpenCV in Windows for Python

It is just as simple as copy and paste. Hope it will be useful for future viewers.

  1. Download Python, Numpy, OpenCV from their official sites.

  2. Extract OpenCV (will be extracted to a folder opencv)

  3. Copy ..\opencv\build\python\x86\2.7\cv2.pyd

  4. Paste it in C:\Python27\Lib\site-packages

  5. Open Python IDLE or terminal, and type

    >>> import cv2
    

If no errors shown, it is OK.

UPDATE (Thanks to dana for this info):

If you are using the VideoCapture feature, you must copy opencv_ffmpeg.dll into your path as well. See: https://stackoverflow.com/a/11703998/1134940

Load local images in React.js

You have diferent ways to achieve this, here is an example:

import myimage from './...' // wherever is it.

in your img tag just put this into src:

<img src={myimage}...>

You can also check official docs here: https://facebook.github.io/react-native/docs/image.html

Switch android x86 screen resolution

In VirtualBox you should add custom resolution via the command:

VBoxManage setextradata "VM name" "CustomVideoMode1" "800x480x16"

instead of editing a .vbox file.

This solution works fine for me!

Change button text from Xcode?

UIButton *myButton;

[myButton setTitle:@"My Title" forState:UIControlStateNormal];
[myButton setTitle:@"My Selected Title" forState:UIControlStateSelected];

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

Access host database from a docker container

From the 18.03 docs:

I want to connect from a container to a service on the host

The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name host.docker.internal, which resolves to the internal IP address used by the host.

The gateway is also reachable as gateway.docker.internal.

EXAMPLE: Here's what I use for my MySQL connection string inside my container to access the MySQL instance on my host:

mysql://host.docker.internal:3306/my_awesome_database

How to run a Python script in the background even after I logout SSH?

You might consider turning your python script into a proper python daemon, as described here.

python-daemon is a good tool that can be used to run python scripts as a background daemon process rather than a forever running script. You will need to modify existing code a bit but its plain and simple.

If you are facing problems with python-daemon, there is another utility supervisor that will do the same for you, but in this case you wont have to write any code (or modify existing) as this is a out of the box solution for daemonizing processes.

JQuery Datatables : Cannot read property 'aDataSort' of undefined

I faced the same problem, the following changes solved my problem.

$(document).ready(function() {
     $('.datatable').dataTable( {
            bSort: false,
            aoColumns: [ { sWidth: "45%" }, { sWidth: "45%" }, { sWidth: "10%", bSearchable: false, bSortable: false } ],
        "scrollY":        "200px",
        "scrollCollapse": true,
        "info":           true,
        "paging":         true
    } );
} );

the aoColumns array describes the width of each column and its sortable properties.

Another thing to mention this error will also appear when you order by a column number that does not exist.

Print <div id="printarea"></div> only?

All the answers so far are pretty flawed - they either involve adding class="noprint" to everything or will mess up display within #printable.

I think the best solution would be to create a wrapper around the non-printable stuff:

<head>
    <style type="text/css">

    #printable { display: none; }

    @media print
    {
        #non-printable { display: none; }
        #printable { display: block; }
    }
    </style>
</head>
<body>
    <div id="non-printable">
        Your normal page contents
    </div>

    <div id="printable">
        Printer version
    </div>
</body>

Of course this is not perfect as it involves moving things around in your HTML a bit...

Check if a string contains a string in C++

From so many answers in this website I didn't find out a clear answer so in 5-10 minutes I figured it out the answer myself. But this can be done in two cases:

  1. Either you KNOW the position of the sub-string you search for in the string
  2. Either you don't know the position and search for it, char by char...

So, let's assume we search for the substring "cd" in the string "abcde", and we use the simplest substr built-in function in C++

for 1:

#include <iostream>
#include <string>

    using namespace std;
int i;

int main()
{
    string a = "abcde";
    string b = a.substr(2,2);    // 2 will be c. Why? because we start counting from 0 in a string, not from 1.

    cout << "substring of a is: " << b << endl;
    return 0;
}

for 2:

#include <iostream>
#include <string>

using namespace std;
int i;

int main()
{
    string a = "abcde";

    for (i=0;i<a.length(); i++)
    {
        if (a.substr(i,2) == "cd")
        {
        cout << "substring of a is: " << a.substr(i,2) << endl;    // i will iterate from 0 to 5 and will display the substring only when the condition is fullfilled 
        }
    }
    return 0;
}

How do I use a custom deleter with a std::unique_ptr member?

Unless you need to be able to change the deleter at runtime, I would strongly recommend using a custom deleter type. For example, if use a function pointer for your deleter, sizeof(unique_ptr<T, fptr>) == 2 * sizeof(T*). In other words, half of the bytes of the unique_ptr object are wasted.

Writing a custom deleter to wrap every function is a bother, though. Thankfully, we can write a type templated on the function:

Since C++17:

template <auto fn>
using deleter_from_fn = std::integral_constant<decltype(fn), fn>;

template <typename T, auto fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<fn>>;

// usage:
my_unique_ptr<Bar, destroy> p{create()};

Prior to C++17:

template <typename D, D fn>
using deleter_from_fn = std::integral_constant<D, fn>;

template <typename T, typename D, D fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<D, fn>>;

// usage:
my_unique_ptr<Bar, decltype(destroy), destroy> p{create()};

bootstrap responsive table content wrapping

The UberNeo response is Ok and i like it because you do not have to modify anything else except the TD. The only point is that you also have to add "white-space:normal" to the style in order to maintain the responsive characteristics of the table, if not, at certain resolutions the wrap is not made and the scroll of the table does not appear.

style="word-wrap: break-word;min-width: 160px;max-width: 160px;white-space:normal;"

jQuery Scroll to Div

It is often required to move both body and html objects together.

$('html,body').animate({
   scrollTop: $("#divToBeScrolledTo").offset().top
});

ShiftyThomas is right:

$("#divToBeScrolledTo").offset().top + 10 // +10 (pixels) reduces the margin.

So to increase the margin use:

$("#divToBeScrolledTo").offset().top - 10 // -10 (pixels) would increase the margin between the top of your window and your element.

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

My manifest does not reference any themes... it should not have to AFAIK

Sure it does. Nothing is going to magically apply Theme.Styled to an activity. You need to declare your activities -- or your whole application -- is using Theme.Styled, e.g., :

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.Styled">

Passing ArrayList from servlet to JSP

the possible errors would be...
1.you set the array list from the servelt in the session, not the in the request.
2.the array you set is null.
3.you redirect the page instead of forward it.

also you should not initialize the list and the category in jsp. try this.

for(Category cx: ((ArrayList<Category>)request.getAttribute("servletName"))) {

out.println( cx.getId());

out.println(cx.getName());

out.println(cx.getMainCategoryId() );
}

Swift - Remove " character from string

Replacing for Removing is not quite logical. String.filter allows to iterate a string char by char and keep only true assertion.

Swift 4 & 5

var aString = "Optional(\"5\")"

aString = aString.filter { $0 != "\"" }

> Optional(5)

Or to extend

var aString = "Optional(\"5\")"

let filteredChars = "\"\n\t"

aString = aString.filter { filteredChars.range(of: String($0)) == nil }

> Optional(5)

Efficient way to remove ALL whitespace from String?

If you need superb performance, you should avoid LINQ and regular expressions in this case. I did some performance benchmarking, and it seems that if you want to strip white space from beginning and end of the string, string.Trim() is your ultimate function.

If you need to strip all white spaces from a string, the following method works fastest of all that has been posted here:

    public static string RemoveWhitespace(this string input)
    {
        int j = 0, inputlen = input.Length;
        char[] newarr = new char[inputlen];

        for (int i = 0; i < inputlen; ++i)
        {
            char tmp = input[i];

            if (!char.IsWhiteSpace(tmp))
            {
                newarr[j] = tmp;
                ++j;
            }
        }
        return new String(newarr, 0, j);
    }

How do I convert an array object to a string in PowerShell?

From a pipe

# This Is a cat
'This', 'Is', 'a', 'cat' | & {"$input"}

# This-Is-a-cat
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"}

Write-Host

# This Is a cat
Write-Host 'This', 'Is', 'a', 'cat'

# This-Is-a-cat
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat'

Example

When do items in HTML5 local storage expire?

@sebarmeli's approach is the best in my opinion, but if you only want data to persist for the life of a session then sessionStorage is probably a better option:

This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

MDN: sessionStorage

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

How to check if std::map contains a key without doing insert?

Use my_map.count( key ); it can only return 0 or 1, which is essentially the Boolean result you want.

Alternately my_map.find( key ) != my_map.end() works too.

Using Java generics for JPA findAll() query with WHERE clause

I found this page very useful

https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

public abstract class GenericDAOWithJPA<T, ID extends Serializable> {

    private Class<T> persistentClass;

    //This you might want to get injected by the container
    protected EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public GenericDAOWithJPA() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

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.

Height equal to dynamic width (CSS fluid layout)

width: 80vmin; height: 80vmin;

CSS does 80% of the smallest view, height or width

http://caniuse.com/#feat=viewport-units

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

resolved this for me as well; however, I noticed that the servlet restart times were much worse, so while it was better in production, it was kind of a drag in development.

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

Maybe something like this ?

Create a batch to connect to telnet and run a script to issue commands ? source

Batch File (named Script.bat ):

     :: Open a Telnet window
   start telnet.exe 192.168.1.1
   :: Run the script 
    cscript SendKeys.vbs 

Command File (named SendKeys.vbs ):

set OBJECT=WScript.CreateObject("WScript.Shell")
WScript.sleep 50 
OBJECT.SendKeys "mylogin{ENTER}" 
WScript.sleep 50 
OBJECT.SendKeys "mypassword{ENTER}"
WScript.sleep 50 
OBJECT.SendKeys " cd /var/tmp{ENTER}" 
WScript.sleep 50 
OBJECT.SendKeys " rm log_web_activity{ENTER}" 
WScript.sleep 50 
OBJECT.SendKeys " ln -s /dev/null log_web_activity{ENTER}" 
WScript.sleep 50 
OBJECT.SendKeys "exit{ENTER}" 
WScript.sleep 50 
OBJECT.SendKeys " "

Best/Most Comprehensive API for Stocks/Financial Data

Last I looked -- a couple of years ago -- there wasn't an easy option and the "solution" (which I did not agree with) was screen-scraping a number of websites. It may be easier now but I would still be surprised to see something, well, useful.

The problem here is that the data is immensely valuable (and very expensive), so while defining a method of retrieving it would be easy, getting the trading venues to part with their data would be next to impossible. Some of the MTFs (currently) provide their data for free but I'm not sure how you would get it without paying someone else, like Reuters, for it.

adding 30 minutes to datetime php/mysql

Dominc has the right idea, but put the calculation on the other side of the expression.

SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)

This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.

How to make MySQL table primary key auto increment with some prefix

Create a table with a normal numeric auto_increment ID, but either define it with ZEROFILL, or use LPAD to add zeroes when selecting. Then CONCAT the values to get your intended behavior. Example #1:

create table so (
 id int(3) unsigned zerofill not null auto_increment primary key,
 name varchar(30) not null
);

insert into so set name = 'John';
insert into so set name = 'Mark';

select concat('LHPL', id) as id, name from so;
+---------+------+
| id      | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+

Example #2:

create table so (
 id int unsigned not null auto_increment primary key,
 name varchar(30) not null
);

insert into so set name = 'John';
insert into so set name = 'Mark';

select concat('LHPL', LPAD(id, 3, 0)) as id, name from so;
+---------+------+
| id      | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+

reCAPTCHA ERROR: Invalid domain for site key

I ran into this issue also and my solution was to verify I was integrating the appropriate client code for the version I had selected.

In my case, I had selected reCAPTCHA v3 but was taking client integration code for v2.

V3 looks like this:

<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
<script>
  grecaptcha.ready(function() {
      grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token) {
         ...
      });
  });
</script>

V2 code looks like this:

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha" data-sitekey="your_site_key"></div>
      <br/>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

As for which version you have, this will be what you decided at the start of your reCAPTCHA account setup. enter image description here

Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header('Location: /');
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

Changing cursor to waiting in javascript/jquery

$('#some_id').click(function() {
  $("body").css("cursor", "progress");
  $.ajax({
    url: "test.html",
    context: document.body,
    success: function() {
      $("body").css("cursor", "default");
    }
  });
});

This will create a loading cursor till your ajax call succeeds.

in_array multiple values

IMHO Mark Elliot's solution's best one for this problem. If you need to make more complex comparison operations between array elements AND you're on PHP 5.3, you might also think about something like the following:

<?php

// First Array To Compare
$a1 = array('foo','bar','c');

// Target Array
$b1 = array('foo','bar');


// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
        if (!in_array($x,$b1)) {
                $b=false;
        }
};


// Actual Test on array (can be repeated with others, but guard 
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);

This relies on a closure; comparison function can become much more powerful. Good luck!

Import Android volley to Android Studio

step 1:- Download volley.jar file.

step 2:- Go to your project and set the display menu from Android to Project then go to

app -> libs-> paste your volley.jar file here

step 3:- Right click on the volley.jar file and click on "add as library". and its all done.

Hibernate, @SequenceGenerator and allocationSize

I would check the DDL for the sequence in the schema. JPA Implementation is responsible only creation of the sequence with the correct allocation size. Therefore, if the allocation size is 50 then your sequence must have the increment of 50 in its DDL.

This case may typically occur with the creation of a sequence with allocation size 1 then later configured to allocation size 50 (or default) but the sequence DDL is not updated.

How to import existing Android project into Eclipse?

You can also use Make new > General > Project, then import the project to that project directory

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

I had this error come up today due to a defect in code that was posting back a tremendous amount of times causing IIS to be flooded with requests. This essentially locked up IIS and so when I tried to debug, it 'timed out' trying to start the debugger. I simply restarted IIS, which took a few minutes, and it solved the issue.

I sure do wish this error was less generic, seems like there are several different ways to produce it.

Bootstrap Columns Not Working

While this does not address the OP's question, I had trouble with my bootstrap rows / columns while trying to use them in conjunction with Kendo ListView (even with the bootstrap-kendo css).

Adding the following css fixed the problem for me:

#myListView.k-widget, #catalog-items.k-widget * {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

Access Control Origin Header error using Axios in React Web throwing error in Chrome

I had the same error. I solved it by installing CORS in my backend using npm i cors. You'll then need to add this to your code:

const cors = require('cors');
app.use(cors());

This fixed it for me; now I can post my forms using AJAX and without needing to add any customized headers.

java.io.IOException: Broken pipe

I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080 to forward the appropiate requests to tomcat.

There is a default value for the nginx variable proxy_read_timeout of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.

NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)

Maven Out of Memory Build Failure

Answering late to mention yet another option rather than the common MAVEN_OPTS environment variable to pass to the Maven build the required JVM options.

Since Maven 3.3.1, you could have an .mvn folder as part of the concerned project and a jvm.config file as perfect place for such an option.

two new optional configuration files .mvn/jvm.config and .mvn/maven.config, located at the base directory of project source tree. If present, these files will provide default jvm and maven options. Because these files are part of the project source tree, they will be present in all project checkouts and will be automatically used every time the project is build.

As part of the official release notes

In Maven it is not simple to define JVM configuration on a per project base. The existing mechanism based on an environment variable MAVEN_OPTS and the usage of ${user.home}/.mavenrc is an other option with the drawback of not being part of the project.

Starting with this release you can define JVM configuration via ${maven.projectBasedir}/.mvn/jvm.config file which means you can define the options for your build on a per project base. This file will become part of your project and will be checked in along with your project. So no need anymore for MAVEN_OPTS, .mavenrc files. So for example if you put the following JVM options into the ${maven.projectBasedir}/.mvn/jvm.config file:

-Xmx2048m -Xms1024m -XX:MaxPermSize=512m -Djava.awt.headless=true

The main advantage of this approach is that the configuration is isolated to the concerned project and applied to the whole build as well, and less fragile than MAVEN_OPTS for other developers working on the same project (forgetting to setting it).
Moreover, the options will be applied to all modules in case of a multi-module project.

When and Why to use abstract classes/methods?

Abstract classes/methods are generally used when a class provides some high level functionality but leaves out certain details to be implemented by derived classes. Making the class/method abstract ensures that it cannot be used on its own, but must be specialized to define the details that have been left out of the high level implementation. This is most often used with the template method pattern:

http://en.wikipedia.org/wiki/Template_method_pattern

How to include quotes in a string

As well as escaping quotes with backslashes, also see SO question 2911073 which explains how you could alternatively use double-quoting in a @-prefixed string:

string msg = @"I want to learn ""c#""";

SQLite DateTime comparison

SQLite doesn't have dedicated datetime types, but does have a few datetime functions. Follow the string representation formats (actually only formats 1-10) understood by those functions (storing the value as a string) and then you can use them, plus lexicographical comparison on the strings will match datetime comparison (as long as you don't try to compare dates to times or datetimes to times, which doesn't make a whole lot of sense anyway).

Depending on which language you use, you can even get automatic conversion. (Which doesn't apply to comparisons in SQL statements like the example, but will make your life easier.)

Swift add icon/image in UITextField

You can put this function your global file or above your class so you can access it in entire application. After this procedure you can call this function as per your requirement in application.

        func SetLeftSIDEImage(TextField: UITextField, ImageName: String){

                let leftImageView = UIImageView()
                leftImageView.contentMode = .scaleAspectFit

                let leftView = UIView()

                leftView.frame = CGRect(x: 20, y: 0, width: 30, height: 20)
                leftImageView.frame = CGRect(x: 13, y: 0, width: 15, height: 20)
                TextField.leftViewMode = .always
                TextField.leftView = leftView

                let image = UIImage(named: ImageName)?.withRenderingMode(.alwaysTemplate)
                leftImageView.image = image
                leftImageView.tintColor = UIColor(red: 106/255, green: 79/255, blue: 131/255, alpha: 1.0)
                leftImageView.tintColorDidChange()

                leftView.addSubview(leftImageView)
            }

            SetLeftSIDEImage(TextField: Your_textField, ImageName: “YourImageName”) // call function

Angular 2 Unit Tests: Cannot find name 'describe'

In order for TypeScript Compiler to use all visible Type Definitions during compilation, types option should be removed completely from compilerOptions field in tsconfig.json file.

This problem arises when there exists some types entries in compilerOptions field, where at the same time jest entry is missing.

So in order to fix the problem, compilerOptions field in your tscongfig.json should either include jest in types area or get rid of types comnpletely:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "target": "es6",
    "module": "commonjs",
    "outDir": "dist",
    "types": ["reflect-metadata", "jest"],  //<--  add jest or remove completely
    "moduleResolution": "node",
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

How do I set the selenium webdriver get timeout?

I find that the timeout calls are not reliable enough in real life, particularly for internet explorer , however the following solutions may be of help:

  1. You can timeout the complete test by using @Test(timeout=10000) in the junit test that you are running the selenium process from. This will free up the main thread for executing the other tests, instead of blocking up the whole show. However even this does not work at times.

  2. Anyway by timing out you do not intend to salvage the test case, because timing out even a single operation might leave the entire test sequence in inconsistent state. You might just want to proceed with the other testcases without blocking (or perhaps retry the same test again). In such a case a fool-proof method would be to write a poller that polls processes of Webdriver (eg. IEDriverServer.exe, Phantomjs.exe) running for more than say 10 min and kill them. An example could be found at Automatically identify (and kill) processes with long processing time

Fatal error: Call to a member function bind_param() on boolean

Following two are the most probable cause of this issue:

  1. Spelling mistake either in column names or table name
  2. Previously established statement is not closed. Just close it before making the prepared statement.

$stmt->close(); // <<<-----This fixed the issue for me

$stmt = $conn->prepare("Insert statement");

Extract Google Drive zip from Google colab notebook

Colab research team has a notebook for helping you out.

Still, in short, if you are dealing with a zip file, like for me it is mostly thousands of images and I want to store them in a folder within drive then do this --

!unzip -u "/content/drive/My Drive/folder/example.zip" -d "/content/drive/My Drive/folder/NewFolder"

-u part controls extraction only if new/necessary. It is important if suddenly you lose connection or hardware switches off.

-d creates the directory and extracted files are stored there.

Of course before doing this you need to mount your drive

from google.colab import drive 
drive.mount('/content/drive')

I hope this helps! Cheers!!

AngularJS custom filter function

Additionally, if you want to use the filter in your controller the same way you do it here:

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

You could do something like:

var filteredItems =  $scope.$eval('items | filter:filter:criteriaMatch(criteria)');

How to find third or n?? maximum salary from salary table?

If you want optimize way means use TOP Keyword, So the nth max and min salaries query as follows but the queries look like a tricky as in reverse order by using aggregate function names:

N maximum salary:

SELECT MIN(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP N EmpSalary FROM Salary ORDER BY EmpSalary DESC) 

for Ex: 3 maximum salary:

SELECT MIN(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP 3 EmpSalary FROM Salary ORDER BY EmpSalary DESC) 

N minimum salary:

SELECT MAX(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP N EmpSalary FROM Salary ORDER BY EmpSalary ASC)

for Ex: 3 minimum salary:

SELECT MAX(EmpSalary)
FROM Salary
WHERE EmpSalary IN(SELECT TOP 3 EmpSalary FROM Salary ORDER BY EmpSalary ASC)

How to check certificate name and alias in keystore files?

You can run the following command to list the content of your keystore file (and alias name):

keytool -v -list -keystore .keystore

If you are looking for a specific alias, you can also specify it in the command:

keytool -list -keystore .keystore -alias foo

If the alias is not found, it will display an exception:

keytool error: java.lang.Exception: Alias does not exist

JavaScript Chart Library

Check out ZingChart HTML5 Canvas, SVG, VML and Flash Charts. Very powerful and compatible library. I'm on the Zing team - mention us on twitter @zingchart or shoot any questions to [email protected].

Import Excel Data into PostgreSQL 9.3

For python you could use openpyxl for all 2010 and newer file formats (xlsx).

Al Sweigart has a full tutorial from automate the boring parts on working with excel spreadsheets its very indepth and the whole book and accompanying Udemy course are great resources.

From his example

>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">

Understandably once you have this access you can now use psycopg to parse the data to postgres as you normally would do.

This is a link to a list of python resources at python-excel also xlwings provides a large array of features for using python in place of vba in excel.

How does JavaScript .prototype work?

Javascript doesn't have inheritance in the usual sense, but it has the prototype chain.

prototype chain

If a member of an object can't be found in the object it looks for it in the prototype chain. The chain consists of other objects. The prototype of a given instance can be accessed with the __proto__ variable. Every object has one, as there is no difference between classes and instances in javascript.

The advantage of adding a function / variable to the prototype is that it has to be in the memory only once, not for every instance.

It's also useful for inheritance, because the prototype chain can consist of many other objects.

Flask raises TemplateNotFound error even though template file exists

(Please note that the above accepted Answer provided for file/project structure is absolutely correct.)

Also..

In addition to properly setting up the project file structure, we have to tell flask to look in the appropriate level of the directory hierarchy.

for example..

    app = Flask(__name__, template_folder='../templates')
    app = Flask(__name__, template_folder='../templates', static_folder='../static')

Starting with ../ moves one directory backwards and starts there.

Starting with ../../ moves two directories backwards and starts there (and so on...).

Hope this helps

Split an NSString to access one particular piece

Use [myString componentsSeparatedByString:@"/"]

Integer.valueOf() vs. Integer.parseInt()

Integer.valueOf() returns an Integer object, while Integer.parseInt() returns an int primitive.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

What is web.xml file and what are all things can I do with it?

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <description></description>
    <display-name>pdfServlet</display-name>
    <servlet-name>pdfServlet</servlet-name>
    <servlet-class>com.sapta.smartcam.servlet.pdfServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>pdfServlet</servlet-name>
    <url-pattern>/pdfServlet</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Visual Studio Code how to resolve merge conflicts with git?

The error message you are getting is a result of Git still thinking that you have not resolved the merge conflicts. In fact, you already have, but you need to tell Git that you have done this by adding the resolved files to the index.

This has the side effect that you could actually just add the files without resolving the conflicts, and Git would still think that you have. So you should be diligent in making sure that you have really resolved the conflicts. You could even run the build and test the code before you commit.

Saving to CSV in Excel loses regional date format

A not so scalable fix that I used for this is to copy the data to a plain text editor, convert the cells to text and then copy the data back to the spreadsheet.

Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

You can also use below mentioned code

Response.Write("<script type='text/javascript'>"); Response.Write("window.location = '" + redirect url + "'</script>");Response.Flush();

Define global variable with webpack

You can use define window.myvar = {}. When you want to use it, you can use like window.myvar = 1

Define global constants

All solutions seems to be complicated. I'm looking for the simplest solution for this case and I just want to use constants. Constants are simple. Is there anything which speaks against the following solution?

app.const.ts

'use strict';

export const dist = '../path/to/dist/';

app.service.ts

import * as AppConst from '../app.const'; 

@Injectable()
export class AppService {

    constructor (
    ) {
        console.log('dist path', AppConst.dist );
    }

}

Does VBA have Dictionary Structure?

Yes. For VB6, VBA (Excel), and VB.NET

Jackson: how to prevent field serialization

transient is the solution for me. thanks! it's native to Java and avoids you to add another framework-specific annotation.

Address already in use: JVM_Bind

My answer does 100% fit to this problem, but I want to document my solution and the trap behind it, since the Exception is the same.

My port was always in use testing a Jetty in a Junit testcase. Problem was Google's code pro on Eclipse, which, I guess, was testing in the background and thus starting jetty before me all the time. Workaround: let Eclipse open *.java files always w/ the Java editor instead of Google's Junit editor. That seems to help.

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

How can I change default dialog button text color in android 5

Here is how you do it: Simple way

// Initializing a new alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.message);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        doAction();
    }
});
builder.setNegativeButton(R.string.cancel, null);

// Create the alert dialog and change Buttons colour
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface arg0) {
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.red));
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.blue));
        //dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(getResources().getColor(R.color.black));
    }
});
dialog.show();

How to install SQL Server 2005 Express in Windows 8

install "SQL Express 2005 service pack 4" version "directly".

it contains sql Express 2005 inside . dont let the name fool you

runs succesfuly. from my experince

enter image description here

Lua - Current time in milliseconds

If your environment is Windows and you have access to system commands, you can get time of centiseconds precision with io.popen(command):

local handle = io.popen("echo %time%")
local result = handle:read("*a")
handle:close()

The result will hold string of hh:mm:ss.cc format: (with trailing line break)

"19:56:53.90\n"

Note, it's in local timesone, so you probably want to extract only the .cc part and combine it with epoch seconds from os.time().

How to select option in drop down protractorjs e2e tests

Here is how to do it by either option value or index. This example is a bit crude, but it shows how to do what you want:

html:

<mat-form-field id="your-id">
    <mat-select>
        <mat-option [value]="1">1</mat-option>
        <mat-option [value]="2">2</mat-option>
    </mat-select>
</mat-form-field>

ts:

function selectOptionByOptionValue(selectFormFieldElementId, valueToFind) {

  const formField = element(by.id(selectFormFieldElementId));
  formField.click().then(() => {

    formField.element(by.tagName('mat-select'))
      .getAttribute('aria-owns').then((optionIdsString: string) => {
        const optionIds = optionIdsString.split(' ');    

        for (let optionId of optionIds) {
          const option = element(by.id(optionId));
          option.getText().then((text) => {
            if (text === valueToFind) {
              option.click();
            }
          });
        }
      });
  });
}

function selectOptionByOptionIndex(selectFormFieldElementId, index) {

  const formField = element(by.id(selectFormFieldElementId));
  formField.click().then(() => {

    formField.element(by.tagName('mat-select'))
      .getAttribute('aria-owns').then((optionIdsString: string) => {
        const optionIds = optionIdsString.split(' ');

        const optionId = optionIds[index];
        const option = element(by.id(optionId));
        option.click();
      });
  });
}

selectOptionByOptionValue('your-id', '1'); //selects first option
selectOptionByOptionIndex('your-id', 1); //selects second option

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

In Java I had to set a property

System.setProperty(SDKGlobalConfiguration.ENFORCE_S3_SIGV4_SYSTEM_PROPERTY, "true")

and add the region to the s3Client instance.

s3Client.setRegion(Region.getRegion(Regions.EU_CENTRAL_1))

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

Angular2 dynamic change CSS property

Angular 6 + Alyle UI

With Alyle UI you can change the styles dynamically

Here a demo stackblitz

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    AlyleUIModule.forRoot(
      {
        name: 'myTheme',
        primary: {
          default: '#00bcd4'
        },
        accent: {
          default: '#ff4081'
        },
        scheme: 'myCustomScheme', // myCustomScheme from colorSchemes
        lightGreen: '#8bc34a',
        colorSchemes: {
          light: {
            myColor: 'teal',
          },
          dark: {
            myColor: '#FF923D'
          },
          myCustomScheme: {
            background: {
              primary: '#dde4e6',
            },
            text: {
              default: '#fff'
            },
            myColor: '#C362FF'
          }
        }
      }
    ),
    LyCommonModule, // for bg, color, raised and others
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Html

<div [className]="classes.card">dynamic style</div>
<p color="myColor">myColor</p>
<p bg="myColor">myColor</p>

For change Style

import { Component } from '@angular/core';
import { LyTheme } from '@alyle/ui';

@Component({ ... })
export class AppComponent  {
  classes = {
    card: this.theme.setStyle(
      'card', // key
      () => (
        // style
        `background-color: ${this.theme.palette.myColor};` +
        `position: relative;` +
        `margin: 1em;` +
        `text-align: center;`
         ...
      )
    )
  }
  constructor(
    public theme: LyTheme
  ) { }

  changeScheme() {
    const scheme = this.theme.palette.scheme === 'light' ?
    'dark' : this.theme.palette.scheme === 'dark' ?
    'myCustomScheme' : 'light';
    this.theme.setScheme(scheme);
  }
}

Github Repository

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

 select p.post_title,m.meta_value sale_price ,n.meta_value   regular_price
    from  wp_postmeta m 
    inner join wp_postmeta n
      on m.post_id  = n.post_id
    inner join wp_posts p
      ON m.post_id=p.id 
    and m.meta_key = '_sale_price'
    and  n.meta_key = '_regular_price'
     AND p.post_type = 'product';



 update  wp_postmeta m 
inner join wp_postmeta n
  on m.post_id  = n.post_id
inner join wp_posts p
  ON m.post_id=p.id 
and m.meta_key = '_sale_price'
and  n.meta_key = '_regular_price'
 AND p.post_type = 'product'
 set m.meta_value = n.meta_value;

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

When user press F5 although new request goes to web server and get a responce for the request as well. But when the responce header is Parsed it check the required information in browser cache. If the required information in cache has not expired then that information is restored from in cache itself.

When user click on CTRL-F5 even then new request goes to web server and get a responce. But this time when the responce header is Parsed it do not check any required information in cache, and bring all updated information form server only.

Scale iFrame css width 100% like an image

I like this solution best. Simple, scalable, responsive. The idea here is to create a zero-height outer div with bottom padding set to the aspect ratio of the video. The iframe is scaled to 100% in both width and height, completely filling the outer container. The outer container automatically adjusts its height according to its width, and the iframe inside adjusts itself accordingly.

<div style="position:relative; width:100%; height:0px; padding-bottom:56.25%;">
    <iframe style="position:absolute; left:0; top:0; width:100%; height:100%"
        src="http://www.youtube.com/embed/RksyMaJiD8Y">
    </iframe>
</div>

The only variable here is the padding-bottom value in the outer div. It's 75% for 4:3 aspect ratio videos, and 56.25% for widescreen 16:9 aspect ratio videos.