Programs & Examples On #Visual studio 2008

This tag refers to the Visual Studio line of software development products from Microsoft, the 2008 version. Do not use this tag unless you have a specific question about Visual Studio -- not just a coding issue. Questions should be specific to the 2008 version of Visual Studio.

Find in Files: Search all code in Team Foundation Server

We have set up a solution for Team Foundation Server Source Control (not SourceSafe as you mention) similar to what Grant suggests; scheduled TF Get, Search Server Express. However the IFilter used for C# files (text) was not giving the results we wanted, so we convert source files to .htm files. We can now add additional meta-data to the files such as:

  • Author (we define it as the person that last checked in the file)
  • Color coding (on our todo-list)
  • Number of changes indicating potential design problems (on our todo-list)
  • Integrate with the VSTS IDE like Koders SmartSearch feature
  • etc.

We would however prefer a protocolhandler for TFS Source Control, and a dedicated source code IFilter for a much more targeted solution.

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

I often found that copy/pasting caused this behaviour for me. Most cases can be solved by editing the ID of a server control (just add a character, then delete it).

Also remember that control inside things like Repeaters aren't visible in the designer file.

And yes, there are cases where you need to do the delete-the-file magic listed above - but the name-change solution will work most of the time.

Edit and Continue: "Changes are not allowed when..."

I had this problem in Microsoft Visual Studio 2008 and the solution is easy. when you run your project please set in "Debug" mode not "Release". The another people solution can be useful.

How do I add my new User Control to the Toolbox or a new Winform?

One way to get this error is trying to add a usercontrol to a form while the project is set to compile as x64. Visual Studio throws the unhelpful: "Failed to load toolbox item . It will be removed from the toolbox."

Workaround is to design with "Any CPU" and compile to x64 as necessary.

Reference: https://support.microsoft.com/en-us/kb/963017

Visual Studio Post Build Event - Copy to Relative Directory Location

Here is what you want to put in the project's Post-build event command line:

copy /Y "$(TargetDir)$(ProjectName).dll" "$(SolutionDir)lib\$(ProjectName).dll"

EDIT: Or if your target name is different than the Project Name.

copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)lib\$(TargetName).dll"

How to define relative paths in Visual Studio Project?

By default, all paths you define will be relative. The question is: relative to what? There are several options:

  1. Specifying a file or a path with nothing before it. For example: "mylib.lib". In that case, the file will be searched at the Output Directory.
  2. If you add "..\", the path will be calculated from the actual path where the .sln file resides.

Please note that following a macro such as $(SolutionDir) there is no need to add a backward slash "\". Just use $(SolutionDir)mylibdir\mylib.lib. In case you just can't get it to work, open the project file externally from Notepad and check it.

Why can't I reference my class library?

Since they are both in the same solution, instead of adding a reference to the DLL, add a reference to the class library project itself (the Add Reference dialog will have a tab for this).

Ahh, it's a different solution. Missed that. How about you try instead of adding a reference to the project addding a reference to the compiled DLL of your class library. The Add Reference dialog has a Browse tab which does this.

Visual Studio: Relative Assembly References Paths

Probably, the easiest way to achieve this is to simply add the reference to the assembly and then (manually) patch the textual representation of the reference in the corresponding Visual Studio project file (extension .csproj) such that it becomes relative.

I've done this plenty of times in VS 2005 without any problems.

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

I think this sort of question is entirely appropriate to the forum, especially if an easy solution can be found, as would save others hours of pain.

Unfortunately I dont have the solution, but would suggest (if you haven't already)

  1. Run FileMon to see if the installer is looking for specific files which are no longer there - this may give some clues.

  2. Painful, but try uninstalling other apps based upon the VS shell (eg 2005) first.

SSRS the definition of the report is invalid

I found the problem to this... due to a incorrect/failed reference in .rdl to data conns etc. Also found that BIDS wasn't happy about having spaces in some of the project/report filenames... so anyone facing this issue make sure you have no spaces in your naming and check your rdl files, connections, everything for failed/out of date references! Visual Studio seems crap at keeping all of it's references up to date... god forbid you have to rename anything!

How can I disable ReSharper in Visual Studio and enable it again?

If resharper is completely missing from the options menu, it could be because the extension itself has been disabled.

In Visual Studio 2017 ReSharper 2018.X.X can be enabled and disabled by going to Help > Manage Visual Studio Performance. Then select JetBrains ReSharper ... under Extensions.

enter image description here

In Visual Studio 2019, you would go under Extensions->Manage Extensions->Installed

How to have comments in IntelliSense for function in Visual Studio?

read http://msdn.microsoft.com/en-us/library/3260k4x7.aspx Just specifying the comments will not show the help comments in intellisense.

How do I create/edit a Manifest file?

In Visual Studio 2019 WinForm Projects, it is available under

Project Properties -> Application -> View Windows Settings (button)

enter image description here

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

Make sure any XML file (or any file that would be interpreted as an XML file by visual studio) has a correct XML structure - that is, one root element (with any name, I have use rootElement in my example):

<?xml version="1.0"?> 
<rootElement>
 ...
</rootElement>

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

How to insert Records in Database using C# language?

Use a parameterized query to prevent Sql injections (secutity problem)

Use the using statement so the connection will be closed and resources will be disposed.

using(var connection = new SqlConnection("connectionString"))
{
    connection.Open();
    var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
    using(var cmd = new SqlCommand(sql, connection))
    {
        cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
        cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);

        cmd.ExecuteNonQuery();
    }
}

Auto generate function documentation in Visual Studio

Make that "three single comment-markers"

In C# it's ///

which as default spits out:

/// <summary>
/// 
/// </summary>
/// <returns></returns>

Here's some tips on editing VS templates.

Select All as default value for Multivalue parameter

Adding to the answer from E_8.
This does not work if you have empty strings.

You can get around this by modifying your select statement in SQL or modifying your query in the SSRS dataset.

 Select distinct phonenumber
from YourTable
where phonenumber <> ''
Order by Phonenumber

Visual Studio - How to change a project's folder name and solution name without breaking the solution

go to my start-documents-iisExpress-config and then right click on applicationhost and select open with visual studio 2013 for web you will get into applicationhost.config window in the visual studio and now in the region chsnge the physical path to the path where your project is placed

How to set standard encoding in Visual Studio

I don't know of a global setting nither but you can try this:

  1. Save all Visual Studio templates in UTF-8
  2. Write a Visual Studio Macro/Addin that will listen to the DocumentSaved event and will save the file in UTF-8 format (if not already).
  3. Put a proxy on your source control that will make sure that new files are always UTF-8.

LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

I had this happen in Visual Studio 2015 too for an interesting reason. Just adding it here in case it happens to someone else.

I already had number of files in project and I was adding another one that would have main function in it, however when I initially added the file I made a typo in the extension (.coo instead of .cpp). I corrected that but when I was done I got this error. It turned out that Visual Studio was being smart and when file was added it decided that it is not a source file due to the initial extension.

Right-clicking on file in solution explorer and selecting Properties -> General -> ItemType and setting it to "C/C++ compiler" fixed the issue.

The name 'ConfigurationManager' does not exist in the current context

In NetCore 3.1 I had to use Microsoft.Extensions.Configuration instead:

    public static async Task Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
            .Build();

...

Unexpected end of file error

Change the Platform of your C++ project to "x64" (or whichever platform you are targeting) instead of "Win32". This can be found in Visual Studio under Build -> Configuration Manager. Find your project in the list and change the Platform column. Don't forget to do this for all solution configurations.

How to add New Column with Value to the Existing DataTable?

Add the column and update all rows in the DataTable, for example:

DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
    DataRow row = tbl.NewRow();
    row["ID"] = i;
    row["Name"] = i + ". row";
    tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
    row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;

how to open *.sdf files?

It's a SQL Compact database. You need to define what you mean by "Open". You can open it via code with the SqlCeConnection so you can write your own tool/app to access it.

Visual Studio can also open the files directly if was created with the right version of SQL Compact.

There are also some third-party tools for manipulating them.

Git in Visual Studio - add existing project?

After slogging around Visual Studio I finally figured out the answer that took far longer than it should have.

In order to take an existing project without source control and put it to an existing EMPTY (this is important) GitHub repository, the process is simple, but tricky, because your first inclination is to use the Team Explorer, which is wrong and is why you're having problems.

First, add it to source control. There are some explanations of that above, and everybody gets this far.

Now, this opens an empty LOCAL repository and the trick which nobody ever tells you about is to ignore the Team Explorer completely and go to the Solution Explorer, right click the solution and click Commit.

This then commits all differences between your existing solution and the local repository, essentially updating it with all these new files. Give it a default commit name 'initial files' or whatever floats your boat and commit.

Then simply click Sync on the next screen and drop in the EMPTY GitHub repository URL. Make sure it's empty or you'll have master branch conflicts and it won't let you. So either use a new repository or delete the old one that you had previously screwed up. Bear in mind this is Visual Studio 2013, so your mileage may vary.

Metadata file '.dll' could not be found

I faced this issue after getting latest (Team Foundation Server (TFS) command).

After resolving the conflicts I found using a statement for a namespace that does not exist in the project.

So I removed that using statement then clean and rebuild, and everything was OK.

How do I start a program with arguments when debugging?

For Visual Studio Code:

  • Open launch.json file
  • Add args to your configuration:

"args": ["some argument", "another one"],

app.config for a class library

I would recommend using Properties.Settings to store values like ConnectionStrings and so on inside of the class library. This is where all the connection strings are stores in by suggestion from visual studio when you try to add a table adapter for example. enter image description here

And then they will be accessible by using this code every where in the clas library

var cs=  Properties.Settings.Default.[<name of defined setting>];

MSBUILD : error MSB1008: Only one project can be specified

I was using single quotes around the password parameter when I got the error

/p:password='my secret' bad

and changed it to use double quotes to resolve the issue.

/p:password="my secret" good

Likely the same would apply to any parameter that needs quotes for values that contain a space.

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

How can I generate UUID in C#

Be careful: while the string representations for .NET Guid and (RFC4122) UUID are identical, the storage format is not. .NET trades in little-endian bytes for the first three Guid parts.

If you are transmitting the bytes (for example, as base64), you can't just use Guid.ToByteArray() and encode it. You'll need to Array.Reverse the first three parts (Data1-3).

I do it this way:

var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);

See this answer for the specific .NET implementation details.

Edit: Thanks to Jeff Walker, Code Ranger, for pointing out that the internals are not relevant to the format of the byte array that goes in and out of the byte-array constructor and ToByteArray().

String escape into XML

George, it's simple. Always use the XML APIs to handle XML. They do all the escaping and unescaping for you.

Never create XML by appending strings.

Visual Studio 2008 Product Key in Registry?

For 32 bit Windows:


Visual Studio 2003:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.0\Registration\PIDKEY

Visual Studio 2005:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY

Visual Studio 2008:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY


For 64 bit Windows:


Visual Studio 2003:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\7.0\Registration\PIDKEY

Visual Studio 2005:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\8.0\Registration\PIDKEY

Visual Studio 2008:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\Registration\PIDKEY


Notes:

  • Data is a GUID without dashes. Put a dash ( – ) after every 5 characters to convert to product key.
  • If PIDKEY value is empty try to look at the subfolders e.g.

    ...\Registration\1000.0x0000\PIDKEY

    or

    ...\Registration\2000.0x0000\PIDKEY

Visual Studio window which shows list of methods

With Visual Studio 2010

You choose Tools->Settings->Expert Settings

On the left-bottom corner, you will see the tab "Class View" right next tab "Solution Explorer"

In the top area of "Class View" layout, you will see the list of class name, enum, struct, ... In the bottom area of "Class View layout, you will see the list of member for these class, enum or struct

Visual Studio Copy Project

After trying above solutions & creating copy for MVC projects

For MVC projects please update the port numbers in .csproj file, you can take help of iis applicationhost.config to check the port numbers. Same port numbers will cause assembly loading issue in IIS.

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

For everybody who uses Rider you have to select your project>Right Click>Properties>Configurations Then select Debug and Release and check "Allow unsafe code" for both.Screenshot

Convert Text to Uppercase while typing in Text box

if you can use LinqToObjects in your Project

private YourTextBox_TextChanged ( object sender, EventArgs e)
{
   return YourTextBox.Text.Where(c=> c.ToUpper());
}

An if you can't use LINQ (e.g. your project's target FW is .NET Framework 2.0) then

private YourTextBox_TextChanged ( object sender, EventArgs e)
{
   YourTextBox.Text = YourTextBox.Text.ToUpper();
}

Why Text_Changed Event ?

There are few user input events in framework..

1-) OnKeyPressed fires (starts to work) when user presses to a key from keyboard after the key pressed and released

2-) OnKeyDown fires when user presses to a key from keyboard during key presses

3-) OnKeyUp fires when user presses to a key from keyboard and key start to release (user take up his finger from key)

As you see, All three are about keyboard event..So what about if the user copy and paste some data to the textbox?

if you use one of these keyboard events then your code work when and only user uses keyboard..in example if user uses a screen keyboard with mouse click or copy paste the data your code which implemented in keyboard events never fires (never start to work)

so, and Fortunately there is another option to work around : The Text Changed event..

Text Changed event don't care where the data comes from..Even can be a copy-paste, a touchscreen tap (like phones or tablets), a virtual keyboard, a screen keyboard with mouse-clicks (some bank operations use this to much more security, or may be your user would be a disabled person who can't press to a standard keyboard) or a code-injection ;) ..

No Matter !

Text Changed event just care about is there any changes with it's responsibility component area ( here, Your TextBox's Text area) or not..

If there is any change occurs, then your code which implemented under Text changed event works..

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

If you are using Entity Framework 6, the name space has changed. You want to use

System.Data.Entity.Core.Objects.ObjectQuery

How do I set the icon for my application in visual studio 2008?

First go to Resource View (from menu: View --> Other Window --> Resource View). Then in Resource View navigate through resources, if any. If there is already a resource of Icon type, added by Visual Studio, then open and edit it. Otherwise right-click and select Add Resource, and then add a new icon.

Use the embedded image editor in order to edit the existing or new icon. Note that an icon can include several types (sizes), selected from Image menu.

Then compile your project and see the effect.

See: http://social.microsoft.com/Forums/en-US/vcgeneral/thread/87614e26-075c-4d5d-a45a-f462c79ab0a0

Shortcut for changing font size

In visual studio code if your front is too small or too big, then you just need to zoom out or zoom in. To do that you just have to do:

  • For zoom in : ctrl + = (ctrl and equal both)
  • For zoom out: ctrl + - (ctrl and - both)

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.

Turn off auto formatting in Visual Studio

I doubt that you can disable re-formatting after refactoring. Refactoring changes code and since it's only text I doubt what you'd want is that it just dumps unformatted text into your source. Wouldn't it be a little easier to just set the code style VS adheres to to the style you like and follow?

Setting the default page for ASP.NET (Visual Studio) server configuration

If you are running against IIS rather than the VS webdev server, ensure that Index.aspx is one of your default files and that directory browsing is turned off.

What does the Visual Studio "Any CPU" target mean?

Check out the article Visual Studio .NET Platform Target Explained.

The default setting, "Any CPU", means that the assembly will run natively on the CPU it is currently running on. Meaning, it will run as 64-bit on a 64-bit machine and 32-bit on a 32-bit machine. If the assembly is called from a 64-bit application, it will perform as a 64-bit assembly and so on.

The above link has been reported to be broken, so here is another article with a similar explanation: What AnyCPU Really Means As Of .NET 4.5 and Visual Studio 11

How do I compile a Visual Studio project from the command-line?

MSBuild usually works, but I've run into difficulties before. You may have better luck with

devenv YourSolution.sln /Build 

If statements for Checkboxes

I simplification for Science_Fiction's answer I think is to use the exclusive or function so you can just have:

if(checkbox1.checked ^ checkbox2.checked)
{
//do stuff
}

That is assuming you want to do the same thing for both situations.

download and install visual studio 2008

https://www.microsoft.com/en-us/download/details.aspx?id=14258

which leads to:

Microsoft® Visual Studio Team System 2008 Database Edition GDR R2

Hope this is helpfull

Setting Icon for wpf application (VS 08)

After getting a XamlParseException with message: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' with the given solutions, setting the icon programmatically worked for me. This is how I did it:

  1. Put the icon in a folder <icon_path> in the project directory
  2. Mimic the folder path <icon_path> in the solution
  3. Add a new item (your icon) in the solution folder you created
  4. Add the following code in the WPF window's code behind:

Icon = new BitmapImage(new Uri("<icon_path>", UriKind.Relative));

Please inform me if you have any difficulties implementing this solution so I can help.

What is and how to fix System.TypeInitializationException error?

System.TypeInitializationException happens when the code that gets executed during the process of loading the type throws an exception.

When .NET loads the type, it must prepare all its static fields before the first time that you use the type. Sometimes, initialization requires running code. It is when that code fails that you get a System.TypeInitializationException.

In your specific case, the following three static fields run some code:

private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");
private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);

Note that s_bstCommonAppData depends on s_commonAppData, but it is declared ahead of its dependency. Therefore, the value of s_commonAppData is null at the time that the Path.Combine is called, resulting in ArgumentNullException. Same goes for the s_bstUserDataDir and s_bstCommonAppData: they are declared in reverse order to the desired order of initialization.

Re-order the lines to fix this problem:

private static string s_commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
private static string s_bstCommonAppData = Path.Combine(s_commonAppData, "XXXX");
private static string s_bstUserDataDir = Path.Combine(s_bstCommonAppData, "UserData");

Access cell value of datatable

foreach(DataRow row in dt.Rows)
{
    string value = row[3].ToString();
}

Post Build exited with code 1

She had a space in one of the folder names in her path, and no quotes around it.

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

You need to add asp content and add content place holder id correspond to the placeholder in master page.

You can read this link for more detail

Executable directory where application is running from?

You can write the following:

Path.Combine(Path.GetParentDirectory(GetType(MyClass).Assembly.Location), "Images\image.jpg")

Visual Studio move project to a different folder

I figured out this try this it worked for me.

In visual studio 2017 community edition it creates a project at this path "C:\Users\mark\source\repos\mipmaps\mipmaps" This will create a access to file is denied issue

Now, you can fix that this way.

close your visual studio process. Then, find your project and copy the project folder But, first make a Sub-folder Named Projects inside of your visual studio 2017 folder in documents. Next, paste the project folder inside of your visual studio 2017 Project folder not the main visual studio 2017 folder it should go into the Sub-folder called Projects. Next, restart Visual studio 2017 Then, choose Open project Solution Then, find your project you pasted in your visual studio 2017 Projects folder Then clean the Project and rebuild it , It, should build and compile just fine. Hope, this Helped out anybody else. Not to sure why Microsoft thought building your projects in a path where it needs write permissions is beyond me.

Set Google Chrome as the debugging browser in Visual Studio

  1. Go to the visual studio toolbar and click on the dropdown next to CPU (where it says IIS Express in the screenshot). One of the choices should be "Browse With..."

    Visual Studio Toolbar

  2. Select a browser, e.g. Google Chrome, then click Set as Default

    Browse With...

  3. Click Browse or Cancel.

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

Alt + Shift + F10 will show the menu associated with the smart tag.

Where can I find WcfTestClient.exe (part of Visual Studio)

FYI - I could not find WcfTestClient.exe under any of the listed file paths. It turns out it needed to be installed by Visual Studio Installer. When you launch the installer and modify your version of VS, make sure Windows Communication Foundation is checked under Optional. It may seem obvious, but it wasn't to me and therefore might not be obvious to everyone else.

Go to Matching Brace in Visual Studio?

Note: It also works for #if / #elif / #endif matching. The caret must be on the #.

How to change the default browser to debug with in Visual Studio 2008?

First click show all files. Then in the bin folder choose any xml file and then right click and by selecting 'browse with' select your desired browser.

How to debug a referenced dll (having pdb)

If you have a project reference, it should work immediately.

If it is a file (dll) reference, you need the debugging symbols (the "pdb" file) to be in the same folder as the dll. Check that your projects are generating debug symbols (project properties => Build => Advanced => Output / Debug Info = full); and if you have copied the dll, put the pdb with it.

You can also load symbols directly in the IDE if you don't want to copy any files, but it is more work.

The easiest option is to use project references!

How to set session timeout in web.config

If you want to set the timeout to 20 minutes, use something like this:

    <configuration>
      <system.web>
         <sessionState timeout="20"></sessionState>
      </system.web>
    </configuration>

The project type is not supported by this installation

If you are using VS 2010 and it is a ASP.NET project make sure you have the Visual Developer installed from the VS 2010 CD. This is not the free one, but part of what is required to work on ASP.NET projects in Visual Studio.

Connecting to SQL Server with Visual Studio Express Editions

The only way I was able to get C# Express 2008 to work was to move the database file. So, I opened up SQL Server Management Studio and after dropping the database, I copied the file to my project folder. Then I reattached the database to management studio. Now, when I try to attach to the local copy it works. Apparently, you can not use the same database file more than once.

Is "&#160;" a replacement of "&nbsp;"?

  • &nbsp; is the character entity reference (meant to be easily parseable by humans).
  • &#160; is the numeric entity reference (meant to be easily parseable by machines).

They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.

You can read more about character entity references in the offical W3C documents.

Calling functions in a DLL from C++

Can also export functions from dll and import from the exe, it is more tricky at first but in the end is much easier than calling LoadLibrary/GetProcAddress. See MSDN.

When creating the project with the VS wizard there's a check box in the dll that let you export functions.

Then, in the exe application you only have to #include a header from the dll with the proper definitions, and add the dll project as a dependency to the exe application.

Check this other question if you want to investigate this point further Exporting functions from a DLL with dllexport.

Visual Studio : short cut Key : Duplicate Line

if you have a macos version, cmd+shift+D can make the job for you

I want to delete all bin and obj folders to force all projects to rebuild everything

For the solution in batch. I am using the following command:

FOR /D /R %%G in (obj,bin) DO @IF EXIST %%G IF %%~aG geq d RMDIR /S /Q "%%G"


The reason not using DIR /S /AD /B xxx
1. DIR /S /AD /B obj will return empty list (at least on my Windows10) enter image description here
2. DIR /S /AD /B *obj will contain the result which is not expected (tobj folder) enter image description here

Visual Studio can't 'see' my included header files

In my experience, with VS2010, when include files can't be found at compile time, doing a clean, then build usually fixes the problem. It's not that rare for the editor to be able to open an include file and then the compiler to announce that it can't find that very file, even when it is open on the screen!

C# adding a character in a string

You can use this:

string alpha = "abcdefghijklmnopqrstuvwxyz";
int length = alpha.Length;

for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
{
    alpha = alpha.Insert(i, "-");
}

Works perfectly with any string. As always, the size doesn't matter. ;)

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

Css transition from display none to display block, navigation with subnav

Generally when people are trying to animate display: none what they really want is:

  1. Fade content in, and
  2. Have the item not take up space in the document when hidden

Most popular answers use visibility, which can only achieve the first goal, but luckily it's just as easy to achieve both by using position.

Since position: absolute removes the element from typing document flow spacing, you can toggle between position: absolute and position: static (global default), combined with opacity. See the below example.

_x000D_
_x000D_
.content-page {_x000D_
  position:absolute;_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
.content-page.active {_x000D_
  position: static;_x000D_
  opacity: 1;_x000D_
  transition: opacity 1s linear;_x000D_
}
_x000D_
_x000D_
_x000D_

Is there a REAL performance difference between INT and VARCHAR primary keys?

Not sure about the performance implications, but it seems a possible compromise, at least during development, would be to include both the auto-incremented, integer "surrogate" key, as well as your intended, unique, "natural" key. This would give you the opportunity to evaluate performance, as well as other possible issues, including the changeability of natural keys.

PHP - add 1 day to date format mm-dd-yyyy

$date = DateTime::createFromFormat('m-d-Y', '04-15-2013');
$date->modify('+1 day');
echo $date->format('m-d-Y');

See it in action

Or in PHP 5.4+

echo (DateTime::createFromFormat('m-d-Y', '04-15-2013'))->modify('+1 day')->format('m-d-Y');

reference

How do I update Anaconda?

Open "command or conda prompt" and run:

conda update conda
conda update anaconda

It's a good idea to run both command twice (one after the other) to be sure that all the basic files are updated.

This should put you back on the latest 'releases', which contains packages that are selected by the people at Continuum to work well together.

If you want the last version of each package run (this can lead to an unstable environment):

conda update --all 

Hope this helps.

Sources:

How to exclude property from Json Serialization

Sorry I decided to write another answer since none of the other answers are copy-pasteable enough.

If you don't want to decorate properties with some attributes, or if you have no access to the class, or if you want to decide what to serialize during runtime, etc. etc. here's how you do it in Newtonsoft.Json

//short helper class to ignore some properties from serialization
public class IgnorePropertiesResolver : DefaultContractResolver
{
    private readonly HashSet<string> ignoreProps;
    public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
    {
        this.ignoreProps = new HashSet<string>(propNamesToIgnore);
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);
        if (this.ignoreProps.Contains(property.PropertyName))
        {
            property.ShouldSerialize = _ => false;
        }
        return property;
    }
}

Usage

JsonConvert.SerializeObject(YourObject, new JsonSerializerSettings()
        { ContractResolver = new IgnorePropertiesResolver(new[] { "Prop1", "Prop2" }) };);

Note: make sure you cache the ContractResolver object if you decide to use this answer, otherwise performance may suffer.

I've published the code here in case anyone wants to add anything

https://github.com/jitbit/JsonIgnoreProps

Name [jdbc/mydb] is not bound in this Context

you put resource-ref in the description tag in web.xml

How to change the button text of <input type="file" />?

In Bootstrap +4.5 you can simply add bellow style to your code:

<style>
    .custom-file-input ~ .custom-file-label::after {
        content: "Your custom text ...";
    }
</style>

and your input:

<div class="custom-file">
    <input type="file" class="custom-file-input">
    <label class="custom-file-label">Your custom placeholder ...</label>
</div>

How to display multiple notifications in android

At the place of uniqueIntNo put unique integer number like this:

mNotificationManager.notify(uniqueIntNo, builder.build());

Why do package names often begin with "com"

  • com => domain
  • something => company name
  • something => Main package name

For example: com.paresh.mainpackage

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com. This information i have found at http://download.oracle.com/javase/tutorial/java/package/namingpkgs.html

http post - how to send Authorization header?

I had the same issue. This is my solution using angular documentation and firebase Token:

getService()  {

const accessToken=this.afAuth.auth.currentUser.getToken().then(res=>{
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': res
    })
  };
  return this.http.get('Url',httpOptions)
    .subscribe(res => console.log(res));
}); }}

Automatically plot different colored lines

Late to the party. I was looking into this myself and just found about this axes option called ColorOrder you can specify the colour order for the session or just for the figure and then just plot an array and let MATLAB automatically cycle through the colours specified.

see Changing the Default ColorOrder

example

set(0,'DefaultAxesColorOrder',jet(5))
A=rand(10,5);
plot(A);

When to use a linked list over an array/array list?

Hmm, Arraylist can be used in cases like follows I guess:

  1. you are not sure how many elements will be present
  2. but you need to access all the elements randomly through indexing

For eg, you need to import and access all elements in a contact list (the size of which is unknown to you)

How to add Headers on RESTful call using Jersey Client API

Try this!

Client client = ClientBuilder.newClient();

String jsonStr = client
            .target("http:....")
            .request(MediaType.APPLICATION_JSON)

            .header("WM_SVC.NAME", "RegistryService")
            .header("WM_QOS.CORRELATION_ID", "d1f0c0d2-2cf4-497b-b630-06d609d987b0")

            .get(String.class);

P.S You can add any number of headers like this!

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

Besides all above solutions, check if you have the "id" or any custom defined parameter in the DELETE method is matching the route config.

public void Delete(int id)
{
 //some code here
}

If you hit with repeated 405 errors better reset the method signature to default as above and try.

The route config by default will look for id in the URL. So the parameter name id is important here unless you change the route config under App_Start folder.

You may change the data type of the id though.

For example the below method should work just fine:

public void Delete(string id)
{
 //some code here
}

Note: Also ensure that you pass the data over the url not the data method that will carry the payload as body content.

DELETE http://{url}/{action}/{id}

Example:

DELETE http://localhost/item/1

Hope it helps.

Where does the .gitignore file belong?

You may also find a global .gitignore directly at the ~ path if you haven't created it in your folder project. This file is taken into account by all your .git projects.

Best way to remove duplicate entries from a data table

    /* To eliminate Duplicate rows */
    private void RemoveDuplicates(DataTable dt)
    {

        if (dt.Rows.Count > 0)
        {
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                if (i == 0)
                {
                    break;
                }
                for (int j = i - 1; j >= 0; j--)
                {
                    if (Convert.ToInt32(dt.Rows[i]["ID"]) == Convert.ToInt32(dt.Rows[j]["ID"]) && dt.Rows[i]["Name"].ToString() == dt.Rows[j]["Name"].ToString())
                    {
                        dt.Rows[i].Delete();
                        break;
                    }
                }
            }
            dt.AcceptChanges();
        }
    }

Best way to do nested case statement logic in SQL Server

This example might help you, the picture shows how SQL case statement will look like when there are if and more than one inner if loops

enter image description here

How to return a class object by reference in C++?

I will show you some examples:

First example, do not return local scope object, for example:

const string &dontDoThis(const string &s)
{
    string local = s;
    return local;
}

You can't return local by reference, because local is destroyed at the end of the body of dontDoThis.

Second example, you can return by reference:

const string &shorterString(const string &s1, const string &s2)
{
    return (s1.size() < s2.size()) ? s1 : s2;
}

Here, you can return by reference both s1 and s2 because they were defined before shorterString was called.

Third example:

char &get_val(string &str, string::size_type ix)
{
    return str[ix];
}

usage code as below:

string s("123456");
cout << s << endl;
char &ch = get_val(s, 0); 
ch = 'A';
cout << s << endl; // A23456

get_val can return elements of s by reference because s still exists after the call.

Fourth example

class Student
{
public:
    string m_name;
    int age;    

    string &getName();
};

string &Student::getName()
{
    // you can return by reference
    return m_name;
}

string& Test(Student &student)
{
    // we can return `m_name` by reference here because `student` still exists after the call
    return stu.m_name;
}

usage example:

Student student;
student.m_name = 'jack';
string name = student.getName();
// or
string name2 = Test(student);

Fifth example:

class String
{
private:
    char *str_;

public:
    String &operator=(const String &str);
};

String &String::operator=(const String &str)
{
    if (this == &str)
    {
        return *this;
    }
    delete [] str_;
    int length = strlen(str.str_);
    str_ = new char[length + 1];
    strcpy(str_, str.str_);
    return *this;
}

You could then use the operator= above like this:

String a;
String b;
String c = b = a;

How to search all loaded scripts in Chrome Developer Tools?

Open a new Search pane in Developer Tools by:

  • pressing Ctrl+Shift+F (Cmd+Option+I on mac)
  • clicking the overflow menu (?) in DevTools, DevTools overflow menu
  • clicking the overflow menu in the Console (?) and choosing the Search option

You can search across all your scripts with support for regular expressions and case sensitivity.

Click any match to load that file/section in the scripts panel.

Search all files - results

Make sure 'Search in anonymous and content scripts' is checked in the DevTools Preferences (F1). This will return results from within iframes and HTML inline scripts:

Search in anonymous and content scripts DevTools Settings Preferences

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Make sure you have the latest values in your gradle files. As of this writing:

  • buildToolsVersion "21.1.2"

  • dependencies { classpath 'com.android.tools.build:gradle:1.1.0' }

How to do a background for a label will be without color?

If you picture box in the background then use this:

label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent;

Put this code below InitializeComponent(); or in Form_Load Method.

Ref: https://www.c-sharpcorner.com/blogs/how-to-make-a-transparent-label-over-a-picturebox1

Can I set enum start value in Java?

Java enums are not like C or C++ enums, which are really just labels for integers.

Java enums are implemented more like classes - and they can even have multiple attributes.

public enum Ids {
    OPEN(100), CLOSE(200);

    private final int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
}

The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.

See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.

Only mkdir if it does not exist

Use mkdir's -p option, but note that it has another effect as well.

 -p      Create intermediate directories as required.  If this option is not specified, the full path prefix of each oper-
         and must already exist.  On the other hand, with this option specified, no error will be reported if a directory
         given as an operand already exists.  Intermediate directories are created with permission bits of rwxrwxrwx
         (0777) as modified by the current umask, plus write and search permission for the owner.

How to read values from properties file?

You need to put a PropertyPlaceholderConfigurer bean in your application context and set its location property.

See details here : http://www.zparacha.com/how-to-read-properties-file-in-spring/

You might have to modify your property file a bit for this thing to work.

Hope it helps.

How can I get the day of a specific date with PHP

$date = strtotime('2016-2-3');
$date = date('l', $date);
var_dump($date)

(i added format 'l' so it will return full name of day)

npm install vs. update - what's the difference?

The difference between npm install and npm update handling of package versions specified in package.json:

{
  "name":          "my-project",
  "version":       "1.0",                             // install   update
  "dependencies":  {                                  // ------------------
    "already-installed-versionless-module":  "*",     // ignores   "1.0" -> "1.1"
    "already-installed-semver-module":       "^1.4.3" // ignores   "1.4.3" -> "1.5.2"
    "already-installed-versioned-module":    "3.4.1"  // ignores   ignores
    "not-yet-installed-versionless-module":  "*",     // installs  installs
    "not-yet-installed-semver-module":       "^4.2.1" // installs  installs
    "not-yet-installed-versioned-module":    "2.7.8"  // installs  installs
  }
}

Summary: The only big difference is that an already installed module with fuzzy versioning ...

  • gets ignored by npm install
  • gets updated by npm update

Additionally: install and update by default handle devDependencies differently

  • npm install will install/update devDependencies unless --production flag is added
  • npm update will ignore devDependencies unless --dev flag is added

Why use npm install at all?

Because npm install does more when you look besides handling your dependencies in package.json. As you can see in npm install you can ...

  • manually install node-modules
  • set them as global (which puts them in the shell's PATH) using npm install -g <name>
  • install certain versions described by git tags
  • install from a git url
  • force a reinstall with --force

How to lazy load images in ListView in Android

1. Picasso allows for hassle-free image loading in your application—often in one line of code!

Use Gradle:

implementation 'com.squareup.picasso:picasso:(insert latest version)'

Just one line of code!

Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);

2. Glide An image loading and caching library for Android focused on smooth scrolling

Use Gradle:

repositories {
  mavenCentral() 
  google()
}

dependencies {
   implementation 'com.github.bumptech.glide:glide:4.11.0'
   annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}

// For a simple view:

  Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);

3. fresco is a powerful system for displaying images in Android applications.Fresco takes care of image loading and display, so you don't have to.

Getting Started with Fresco

How to convert std::string to LPCWSTR in C++ (Unicode)

Thanks for the link to the MSDN article. This is exactly what I was looking for.

std::wstring s2ws(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

std::wstring stemp = s2ws(myString);
LPCWSTR result = stemp.c_str();

How to remove ASP.Net MVC Default HTTP Headers?

I found this configuration in my web.config which was for a New Web Site... created in Visual Studio (as opposed to a New Project...). Since the question states a ASP.NET MVC application, not as relevant, but still an option.

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <clear />
      <remove name="X-Powered-By" />
    </customHeaders>
   </httpProtocol>
</system.webServer>

Update: Also, Troy Hunt has an article titled Shhh… don’t let your response headers talk too loudly with detailed steps on removing these headers as well as a link to his ASafaWeb tool for scanning for them and other security configurations.

Simple JavaScript Checkbox Validation

If your checkbox has an ID of 'checkbox':

 if(document.getElementById('checkbox').checked == true){ // code here }

HTH

Bitbucket git credentials if signed up with Google

Solved:

  • Went on the log-in screen and clicked forgot my password.
  • I entered my Google account email and I received a reset link.
  • As you enter there a new password you'll have bitbucket id and password to use.

Sample:

git clone https://<bitbucket_id>@bitbucket.org/<repo>

SQL select join: is it possible to prefix all columns as 'prefix.*'?

The only database I know that does this is SQLite, depending on the settings you configure with PRAGMA full_column_names and PRAGMA short_column_names. See http://www.sqlite.org/pragma.html

Otherwise all I can recommend is to fetch columns in a result set by ordinal position rather than by column name, if it's too much trouble for you to type the names of the columns in your query.

This is a good example of why it's bad practice to use SELECT * -- because eventually you'll have a need to type out all the column names anyway.

I understand the need to support columns that may change name or position, but using wildcards makes that harder, not easier.

Java/ JUnit - AssertTrue vs AssertFalse

Your first reaction to these methods is quite interesting to me. I will use it in future arguments that both assertTrue and assertFalse are not the most friendly tools. If you would use

assertThat(thisOrThat, is(false));

it is much more readable, and it prints a better error message too.

How to check if a map contains a key in Go?

A two value assignment can be used for this purpose. Please check my sample program below

package main

import (
    "fmt"
)

func main() {
    //creating a map with 3 key-value pairs
    sampleMap := map[string]int{"key1": 100, "key2": 500, "key3": 999}
    //A two value assignment can be used to check existence of a key.
    value, isKeyPresent := sampleMap["key2"]
    //isKeyPresent will be true if key present in sampleMap
    if isKeyPresent {
        //key exist
        fmt.Println("key present, value =  ", value)
    } else {
        //key does not exist
        fmt.Println("key does not exist")
    }
}

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

Some examples with NAs and their removal using apply

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

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

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

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

How to include (source) R script in other scripts

Here is a function I wrote. It wraps the base::source function to store a list of sourced files in a global environment list named sourced. It will only re-source a file if you provide a .force=TRUE argument to the call to source. Its argument signature is otherwise identical to the real source() so you don't need to rewrite your scripts to use this.

warning("overriding source with my own function FYI")
source <- function(path, .force=FALSE, ...) {
  library(tools)
  path <- tryCatch(normalizePath(path), error=function(e) path)
  m<-md5sum(path)

  go<-TRUE
  if (!is.vector(.GlobalEnv$sourced)) {
    .GlobalEnv$sourced <- list()
  }
  if(! is.null(.GlobalEnv$sourced[[path]])) {
    if(m == .GlobalEnv$sourced[[path]]) {
      message(sprintf("Not re-sourcing %s. Override with:\n  source('%s', .force=TRUE)", path, path))
      go<-FALSE
    }
    else {
      message(sprintf('re-sourcing %s as it has changed from: %s to: %s', path, .GlobalEnv$sourced[[path]], m))
      go<-TRUE
    }
  } 
  if(.force) {
    go<-TRUE
    message("  ...forcing.")
  }
  if(go) {
    message(sprintf("sourcing %s", path))
    .GlobalEnv$sourced[path] <- m
    base::source(path, ...)
  }
}

It's pretty chatty (lots of calls to message()) so you can take those lines out if you care. Any advice from veteran R users is appreciated; I'm pretty new to R.

Calling one Bash script from another Script passing it arguments with quotes and spaces

You need to use : "$@" (WITH the quotes) or "${@}" (same, but also telling the shell where the variable name starts and ends).

(and do NOT use : $@, or "$*", or $*).

ex:

#testscript1:
echo "TestScript1 Arguments:"
for an_arg in "$@" ; do
   echo "${an_arg}"
done
echo "nb of args: $#"
./testscript2 "$@"   #invokes testscript2 with the same arguments we received

I'm not sure I understood your other requirement ( you want to invoke './testscript2' in single quotes?) so here are 2 wild guesses (changing the last line above) :

'./testscript2' "$@"  #only makes sense if "/path/to/testscript2" containes spaces?

./testscript2 '"some thing" "another"' "$var" "$var2"  #3 args to testscript2

Please give me the exact thing you are trying to do

edit: after his comment saying he attempts tesscript1 "$1" "$2" "$3" "$4" "$5" "$6" to run : salt 'remote host' cmd.run './testscript2 $1 $2 $3 $4 $5 $6'

You have many levels of intermediate: testscript1 on host 1, needs to run "salt", and give it a string launching "testscrit2" with arguments in quotes...

You could maybe "simplify" by having:

#testscript1

#we receive args, we generate a custom script simulating 'testscript2 "$@"'
theargs="'$1'"
shift
for i in "$@" ; do
   theargs="${theargs} '$i'"
done

salt 'remote host' cmd.run "./testscript2 ${theargs}"

if THAt doesn't work, then instead of running "testscript2 ${theargs}", replace THE LAST LINE above by

echo "./testscript2 ${theargs}" >/tmp/runtestscript2.$$  #generate custom script locally ($$ is current pid in bash/sh/...)
scp /tmp/runtestscript2.$$ user@remotehost:/tmp/runtestscript2.$$ #copy it to remotehost
salt 'remotehost' cmd.run "./runtestscript2.$$" #the args are inside the custom script!
ssh user@remotehost "rm /tmp/runtestscript2.$$" #delete the remote one
rm /tmp/runtestscript2.$$ #and the local one

Sort JavaScript object by key

the best way to do it is

 const object =  Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {})

 //else if its in reverse just do 

 const object = Object.keys(0).reverse ()

You can first convert your almost-array-like object to a real array, and then use .reverse():

Object.assign([], {1:'banana', 2:'apple', 
3:'orange'}).reverse();
// [ "orange", "apple", "banana", <1 empty slot> ]

The empty slot at the end if cause because your first index is 1 instead of 0. You can remove the empty slot with .length-- or .pop().

Alternatively, if you want to borrow .reverse and call it on the same object, it must be a fully-array-like object. That is, it needs a length property:

Array.prototype.reverse.call({1:'banana', 2:'apple', 
3:'orange', length:4});
// {0:"orange", 1:"apple", 3:"banana", length:4}

Note it will return the same fully-array-like object object, so it won't be a real array. You can then use delete to remove the length property.

Error inflating class fragment

I was having the same problem as you are facing. None of the tips on top helped me. Later, I found that all I had to do is fix my imports from:

import android.app.Fragment;

to:

import android.support.v4.app.Fragment;

How to show grep result with complete path or file name

I fall here when I was looking exactly for the same problem and maybe it can help other.

I think the real solution is:

cat *.log | grep -H somethingtosearch

How to use WHERE IN with Doctrine 2

I prefer:

$qb->andWhere($qb->expr()->in('t.user_role_id', [
    User::USER_ROLE_ID_ADVERTISER,
    User::USER_ROLE_ID_MANAGER,
]));

Why my $.ajax showing "preflight is invalid redirect error"?

I had the same problem and it kept me up for days. At the end, I realised that my URL pointing to the app was wrong altogether. example:

URL: 'http://api.example.com/'
URL: 'https://api.example.com/'.

If it's http or https verify.
Check the redirecting URL and make sure it's the same thing you're passing along.

How to make a local variable (inside a function) global

Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:

def foo():
    global bar
    bar = 32

I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.

Dots in URL causes 404 with ASP.NET mvc and IIS

Just add this section to Web.config, and all requests to the route/{*pathInfo} will be handled by the specified handler, even when there are dots in pathInfo. (taken from ServiceStack MVC Host Web.config example and this answer https://stackoverflow.com/a/12151501/801189)

This should work for both IIS 6 & 7. You could assign specific handlers to different paths after the 'route' by modifying path="*" in 'add' elements

  <location path="route">
    <system.web>
      <httpHandlers>
        <add path="*" type="System.Web.Handlers.TransferRequestHandler" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" />
      </httpHandlers>
    </system.web>
    <!-- Required for IIS 7.0 -->
    <system.webServer>
      <modules runAllManagedModulesForAllRequests="true" />
      <validation validateIntegratedModeConfiguration="false" />
      <handlers>
        <add name="ApiURIs-ISAPI-Integrated-4.0" path="*" type="System.Web.Handlers.TransferRequestHandler" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" preCondition="integratedMode,runtimeVersionv4.0" />
      </handlers>
    </system.webServer>
  </location>

Have a variable in images path in Sass?

We can use relative path instead of absolute path:

$assetPath: '~src/assets/images/';
$logo-img: '#{$assetPath}logo.png';
@mixin logo {
  background-image: url(#{$logo-img});
}

.logo {
    max-width: 65px;
    @include logo;
 }

What does collation mean?

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

Collation is the assembly of written information into a standard order. (...) A collation algorithm such as the Unicode collation algorithm defines an order through the process of comparing two given character strings and deciding which should come before the other.

Simple CSS Animation Loop – Fading In & Out "Loading" Text

To make more than one element fade in/out sequentially such as 5 elements fade each 4s,

1- make unique animation for each element with animation-duration equal to [ 4s (duration for each element) * 5 (number of elements) ] = 20s

animation-name: anim1 , anim2, anim3 ... 
animation-duration : 20s, 20s, 20s ... 

2- get animation keyframe for each element.

100% (keyframes percentage) / 5 (elements) = 20% (frame for each element)

3- define starting and ending point for each animation:

each animation has 20% frame length and @keyframes percentage always starts from 0%, so first animation will start from 0% and end in his frame(20%), and each next animation will starts from previous animation ending point and end when it reach his frame (+20% ),

@keyframes animation1 { 0% {}, 20% {}}
@keyframes animation2 { 20% {}, 40% {}}
@keyframes animation3 { 40% {}, 60% {}}
and so on

now we need to make each animation fade in from 0 to 1 opacity and fade out from 1 to 0,

so we will add another 2 points (steps) for each animation after starting and before ending point to handle the full opacity(1)

enter image description here

http://codepen.io/El-Oz/pen/WwPPZQ

.slide1 {
    animation: fadeInOut1 24s ease reverse forwards infinite
}

.slide2 {
    animation: fadeInOut2 24s ease reverse forwards infinite
}

.slide3 {
    animation: fadeInOut3 24s ease reverse forwards infinite
}

.slide4 {
    animation: fadeInOut4 24s ease reverse forwards infinite
}

.slide5 {
    animation: fadeInOut5 24s ease reverse forwards infinite
}

.slide6 {
    animation: fadeInOut6 24s ease reverse forwards infinite
}

@keyframes fadeInOut1 {
    0% { opacity: 0 }
    1% { opacity: 1 }
    14% {opacity: 1 }
    16% { opacity: 0 }
}

@keyframes fadeInOut2 {
    0% { opacity: 0 }
    14% {opacity: 0 }
    16% { opacity: 1 }
    30% { opacity: 1 }
    33% { opacity: 0 }
}

@keyframes fadeInOut3 {
    0% { opacity: 0 }
    30% {opacity: 0 }
    33% {opacity: 1 }
    46% { opacity: 1 }
    48% { opacity: 0 }
}

@keyframes fadeInOut4 {
    0% { opacity: 0 }
    46% { opacity: 0 }
    48% { opacity: 1 }
    64% { opacity: 1 }
    65% { opacity: 0 }
}

@keyframes fadeInOut5 {
    0% { opacity: 0 }
    64% { opacity: 0 }
    66% { opacity: 1 }
    80% { opacity: 1 }
    83% { opacity: 0 }
}

@keyframes fadeInOut6 {
    80% { opacity: 0 }
    83% { opacity: 1 }
    99% { opacity: 1 }
    100% { opacity: 0 }
}

What is the best collation to use for MySQL with PHP?

It is best to use character set utf8mb4 with the collation utf8mb4_unicode_ci.

The character set, utf8, only supports a small amount of UTF-8 code points, about 6% of possible characters. utf8 only supports the Basic Multilingual Plane (BMP). There 16 other planes. Each plane contains 65,536 characters. utf8mb4 supports all 17 planes.

MySQL will truncate 4 byte UTF-8 characters resulting in corrupted data.

The utf8mb4 character set was introduced in MySQL 5.5.3 on 2010-03-24.

Some of the required changes to use the new character set are not trivial:

  • Changes may need to be made in your application database adapter.
  • Changes will need to be made to my.cnf, including setting the character set, the collation and switching innodb_file_format to Barracuda
  • SQL CREATE statements may need to include: ROW_FORMAT=DYNAMIC
    • DYNAMIC is required for indexes on VARCHAR(192) and larger.

NOTE: Switching to Barracuda from Antelope, may require restarting the MySQL service more than once. innodb_file_format_max does not change until after the MySQL service has been restarted to: innodb_file_format = barracuda.

MySQL uses the old Antelope InnoDB file format. Barracuda supports dynamic row formats, which you will need if you do not want to hit the SQL errors for creating indexes and keys after you switch to the charset: utf8mb4

  • #1709 - Index column size too large. The maximum column size is 767 bytes.
  • #1071 - Specified key was too long; max key length is 767 bytes

The following scenario has been tested on MySQL 5.6.17: By default, MySQL is configured like this:

SHOW VARIABLES;

innodb_large_prefix = OFF
innodb_file_format = Antelope

Stop your MySQL service and add the options to your existing my.cnf:

[client]
default-character-set= utf8mb4

[mysqld]
explicit_defaults_for_timestamp = true
innodb_large_prefix = true
innodb_file_format = barracuda
innodb_file_format_max = barracuda
innodb_file_per_table = true

# Character collation
character_set_server=utf8mb4
collation_server=utf8mb4_unicode_ci

Example SQL CREATE statement:

CREATE TABLE Contacts (
 id INT AUTO_INCREMENT NOT NULL,
 ownerId INT DEFAULT NULL,
 created timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
 modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 contact VARCHAR(640) NOT NULL,
 prefix VARCHAR(128) NOT NULL,
 first VARCHAR(128) NOT NULL,
 middle VARCHAR(128) NOT NULL,
 last VARCHAR(128) NOT NULL,
 suffix VARCHAR(128) NOT NULL,
 notes MEDIUMTEXT NOT NULL,
 INDEX IDX_CA367725E05EFD25 (ownerId),
 INDEX created (created),
 INDEX modified_idx (modified),
 INDEX contact_idx (contact),
 PRIMARY KEY(id)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB ROW_FORMAT=DYNAMIC;
  • You can see error #1709 generated for INDEX contact_idx (contact) if ROW_FORMAT=DYNAMIC is removed from the CREATE statement.

NOTE: Changing the index to limit to the first 128 characters on contacteliminates the requirement for using Barracuda with ROW_FORMAT=DYNAMIC

INDEX contact_idx (contact(128)),

Also note: when it says the size of the field is VARCHAR(128), that is not 128 bytes. You can use have 128, 4 byte characters or 128, 1 byte characters.

This INSERT statement should contain the 4 byte 'poo' character in the 2 row:

INSERT INTO `Contacts` (`id`, `ownerId`, `created`, `modified`, `contact`, `prefix`, `first`, `middle`, `last`, `suffix`, `notes`) VALUES
(1, NULL, '0000-00-00 00:00:00', '2014-08-25 03:00:36', '1234567890', '12345678901234567890', '1234567890123456789012345678901234567890', '1234567890123456789012345678901234567890', '12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678', '', ''),
(2, NULL, '0000-00-00 00:00:00', '2014-08-25 03:05:57', 'poo', '12345678901234567890', '', '', '', '', ''),
(3, NULL, '0000-00-00 00:00:00', '2014-08-25 03:05:57', 'poo', '12345678901234567890', '', '', '123', '', '');

You can see the amount of space used by the last column:

mysql> SELECT BIT_LENGTH(`last`), CHAR_LENGTH(`last`) FROM `Contacts`;
+--------------------+---------------------+
| BIT_LENGTH(`last`) | CHAR_LENGTH(`last`) |
+--------------------+---------------------+
|               1024 |                 128 | -- All characters are ASCII
|               4096 |                 128 | -- All characters are 4 bytes
|               4024 |                 128 | -- 3 characters are ASCII, 125 are 4 bytes
+--------------------+---------------------+

In your database adapter, you may want to set the charset and collation for your connection:

SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'

In PHP, this would be set for: \PDO::MYSQL_ATTR_INIT_COMMAND

References:

Cross-browser bookmark/add to favorites JavaScript

jQuery Version

JavaScript (modified from a script I found on someone's site - I just can't find the site again, so I can't give the person credit):

$(document).ready(function() {
  $("#bookmarkme").click(function() {
    if (window.sidebar) { // Mozilla Firefox Bookmark
      window.sidebar.addPanel(location.href,document.title,"");
    } else if(window.external) { // IE Favorite
      window.external.AddFavorite(location.href,document.title); }
    else if(window.opera && window.print) { // Opera Hotlist
      this.title=document.title;
      return true;
    }
  });
});

HTML:

<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>

IE will show an error if you don't run it off a server (it doesn't allow JavaScript bookmarks via JavaScript when viewing it as a file://...).

What is key=lambda

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())

Actually, above codes can be:

>>> sorted(['Some','words','sort','differently'],key=str.lower)

According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

File path issues in R using Windows ("Hex digits in character string" error)

replace all the \ with \\.

it's trying to escape the next character in this case the U so to insert a \ you need to insert an escaped \ which is \\

How to use <md-icon> in Angular Material?

md-icons aren't in the bower release of angular-material yet. I've been using Polymer's icons, they'll probably be the same anyway.

bower install polymer/core-icons

How to change a DIV padding without affecting the width/height ?

Declare this in your CSS and you should be good:

* { 
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
     box-sizing: border-box; 
}

This solution can be implemented without using additional wrappers.

This will force the browser to calculate the width according to the "outer"-width of the div, it means the padding will be subtracted from the width.

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

Other option that we use in our projects in order to be able to set the environment per-site is to add a Parameters.xml file to the project with the following content:

<parameters>
      <parameter name="IIS Web Application Name" defaultValue="MyApp" tags="IisApp" />    
      <parameter name="Environment" description="Environment" tags="">
        <parameterEntry kind="XmlFile" scope="Web.config"  match="/configuration/location/system.webServer/aspNetCore/environmentVariables/environmentVariable[@name='ASPNETCORE_ENVIRONMENT']/@value" />
      </parameter>    
</parameters>

The Build Action for this file is Content and the Copy Action is Copy If Newer so it will be part of the package to deploy.

Then, to deploy the package and set the environment, in the Release, under the "WinRM - IIS Web App Deployment" task (it works just as well when using the "IIS web app deploy" task), we set additional arguments for msdeploy:

-setParam:kind=ProviderPath,scope=contentPath,value="MySite" -setParam:name="Environment",value="Stage"

This way we can have multiple releases, all using the same artifact, but deployed as different environments.

C: printf a float value

printf("%0k.yf" float_variable_name)

Here k is the total number of characters you want to get printed. k = x + 1 + y (+ 1 for the dot) and float_variable_name is the float variable that you want to get printed.

Suppose you want to print x digits before the decimal point and y digits after it. Now, if the number of digits before float_variable_name is less than x, then it will automatically prepend that many zeroes before it.

How to view the Folder and Files in GAC?

You install as assemblies by using:

  • A setup program, that you author for your application.
  • Using the gacutil.exe tool with the -i option from the command line.
  • Dropping the assembly in %windir%\Assembly (only up to .NET 3.5, CLR 2.0)

You view the content of the GAC using:

  • The gacutil.exe tool with the -l option.
  • For .NET 2.0, 3.0 and 3.5 (CLR 2.0) browsing to %windir%\assembly using the Windows Explorer.

Note that the (physical) GAC location has changed for .NET 4.0. It is no longer in %windir%\Assembly, but now in %windir%\Microsoft.NET\assembly. However, you should never write any code that depends on the physical location anyway, because given the tools available that is hardly necessary (some "cool" homegrown system diagnostics tools aside).

Android background music service

I have found two great resources to share, if anyone else come across this thread via Google, this may help them ( 2018 ). One is this video tutorial in which you'll see practically how service works, this is good for starters.

Link :- https://www.youtube.com/watch?v=p2ffzsCqrs8

Other is this website which will really help you with background audio player.

Link :- https://www.dev2qa.com/android-play-audio-file-in-background-service-example/

Good Luck :)

How can I plot separate Pandas DataFrames as subplots?

You can see e.gs. in the documentation demonstrating joris answer. Also from the documentation, you could also set subplots=True and layout=(,) within the pandas plot function:

df.plot(subplots=True, layout=(1,2))

You could also use fig.add_subplot() which takes subplot grid parameters such as 221, 222, 223, 224, etc. as described in the post here. Nice examples of plot on pandas data frame, including subplots, can be seen in this ipython notebook.

Faking an RS232 Serial Port

I use com0com - With Signed Driver, on windows 7 x64 to emulate COM3 AND COM4 as a pair.

Then i use COM Dataport Emulator to recieve from COM4.

Then i open COM3 with the app im developping (c#) and send data to COM3.

The data sent thru COM3 is received by COM4 and shown by 'COM Dataport Emulator' who can also send back a response (not automated).

So with this 2 great programs i managed to emulate Serial RS-232 comunication.

Hope it helps.

Both programs are free!!!!!

Change button background color using swift language

U can also play around the tintcolor and button image to indirectly change the color.

Retrieving parameters from a URL

There is a nice library w3lib.url

from w3lib.url import url_query_parameter
url = "/abc?def=ghi"
print url_query_parameter(url, 'def')
ghi

javascript regex for special characters

There are some issue with above written Regex.

This works perfectly.

^[a-zA-Z\d\-_.,\s]+$

Only allowed special characters are included here and can be extended after comma.

Is mongodb running?

On Ubuntu (doc)

sudo systemctl status mongod

If running

? mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: active (running) since Wed 2020-10-14 14:13:40 UTC; 3s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 1604 (mongod)
     Memory: 210.8M
     CGroup: /system.slice/mongod.service
             +-1604 /usr/bin/mongod --config /etc/mongod.conf

If not running

? mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: inactive (dead)
       Docs: https://docs.mongodb.org/manual

To start mongodb

sudo systemctl start mongod

How can I use pickle to save a dict?

Simple way to dump a Python data (e.g. dictionary) to a pickle file.

import pickle

your_dictionary = {}

pickle.dump(your_dictionary, open('pickle_file_name.p', 'wb'))

PowerShell array initialization

The original example returns an error because the array is created empty, then you try to access the nth element to assign it a value.

The are a number of creative answers here, many I didn't know before reading this post. All are fine for a small array, but as n0rd points out, there are significant differences in performance.

Here I use Measure-Command to find out how long each initialization takes. As you might guess, any approach that uses an explicit PowerShell loop is slower than those that use .Net constructors or PowerShell operators (which would be compiled in IL or native code).

Summary

  • New-Object and @(somevalue)*n are fast (around 20k ticks for 100k elements).
  • Creating an array with the range operator n..m is 10x slower (200k ticks).
  • Using an ArrayList with the Add() method is 1000x slower than the baseline (20M ticks), as is looping through an already-sized array using for() or ForEach-Object (a.k.a. foreach,%).
  • Appending with += is the worst (2M ticks for just 1000 elements).

Overall, I'd say array*n is "best" because:

  • It's fast.
  • You can use any value, not just the default for the type.
  • You can create repeating values (to illustrate, type this at the powershell prompt: (1..10)*10 -join " " or ('one',2,3)*3)
  • Terse syntax.

The only drawback:

  • Non-obvious. If you haven't seen this construct before, it's not apparent what it does.

But keep in mind that for many cases where you would want to initialize the array elements to some value, then a strongly-typed array is exactly what you need. If you're initializing everything to $false, then is the array ever going to hold anything other than $false or $true? If not, then New-Object type[] n is the "best" approach.

Testing

Create and size a default array, then assign values:

PS> Measure-Command -Expression {$a = new-object object[] 100000} | Format-List -Property "Ticks"
Ticks : 20039

PS> Measure-Command -Expression {for($i=0; $i -lt $a.Length;$i++) {$a[$i] = $false}} | Format-List -Property "Ticks"
Ticks : 28866028

Creating an array of Boolean is bit little slower than and array of Object:

PS> Measure-Command -Expression {$a = New-Object bool[] 100000} | Format-List -Property "Ticks"
Ticks : 130968

It's not obvious what this does, the documentation for New-Object just says that the second parameter is an argument list which is passed to the .Net object constructor. In the case of arrays, the parameter evidently is the desired size.

Appending with +=

PS> $a=@()
PS> Measure-Command -Expression { for ($i=0; $i -lt 100000; $i++) {$a+=$false} } | Format-List -Property "Ticks"

I got tired of waiting for that to complete, so ctrl+c then:

PS> $a=@()
PS> Measure-Command -Expression { for ($i=0; $i -lt    100; $i++) {$a+=$false} } | Format-List -Property "Ticks"
Ticks : 147663
PS> $a=@()
PS> Measure-Command -Expression { for ($i=0; $i -lt   1000; $i++) {$a+=$false} } | Format-List -Property "Ticks"
Ticks : 2194398

Just as (6 * 3) is conceptually similar to (6 + 6 + 6), so ($somearray * 3) ought to give the same result as ($somearray + $somearray + $somearray). But with arrays, + is concatenation rather than addition.

If $array+=$element is slow, you might expect $array*$n to also be slow, but it's not:

PS> Measure-Command -Expression { $a = @($false) * 100000 } | Format-List -Property "Ticks"
Ticks : 20131

Just like Java has a StringBuilder class to avoid creating multiple objects when appending, so it seems PowerShell has an ArrayList.

PS> $al = New-Object System.Collections.ArrayList
PS> Measure-Command -Expression { for($i=0; $i -lt 1000; $i++) {$al.Add($false)} } | Format-List -Property "Ticks"
Ticks : 447133
PS> $al = New-Object System.Collections.ArrayList
PS> Measure-Command -Expression { for($i=0; $i -lt 10000; $i++) {$al.Add($false)} } | Format-List -Property "Ticks"
Ticks : 2097498
PS> $al = New-Object System.Collections.ArrayList
PS> Measure-Command -Expression { for($i=0; $i -lt 100000; $i++) {$al.Add($false)} } | Format-List -Property "Ticks"
Ticks : 19866894

Range operator, and Where-Object loop:

PS> Measure-Command -Expression { $a = 1..100000 } | Format-List -Property "Ticks"
Ticks : 239863
Measure-Command -Expression { $a | % {$false} } | Format-List -Property "Ticks"
Ticks : 102298091

Notes:

  • I nulled the variable between each run ($a=$null).
  • Testing was on a tablet with Atom processor; you would probably see faster speeds on other machines. [edit: About twice as fast on a desktop machine.]
  • There was a fair bit of variation when I tried multiple runs. Look for the orders of magnitude rather than exact numbers.
  • Testing was with PowerShell 3.0 in Windows 8.

Acknowledgements

Thanks to @halr9000 for array*n, @Scott Saad and Lee Desmond for New-Object, and @EBGreen for ArrayList.

Thanks to @n0rd for getting me to think about performance.

jQuery - How to dynamically add a validation rule

The documentation says:

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is,

> $("form").validate() is called first.

Did you do that? The error message kind of indicates that you didn't.

How exactly to use Notification.Builder

Self-contained example

Same technique as in this answer but:

  • self-contained: copy paste and it will compile and run
  • with a button for you to generated as many notifications as you like and play with intent and notification IDs

Source:

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main extends Activity {
    private int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Button button = new Button(this);
        button.setText("click me");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Notification notification = new Notification.Builder(Main.this)
                        /* Make app open when you click on the notification. */
                        .setContentIntent(PendingIntent.getActivity(
                                Main.this,
                                Main.this.i,
                                new Intent(Main.this, Main.class),
                                PendingIntent.FLAG_CANCEL_CURRENT))
                        .setContentTitle("title")
                        .setAutoCancel(true)
                        .setContentText(String.format("id = %d", Main.this.i))
                        // Starting on Android 5, only the alpha channel of the image matters.
                        // https://stackoverflow.com/a/35278871/895245
                        // `android.R.drawable` resources all seem suitable.
                        .setSmallIcon(android.R.drawable.star_on)
                        // Color of the background on which the alpha image wil drawn white.
                        .setColor(Color.RED)
                        .build();
                final NotificationManager notificationManager =
                        (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(Main.this.i, notification);
                // If the same ID were used twice, the second notification would replace the first one. 
                //notificationManager.notify(0, notification);
                Main.this.i++;
            }
        });
        this.setContentView(button);
    }
}

Tested in Android 22.

C++ create string of text and variables

See also boost::format:

#include <boost/format.hpp>

std::string var = (boost::format("somtext %s sometext %s") % somevar % somevar).str();

Example using Hyperlink in WPF

Hyperlink is not a control, it is a flow content element, you can only use it in controls which support flow content, like a TextBlock. TextBoxes only have plain text.

How can I undo git reset --hard HEAD~1?

My problem is almost similar. I have uncommitted files before I enter git reset --hard.

Thankfully. I managed to skip all these resources. After I noticed that I can just undo (ctrl-z). I just want to add this to all of the answers above.

Note. Its not possible to ctrl-z unopened files.

Query to count the number of tables I have in MySQL

SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'dbName';

Source

This is mine:

USE databasename; 
SHOW TABLES; 
SELECT FOUND_ROWS();

JavaScript before leaving the page

This what I did to show the confirmation message just when I have unsaved data

window.onbeforeunload = function () {
            if (isDirty) {
                return "There are unsaved data.";
            }
            return undefined;
        }

returning "undefined" will disable the confirmation

Note: returning "null" will not work with IE

Also you can use "undefined" to disable the confirmation

window.onbeforeunload = undefined;

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

Split varchar into separate columns in Oracle

Simple way is to convert into column

SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))

CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);

CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
   RETURN split_tbl
   PIPELINED IS
   l_idx PLS_INTEGER;
   l_list VARCHAR2 (32767) := p_list;
   l_value VARCHAR2 (32767);
BEGIN
   LOOP
      l_idx := INSTR (l_list, p_del);

      IF l_idx > 0 THEN
         PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
         l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
      ELSE
         PIPE ROW (l_list);
         EXIT;
      END IF;
   END LOOP;

   RETURN;
END split;

Check the current number of connections to MongoDb

You can just use

db.serverStatus().connections

Also, this function can help you spot the IP addresses connected to your Mongo DB

db.currentOp(true).inprog.forEach(function(x) { print(x.client) })

no target device found android studio 2.1.1

This happened to me on android studio version 4 after doing an update to the IDE. The "invalidate caches and restart" option fixed it.

Python Git Module experiences?

PTBNL's Answer is quite perfect for me. I make a little more for Windows user.

import time
import subprocess
def gitAdd(fileName, repoDir):
    cmd = 'git add ' + fileName
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    print out,error
    pipe.wait()
    return 

def gitCommit(commitMessage, repoDir):
    cmd = 'git commit -am "%s"'%commitMessage
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    print out,error
    pipe.wait()
    return 
def gitPush(repoDir):
    cmd = 'git push '
    pipe = subprocess.Popen(cmd, shell=True, cwd=repoDir,stdout = subprocess.PIPE,stderr = subprocess.PIPE )
    (out, error) = pipe.communicate()
    pipe.wait()
    return 

temp=time.localtime(time.time())
uploaddate= str(temp[0])+'_'+str(temp[1])+'_'+str(temp[2])+'_'+str(temp[3])+'_'+str(temp[4])

repoDir='d:\\c_Billy\\vfat\\Programming\\Projector\\billyccm' # your git repository , windows your need to use double backslash for right directory.
gitAdd('.',repoDir )
gitCommit(uploaddate, repoDir)
gitPush(repoDir)

How do I verify that a string only contains letters, numbers, underscores and dashes?

There are a variety of ways of achieving this goal, some are clearer than others. For each of my examples, 'True' means that the string passed is valid, 'False' means it contains invalid characters.

First of all, there's the naive approach:

import string
allowed = string.letters + string.digits + '_' + '-'

def check_naive(mystring):
    return all(c in allowed for c in mystring)

Then there's use of a regular expression, you can do this with re.match(). Note that '-' has to be at the end of the [] otherwise it will be used as a 'range' delimiter. Also note the $ which means 'end of string'. Other answers noted in this question use a special character class, '\w', I always prefer using an explicit character class range using [] because it is easier to understand without having to look up a quick reference guide, and easier to special-case.

import re
CHECK_RE = re.compile('[a-zA-Z0-9_-]+$')
def check_re(mystring):
    return CHECK_RE.match(mystring)

Another solution noted that you can do an inverse match with regular expressions, I've included that here now. Note that [^...] inverts the character class because the ^ is used:

CHECK_INV_RE = re.compile('[^a-zA-Z0-9_-]')
def check_inv_re(mystring):
   return not CHECK_INV_RE.search(mystring)

You can also do something tricky with the 'set' object. Have a look at this example, which removes from the original string all the characters that are allowed, leaving us with a set containing either a) nothing, or b) the offending characters from the string:

def check_set(mystring):
    return not set(mystring) - set(allowed)

LINQ Joining in C# with multiple conditions

If you need not equal object condition use cross join sequences:

var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]

Valid characters of a hostname?

A "name" (Net, Host, Gateway, or Domain name) is a text string up to 24 characters drawn from the alphabet (A-Z), digits (0-9), minus sign (-), and period (.). Note that periods are only allowed when they serve to delimit components of "domain style names". (See RFC-921, "Domain Name System Implementation Schedule", for background). No blank or space characters are permitted as part of a name. No distinction is made between upper and lower case. The first character must be an alpha character. The last character must not be a minus sign or period. A host which serves as a GATEWAY should have "-GATEWAY" or "-GW" as part of its name. Hosts which do not serve as Internet gateways should not use "-GATEWAY" and "-GW" as part of their names. A host which is a TAC should have "-TAC" as the last part of its host name, if it is a DoD host. Single character names or nicknames are not allowed.

This is provided in http://support.microsoft.com/kb/149044

Java Multithreading concept and join() method

The JVM and the underlying OS have considerable freedom when scheduling things. The fact that you get all the way to "Waiting for threads to finish" before you see the output from individual threads may simply mean that thread start-up takes a bit longer (i.e. it takes some time between the moment when a thread becomes "alive" and when the run() method actually starts executing). You could conceivably see thread output sooner but it's not guaranteed either way.

As for join(), it only guarantees that whatever is after it will only happen once the thread you are joining is done. So when you have three join() calls in a row it doesn't mean the threads should end in a particular order. It simply means that you will wait for ob1 first. Once ob1 finishes, ob2 and ob3 may be still running or they may already be finished. If they are finished, your other join() calls will return immediately.

synchronized is used specifically when multiple threads access the same object and make changes to it. A synchronized block is guaranteed never to be executed by two threads simultaneously - i.e. the thread that executes it has the synchronized object all to itself.

Insert data into table with result from another select query

If table_2 is empty, then try the following insert statement:

insert into table_2 (itemid,location1) 
select itemid,quantity from table_1 where locationid=1

If table_2 already contains the itemid values, then try this update statement:

update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

How to create timer events using C++ 11?

Made a simple implementation of what I believe to be what you want to achieve. You can use the class later with the following arguments:

  • int (milliseconds to wait until to run the code)
  • bool (if true it returns instantly and runs the code after specified time on another thread)
  • variable arguments (exactly what you'd feed to std::bind)

You can change std::chrono::milliseconds to std::chrono::nanoseconds or microseconds for even higher precision and add a second int and a for loop to specify for how many times to run the code.

Here you go, enjoy:

#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

class later
{
public:
    template <class callable, class... arguments>
    later(int after, bool async, callable&& f, arguments&&... args)
    {
        std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));

        if (async)
        {
            std::thread([after, task]() {
                std::this_thread::sleep_for(std::chrono::milliseconds(after));
                task();
            }).detach();
        }
        else
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(after));
            task();
        }
    }

};

void test1(void)
{
    return;
}

void test2(int a)
{
    printf("%i\n", a);
    return;
}

int main()
{
    later later_test1(1000, false, &test1);
    later later_test2(1000, false, &test2, 101);

    return 0;
}

Outputs after two seconds:

101

How to fix syntax error, unexpected T_IF error in php?

Here is the issue

  $total_result = $result->num_rows;

try this

<?php
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
    if ($result->num_rows > 0)
    {
        $total_result = $result->num_rows;
        $total_pages = ceil($total_result / $per_page);

        if(isset($_GET['page']) && is_numeric($_GET['page']))
        {
            $show_page = $_GET['page'];

            if ($show_page > 0 && $show_page <= $total_pages)
            {
                $start = ($show_page - 1) * $per_page;
                $end = $start + $per_page;
            }
            else
            {
                $start = 0;
                $end = $per_page;
            }               

        }
        else
        {
            $start = 0;
            $end = $per_page;
        }


        //display paginations
        echo "<p> View pages: ";
        for ($i=1; $i < $total_pages; $i++)
        { 
            if (isset($_GET['page']) && $_GET['page'] == $i)
            {
                echo  $i . " ";
            }
            else
            {
                echo "<a href='view-pag.php?$i'>" . $i . "</a> | ";
            }

        }
        echo "</p>";

    }
    else
    {
        echo "No result to display.";
    }

}
else
{
    echo "Error: " . $mysqli->error;
}


?>

Convenient C++ struct initialisation

Many compilers' C++ frontends (including GCC and clang) understand C initializer syntax. If you can, simply use that method.

How do I escape a string inside JavaScript code inside an onClick handler?

Any good templating engine worth its salt will have an "escape quotes" function. Ours (also home-grown, where I work) also has a function to escape quotes for javascript. In both cases, the template variable is then just appended with _esc or _js_esc, depending on which you want. You should never output user-generated content to a browser that hasn't been escaped, IMHO.

Is right click a Javascript event?

Ya, though w3c says the right click can be detected by the click event, onClick is not triggered through right click in usual browsers.

In fact, right click only trigger onMouseDown onMouseUp and onContextMenu.

Thus, you can regard "onContextMenu" as the right click event. It's an HTML5.0 standard.

Can I use jQuery with Node.js?

You have to get the window using the new JSDOM API.

const jsdom = require("jsdom");
const { window } = new jsdom.JSDOM(`...`);
var $ = require("jquery")(window);

How do I rename both a Git local and remote branch name?

It seems that there is a direct way:

If you really just want to rename branches remotely (without renaming any local branches at the same time) you can do this with a single command like

git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>

Renaming branches remotely in Git

See the original answer for more detail.

Is there any native DLL export functions viewer?

DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.

This utility displays the list of all exported functions and their virtual memory addresses for the specified DLL files. You can easily copy the memory address of the desired function, paste it into your debugger, and set a breakpoint for this memory address. When this function is called, the debugger will stop in the beginning of this function.

enter image description here

Object of custom type as dictionary key

You need to add 2 methods, note __hash__ and __eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

Extract csv file specific columns to list in Python

A standard-lib version (no pandas)

This assumes that the first row of the csv is the headers

import csv

# open the file in universal line ending mode 
with open('test.csv', 'rU') as infile:
  # read the file as a dictionary for each row ({header : value})
  reader = csv.DictReader(infile)
  data = {}
  for row in reader:
    for header, value in row.items():
      try:
        data[header].append(value)
      except KeyError:
        data[header] = [value]

# extract the variables you want
names = data['name']
latitude = data['latitude']
longitude = data['longitude']

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

If you are using vscode I would recommend you to click the option at the bottom-right of the window and set it to LF from CRLF..this fixed my errors

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

How to set a default value with Html.TextBoxFor?

If you have a partial page form for both editing and adding, then the trick I use to default value to 0 is to do the following:

@Html.TextBox("Age", Model.Age ?? 0)

That way it will be 0 if unset or the actual age if it exists.

Select Rows with id having even number

Try this:

SELECT DISTINCT city FROM STATION WHERE ID%2=0 ORDER BY CITY;

Materialize CSS - Select Doesn't Seem to Render

Only this worked for me:

$(document).ready(function(){
    $('select').not('.disabled').formSelect();
});

SSH configuration: override the default username

You can use a shortcut. Create a .bashrc file in your home directory. In there, you can add the following:

alias sshb="ssh buck@host"

To make the alias available in your terminal, you can either close and open your terminal, or run

source ~/.bashrc

Then you can connect by just typing in:

sshb

check output from CalledProcessError

If you want to get stdout and stderr back (including extracting it from the CalledProcessError in the event that one occurs), use the following:

import subprocess

command = ["ls", "-l"]
try:
    output = subprocess.check_output(command, stderr=subprocess.STDOUT).decode()
    success = True 
except subprocess.CalledProcessError as e:
    output = e.output.decode()
    success = False

print(output)

This is Python 2 and 3 compatible.

If your command is a string rather than an array, prefix this with:

import shlex
command = shlex.split(command)

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

Convert a char to upper case using regular expressions (EditPad Pro)

You can do this in jEdit, by using the "Return value of a BeanShell snippet" option in jEdit's find and replace dialog. Just search for " [a-z]" and replace it by " _0.toUpperCase()" (without quotes)

chart.js load totally new data

I had loads of trouble with this too. I have data and labels in separate arrays then I reinitialise the chart data. I added the line.destroy(); as suggested above which has done the trick

_x000D_
_x000D_
var ctx = document.getElementById("canvas").getContext("2d");_x000D_
if(window.myLine){_x000D_
 window.myLine.destroy();_x000D_
}_x000D_
window.myLine = new Chart(ctx).Line(lineChartData, {_x000D_
  etc_x000D_
  etc
_x000D_
_x000D_
_x000D_

Cassandra cqlsh - connection refused

For me it turned out that the service wasn't running at all. Check with

service cassandra status

If you got the same error as I got, or another type, then messing around with IP addresses won't solve your problem at all.

The error I got:

cassandra dead but pid file exists

Edit: This was the solution for my problem: https://stackoverflow.com/a/46743119/3881406

Passing dynamic javascript values using Url.action()

This answer might not be 100% relevant to the question. But it does address the problem. I found this simple way of achieving this requirement. Code goes below:

<a href="@Url.Action("Display", "Customer")?custId={{cust.Id}}"></a>

In the above example {{cust.Id}} is an AngularJS variable. However one can replace it with a JavaScript variable.

I haven't tried passing multiple variables using this method but I'm hopeful that also can be appended to the Url if required.

How to check if a database exists in SQL Server?

I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.

CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
RETURNS bit
AS
BEGIN
    declare @result bit = 0 
    SELECT @result = CAST(
        CASE WHEN db_id(@dbname) is not null THEN 1 
        ELSE 0 
        END 
    AS BIT)
    return @result
END
GO

Now you can use it like this:

select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0

Convert seconds value to hours minutes seconds?

This is my simple solution:

String secToTime(int sec) {
    int seconds = sec % 60;
    int minutes = sec / 60;
    if (minutes >= 60) {
        int hours = minutes / 60;
        minutes %= 60;
        if( hours >= 24) {
            int days = hours / 24;
            return String.format("%d days %02d:%02d:%02d", days,hours%24, minutes, seconds);
        }
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
    return String.format("00:%02d:%02d", minutes, seconds);
}

Test Results:

Result: 00:00:36 - 36
Result: 01:00:07 - 3607
Result: 6313 days 12:39:05 - 545488745

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

In my codebehind i created a checkboxlist from sql db in my Page_Load event and in my button_click event did all the get values from checkboxlist etc.

So when i checked some checkboxes and then clicked my button the first thing that happend was that my page_load event recreated the checkboxlist thus not having any boxes checked when it ran my get checkbox values... I've missed to add in the page_load event the if (!this.IsPostBack)

protected void Page_Load(object sender, EventArgs e)
{
   if (!this.IsPostBack)
   {
      // db query and create checkboxlist and other
      SqlConnection dbConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
      string query;
      try
      {
        query = "SELECT [name], [mail] FROM [users]";
        dbConn.Open();
        SqlDataAdapter da = new SqlDataAdapter(query, dbConn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count != 0)
        {
          checkboxlist1.DataSource = ds;
          checkboxlist1.DataTextField = "name";
          checkboxlist1.DataValueField = "mail";
          checkboxlist1.DataBind();
        }
        else
        {
          Response.Write("No Results found");
        }
       }
       catch (Exception ex)
       {
          Response.Write("<br>" + ex);
       }
       finally
       {
          dbConn.Close();
       }
   }
}

protected void btnSend_Click(object sender, EventArgs e)
 {
   string strChkBox = string.Empty;
   foreach (ListItem li in checkboxlist1.Value)
    {
      if (li.Selected == true)
       {
         strChkBox += li.Value + "; ";    
         // use only   strChkBox += li + ", ";   if you want the name of each checkbox checked rather then it's value.
       }
    }
   Response.Write(strChkBox);
 }

And the output was as expected, a semicolon separeted list for me to use in a mailsend function:

    [email protected]; [email protected]; [email protected]

A long answer to a small problem. Please note that i'm far from an expert at this and know that there are better solutions then this but it might help out for some.

How can I store and retrieve images from a MySQL database using PHP?

First you create a MySQL table to store images, like for example:

create table testblob (
    image_id        tinyint(3)  not null default '0',
    image_type      varchar(25) not null default '',
    image           blob        not null,
    image_size      varchar(25) not null default '',
    image_ctgy      varchar(25) not null default '',
    image_name      varchar(50) not null default ''
);

Then you can write an image to the database like:

/***
 * All of the below MySQL_ commands can be easily
 * translated to MySQLi_ with the additions as commented
 ***/ 
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli 
// $link = mysqli_connect("localhost", $username, $password,$dbname); 
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    /***
     * For all mysqli_ functions below, the syntax is:
     * mysqli_whartever($link, $functionContents); 
     ***/
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);

You can display an image from the database in a web page with:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);

Spring Boot default H2 jdbc connection (and H2 console)

Use jdbc:h2:mem:testdb as your path when logging into the H2 console.

Obviously if you have altered Spring Boot properties your datasource may be different, but it seems like you're struggling with how to find the default. That's all there is to it! You'll see your schema after logging in to H2.

Python function global variables?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

Set colspan dynamically with jquery

td.setAttribute('rowspan',x);

Windows 10 SSH keys

Create private/public key:

  1. Open up terminal (git bash, PowerShell, cmd.exe etc.)
  2. Type in ssh-keygen
  3. Press enter for default file save (~/.ssh/id_rsa)
  4. Press enter for default passphrase (no passphrase)
  5. Press enter again
  6. Look at the output and make sure that the RSA is 3072 or above

You have now created a private/public key pair.

For GIT the key must have a strength of 2048, must be located in the users .ssh directory and be called id_rsa and id_rsa.pub. When pasting the keys anywhere make sure to use a program that does not add new lines like VIM.

How to put scroll bar only for modal-body?

In your modal body you have to set a height, it can be % vh or calc:

modal-body {
    height: 80vh;
    overflow-x: auto;
}

or

modal-body {
    height: calc(100vh - 5em);
    overflow-x: auto;
}

In my case look like: enter image description here

Using ping in c#

private async void Ping_Click(object sender, RoutedEventArgs e)
{
    Ping pingSender = new Ping();
    string host = @"stackoverflow.com";
    await Task.Run(() =>{
         PingReply reply = pingSender.Send(host);
         if (reply.Status == IPStatus.Success)
         {
            Console.WriteLine("Address: {0}", reply.Address.ToString());
            Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
            Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
            Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
            Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
         }
         else
         {
            Console.WriteLine("Address: {0}", reply.Status);
         }
   });           
}

How does DHT in torrents work?

DHT nodes have unique identifiers, termed, Node ID. Node IDs are chosen at random from the same 160-bit space as BitTorrent info-hashes. Closeness is measured by comparing Node ID's routing tables, the closer the Node, the more detailed, resulting in optimal

What then makes them more optimal than it's predecessor "Kademlia" which used simple unsigned integers: distance(A,B) = |A xor B| Smaller values are closer. XOR. Besides not being secure, its logic was flawed.

If your client supports DHT, there are 8-bytes reserved in which contains 0x09 followed by a 2-byte payload with the UDP Port and DHT node. If the handshake is successful the above will continue.

How to color the Git console?

Another way is to edit the .gitconfig (create one if not exist), for instance:

vim ~/.gitconfig

and then add:

[color]
  diff = auto
  status = auto
  branch = auto

Java Regex to Validate Full Name allow only Spaces and Letters

Regex pattern for matching only alphabets and white spaces:

String regexUserName = "^[A-Za-z\\s]+$";

Using CSS in Laravel views?

You can simply put all the files in its specified folder in public like


public/css
public/js
public/images


Then just call the files as in normal html like
<link href="css/file.css" rel="stylesheet" type="text/css">

It works just fine in any version of Laravel

Will iOS launch my app into the background if it was force-quit by the user?

The answer is YES, but shouldn't use 'Background Fetch' or 'Remote notification'. PushKit is the answer you desire.

In summary, PushKit, the new framework in ios 8, is the new push notification mechanism which can silently launch your app into the background with no visual alert prompt even your app was killed by swiping out from app switcher, amazingly you even cannot see it from app switcher.

PushKit reference from Apple:

The PushKit framework provides the classes for your iOS apps to receive pushes from remote servers. Pushes can be of one of two types: standard and VoIP. Standard pushes can deliver notifications just as in previous versions of iOS. VoIP pushes provide additional functionality on top of the standard push that is needed to VoIP apps to perform on-demand processing of the push before displaying a notification to the user.

To deploy this new feature, please refer to this tutorial: https://zeropush.com/guide/guide-to-pushkit-and-voip - I've tested it on my device and it works as expected.

How to improve performance of ngRepeat over a huge dataset (angular.js)?

Beside all the above hints like track by and smaller loops, this one also helped me a lot

<span ng-bind="::stock.name"></span>

this piece of code would print the name once it has been loaded, and stop watching it after that. Similarly, for ng-repeats, it could be used as

<div ng-repeat="stock in ::ctrl.stocks">{{::stock.name}}</div>

however it only works for AngularJS version 1.3 and higher. From http://www.befundoo.com/blog/optimizing-ng-repeat-in-angularjs/

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

At least in Visual C++: printf (and other ACSII functions): %s represents an ASCII string %S is a Unicode string wprintf (and other Unicode functions): %s is a Unicode string %S is an ASCII string

As far as no compiler warnings, printf uses a variable argument list, with only the first argument able to be type checked. The compiler is not designed to parse the format string and type check the parameters that match. In cases of functions like printf, that is up to the programmer

Current Subversion revision command

Nobody mention for Windows world SubWCRev, which, properly used, can substitute needed data into the needed places automagically, if script call SubWCRev in form SubWCRev WC_PATH TPL-FILE READY-FILE

Sample of my post-commit hook (part of)

SubWCRev.exe CustomLocations Builder.tpl  z:\Builder.bat
...
call z:\Builder.bat

where my Builder.tpl is

svn.exe export trunk z:\trunk$WCDATE=%Y%m%d$-r$WCREV$

as result, I have every time bat-file with variable part - name of dir - which corresponds to the metadata of Working Copy

Only allow Numbers in input Tag without Javascript

Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.

So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title attribute).

There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.

On the other hand, in HTML 5 you have two options:

  • input of type number:

    <input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
    

    – only validates the range – if user enters a non-number, an empty value is submitted
    – the field visual is enhanced with increment / decrement controls (browser dependent)

  • the pattern attribute:

    <input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
    <input type="text" pattern="\d{3}" title="Format: 3 digits" />
    

    – this gives you a full contorl over the format (anything you can specify by regular expression)
    – no visual difference / enhancement

But here you still rely on browser capabilities, so do a server-side validation in either case.

Java resource as file

I had the same problem and was able to use the following:

// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()

How to parse JSON boolean value?

You can cast this value to a Boolean in a very simple manner: by comparing it with integer value 1, like this:

boolean multipleContacts = new Integer(1).equals(jsonObject.get("MultipleContacts"))

If it is a String, you could do this:

boolean multipleContacts = "1".equals(jsonObject.get("MultipleContacts"))

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

Note that if you use SELECT FOR UPDATE to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE, then to check the affected row count.

add below line to my.cnf file

innodb_locks_unsafe_for_binlog = 1

#

1 - ON
0 - OFF

#

How to convert a Collection to List?

List list = new ArrayList(coll);
Collections.sort(list);

As Erel Segal Halevi says below, if coll is already a list, you can skip step one. But that would depend on the internals of TreeBidiMap.

List list;
if (coll instanceof List)
  list = (List)coll;
else
  list = new ArrayList(coll);

Batch file to map a drive when the folder name contains spaces

net use f: \\\VFServer"\HQ Publications" /persistent:yes

Note that the first quotation mark goes before the leading \ and the second goes after the end of the folder name.

Access denied for root user in MySQL command-line

You mustn't have a space character between -u and the username:

mysql -uroot -p
# or
mysql --user=root --password

How do I use method overloading in Python?

I think the word you're looking for is "overloading". There isn't any method overloading in Python. You can however use default arguments, as follows.

def stackoverflow(self, i=None):
    if i != None:
        print 'second method', i
    else:
        print 'first method'

When you pass it an argument, it will follow the logic of the first condition and execute the first print statement. When you pass it no arguments, it will go into the else condition and execute the second print statement.

Can I set the height of a div based on a percentage-based width?

This can actually be done with only CSS, but the content inside the div must be absolutely positioned. The key is to use padding as a percentage and the box-sizing: border-box CSS attribute:

_x000D_
_x000D_
div {_x000D_
  border: 1px solid red;_x000D_
  width: 40%;_x000D_
  padding: 40%;_x000D_
  box-sizing: border-box;_x000D_
  position: relative;_x000D_
}_x000D_
p {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}
_x000D_
<div>_x000D_
  <p>Some unnecessary content.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Adjust percentages to your liking. Here is a JSFiddle

Can't connect to MySQL server error 111

It probably means that your MySQL server is only listening the localhost interface.

If you have lines like this :

bind-address = 127.0.0.1

In your my.cnf configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.

sudo service mysql restart

Of course, to do this, you must be the administrator of the server.

Android: How to set password property in an edit text?

The only way that worked for me using code (not XML) is this one:

etPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());

onClick function of an input type="button" not working

When I try:

<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!"  />

It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.

Pls try:

<script type="text/javascript">
    function moreFields() {
        alert("The text will be show");
    }
</script>

<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!"  />

Hope it helped.

Differences between key, superkey, minimal superkey, candidate key and primary key

Superkey

A superkey is a combination of attributes that can be uniquely used to identify a 
database record. A table might have many superkeys.Candidate keys are a special subset
of superkeys that do not have any extraneous information in them.

Examples: Imagine a table with the fields <Name>, <Age>, <SSN> and <Phone Extension>.
This table has many possible superkeys. Three of these are <SSN>, <Phone Extension, Name>
and <SSN, Name>.Of those listed, only <SSN> is a **candidate key**, as the others
contain information not necessary to uniquely identify records.

Show a div with Fancybox

For users coming back to this post long after the initial answer was accepted, it may pay off to note that now you can use

data-fancybox-href="#" 

on any element (since data is an HTML-5 accepted attribute) to have the fancybox work on say an input form if for some reason you can't use the options to initiate for some reason (like say you have multiple elements on the page that use fancybox and they all share a similar class you call fancybox on).

Calling a parent window function from an iframe

You can use

window.top

see the following.

<head>
    <script>
    function abc() {
        alert("sss");
    }
    </script>
</head>
<body>
    <iframe id="myFrame">
        <a onclick="window.top.abc();" href="#">Click Me</a>
    </iframe>
</body>

phpexcel to download

Use this call

$objWriter->save('php://output');

To output the XLS sheet to the page you are on, just make sure that the page you are on has no other echo's,print's, outputs.

Transposing a 2D-array in JavaScript

Just another variation using Array.map. Using indexes allows to transpose matrices where M != N:

// Get just the first row to iterate columns first
var t = matrix[0].map(function (col, c) {
    // For each column, iterate all rows
    return matrix.map(function (row, r) { 
        return matrix[r][c]; 
    }); 
});

All there is to transposing is mapping the elements column-first, and then by row.

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

This works for me on a similar issue where I failed to delete the user due to the reference. Thank you

@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH})

Numbering rows within groups in a data frame

Here is a small improvement trick that allows sort 'val' inside the groups:

# 1. Data set
set.seed(100)
df <- data.frame(
  cat = c(rep("aaa", 5), rep("ccc", 5), rep("bbb", 5)), 
  val = runif(15))             

# 2. 'dplyr' approach
df %>% 
  arrange(cat, val) %>% 
  group_by(cat) %>% 
  mutate(id = row_number())

Necessary to add link tag for favicon.ico?

Update Oct 2020:

So if you are on this page scratching your head why my favicon is not working , then read along. I tried all the things (which I supposedly thought I was doing right) yet favicon was not showing up on browser tabs.

Here is one line simple cracker code that worked flawlessly:

<link rel="icon" href="https://abcde.neocities.org/bla123.jpg" size="16x16" type="image/jpg">

enter image description here

Notes:

  1. Put the image in the ROOT folder ( In one of my unsuccessful attempts , I was not using root dir)
  2. Use direct favicon url link ( instead of href="images/bla123.jpg").
  3. I placed this tag just below the <title> tag in the <Header>
  4. I made the favicon size 64x64 px and size was 2.16 KB

I tested it on Firefox, Chrome, Edge, and opera. OS: Win 10, Mac OSX, ios and Android .Also I did not experience any cashing issues, worked pretty much as soon as I refreshed the page.

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

What does DIM stand for in Visual Basic and BASIC?

It's short for Dimension, as it was originally used in BASIC to specify the size of arrays.

DIM — (short for dimension) define the size of arrays

Ref: http://en.wikipedia.org/wiki/Dartmouth_BASIC

A part of the original BASIC compiler source code, where it would jump when finding a DIM command, in which you can clearly see the original intention for the keyword:

DIM    LDA XR01             BACK OFF OBJECT POINTER
       SUB N3
       STA RX01
       LDA L        2       GET VARIABLE TO BE DIMENSIONED
       STA 3
       LDA S        3
       CAB N36              CHECK FOR $ ARRAY
       BRU *+7              NOT $
       ...

Ref: http://dtss.dartmouth.edu/scans/BASIC/BASIC%20Compiler.pdf

Later on it came to be used to declare all kinds of variables, when the possibility to specify the type for variables was added in more recent implementations.

Defining arrays in Google Scripts

Try this

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  //var values = rows.getValues();

  var Names = sheet.getRange("A2:A7");
  var Name = [
    Names.getCell(1, 1).getValue(),
    Names.getCell(2, 1).getValue(),
    .....
    Names.getCell(5, 1).getValue()]

You can define arrays simply as follows, instead of allocating and then assigning.

var arr = [1,2,3,5]

Your initial error was because of the following line, and ones like it

var Name[0] = Name_cell.getValue(); 

Since Name is already defined and you are assigning the values to its elements, you should skip the var, so just

Name[0] = Name_cell.getValue();

Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.

How to get the CPU Usage in C#?

CMS has it right, but also if you use the server explorer in visual studio and play around with the performance counter tab then you can figure out how to get lots of useful metrics.

Compare two date formats in javascript/jquery

It's quite simple:

if(new Date(fit_start_time) <= new Date(fit_end_time))
{//compare end <=, not >=
    //your code here
}

Comparing 2 Date instances will work just fine. It'll just call valueOf implicitly, coercing the Date instances to integers, which can be compared using all comparison operators. Well, to be 100% accurate: the Date instances will be coerced to the Number type, since JS doesn't know of integers or floats, they're all signed 64bit IEEE 754 double precision floating point numbers.

Using variables inside a bash heredoc

Don't use quotes with <<EOF:

var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF

Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).

Is there a MessageBox equivalent in WPF?

The MessageBox in the Extended WPF Toolkit is very nice. It's at Microsoft.Windows.Controls.MessageBox after referencing the toolkit DLL. Of course this was released Aug 9 2011 so it would not have been an option for you originally. It can be found at Github for everyone out there looking around.

How can I get color-int from color resource?

Most Recent working method:

getColor(R.color.snackBarAction)

What is Ad Hoc Query?

In Sql Server "Ad Hoc Query" is also used for Ad Hoc Distributed Queries. These are ad hoc queries on an other server via OpenRowset or OpenDatasource. Ad Hoc Distributed Queries are only allowed after configuring so. This is a Server configuration option.

Convert DataTable to List<T>

Create a list with type<DataRow> by extend the datatable with AsEnumerable call.

var mylist = dt.AsEnumerable().ToList();

Cheers!! Happy Coding

Eclipse cannot load SWT libraries

SOLVED:

Because I had installed the Oracle Java 7 it had changed the default Java to Oracle Java 7, however it needed to be the Open JDK.

To fix, open up terminal and type

sudo update-alternatives --config java

This brings up a list of the different types of Java. Simply select the Open JDK.

React js onClick can't pass value to method

There are 3 ways to handle this :-

  1. Bind the method in constructor as :-

    export class HeaderRows extends Component {
       constructor() {
           super();
           this.handleSort = this.handleSort.bind(this);
       }
    }
    
  2. Use the arrow function while creating it as :-

    handleSort = () => {
        // some text here
    }
    
  3. Third way is this :-

    <th value={column} onClick={() => that.handleSort} >{column}</th>
    

jQuery: value.attr is not a function

You can also use jQuery('.class-name').attr("href"), in my case it works better.

Here more information: "jQuery(...)" instead of "$(...)"

sort dict by value python

You could created sorted list from Values and rebuild the dictionary:

myDictionary={"two":"2", "one":"1", "five":"5", "1four":"4"}

newDictionary={}

sortedList=sorted(myDictionary.values())

for sortedKey in sortedList:
    for key, value in myDictionary.items():
        if value==sortedKey:
            newDictionary[key]=value

Output: newDictionary={'one': '1', 'two': '2', '1four': '4', 'five': '5'}

Is JavaScript guaranteed to be single-threaded?

I'd say yes - because virtually all existing (at least all non-trivial) javascript code would break if a browser's javascript engine were to run it asynchronously.

Add to that the fact that HTML5 already specifies Web Workers (an explicit, standardized API for multi-threading javascript code) introducing multi-threading into the basic Javascript would be mostly pointless.

(Note to others commenters: Even though setTimeout/setInterval, HTTP-request onload events (XHR), and UI events (click, focus, etc.) provide a crude impression of multi-threadedness - they are still all executed along a single timeline - one at a time - so even if we don't know their execution order beforehand, there's no need to worry about external conditions changing during the execution of an event handler, timed function or XHR callback.)

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Using ensure_ascii=False in json.dumps is the right direction to solve this problem, as pointed out by Martijn. However, this may raise an exception:

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

You need extra settings in either site.py or sitecustomize.py to set your sys.getdefaultencoding() correct. site.py is under lib/python2.7/ and sitecustomize.py is under lib/python2.7/site-packages.

If you want to use site.py, under def setencoding(): change the first if 0: to if 1: so that python will use your operation system's locale.

If you prefer to use sitecustomize.py, which may not exist if you haven't created it. simply put these lines:

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

Then you can do some Chinese json output in utf-8 format, such as:

name = {"last_name": u"?"}
json.dumps(name, ensure_ascii=False)

You will get an utf-8 encoded string, rather than \u escaped json string.

To verify your default encoding:

print sys.getdefaultencoding()

You should get "utf-8" or "UTF-8" to verify your site.py or sitecustomize.py settings.

Please note that you could not do sys.setdefaultencoding("utf-8") at interactive python console.

Comparing two hashmaps for equal values and same key sets?

Compare every key in mapB against the counterpart in mapA. Then check if there is any key in mapA not existing in mapB

public boolean mapsAreEqual(Map<String, String> mapA, Map<String, String> mapB) {

    try{
        for (String k : mapB.keySet())
        {
            if (!mapA.get(k).equals(mapB.get(k))) {
                return false;
            }
        } 
        for (String y : mapA.keySet())
        {
            if (!mapB.containsKey(y)) {
                return false;
            }
        } 
    } catch (NullPointerException np) {
        return false;
    }
    return true;
}

How often should Oracle database statistics be run?

Make sure to balance the risk that fresh statistics cause undesirable changes to query plans against the risk that stale statistics can themselves cause query plans to change.

Imagine you have a bug database with a table ISSUE and a column CREATE_DATE where the values in the column increase more or less monotonically. Now, assume that there is a histogram on this column that tells Oracle that the values for this column are uniformly distributed between January 1, 2008 and September 17, 2008. This makes it possible for the optimizer to reasonably estimate the number of rows that would be returned if you were looking for all issues created last week (i.e. September 7 - 13). If the application continues to be used and the statistics are never updated, though, this histogram will be less and less accurate. So the optimizer will expect queries for "issues created last week" to be less and less accurate over time and may eventually cause Oracle to change the query plan negatively.

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

read.table wants to return a data.frame, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE ) to fill in the blanks.

e.g.

read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
#        V1       V2       V3
#1 Element1 Element2         
#2 Element5 Element6 Element7

A note on whether or not to set header = FALSE... read.table tries to automatically determine if you have a header row thus:

header is set to TRUE if and only if the first row contains one fewer field than the number of columns

Facebook share button and custom text

You can customize Facebook share dialog box by using asynchronous JavaScript SDK provided by Facebook and setting up its parameter values

Have a look at the following code:

<script type="text/javascript">
  $(document).ready(function(){
    $('#share_button').click(function(e){
      e.preventDefault();
      FB.ui(
        {
          method: 'feed',
          name: 'This is the content of the "name" field.',
          link: 'URL which you would like to share ',
          picture: ‘URL of the image which is going to appear as thumbnail image in share dialogbox’,
          caption: 'Caption like which appear as title of the dialog box',
          description: 'Small description of the post',
          message: ''
        }
      );
    });
  });
</script>

Before copying and pasting the below code you must first initialize the SDK and set up jQuery library. Please click here to know a step by step how to set information on the same.

Select elements by attribute

I have created npm package with intended behaviour as described above in question.

Link to [npm] and [github]

Usage is very simple. For example:

<p id="test" class="test">something</p>
$("#test").hasAttr("class")

returns true.

Works with camelcase too.

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

How to pass a callback as a parameter into another function

Example for CoffeeScript:

test = (str, callback) ->
  data = "Input values"
  $.ajax
    type: "post"
    url: "http://www.mydomain.com/ajaxscript"
    data: data
    success: callback

test (data, textStatus, xhr) ->
  alert data + "\t" + textStatus

How do you Programmatically Download a Webpage in Java

Well, you could go with the built-in libraries such as URL and URLConnection, but they don't give very much control.

Personally I'd go with the Apache HTTPClient library.
Edit: HTTPClient has been set to end of life by Apache. The replacement is: HTTP Components

Root password inside a Docker container

To create/change a root password in a running container

docker exec -itu root {containerName} passwd

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

I had the problem under Linux and I needed to install those. I don't know which one actually fixed the problem, but that error was gone after that:

apt-get install mono-utils mono-runtime-sgen mono-runtime-common \
                mono-runtime-boehm mono-runtime-dbg mono-xbuild

Remove redundant paths from $PATH variable

Assuming your shell is Bash, you can set the path with

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

but like Levon said in another answer, as soon as you terminate the shell the changes will be gone. You probably want to set up your PATH in ~/.bash_profile or ~/.bashrc.

ImportError: cannot import name

When this is in a python console if you update a module to be able to use it through the console does not help reset, you must use a

import importlib

and

importlib.reload (*module*)

likely to solve your problem

How do I get the current location of an iframe?

You can use Ra-Ajax and have an iframe wrapped inside e.g. a Window control. Though in general terms I don't encourage people to use iframes (for anything)

Another alternative is to load the HTML on the server and send it directly into the Window as the content of a Label or something. Check out how this Ajax RSS parser is loading the RSS items in the source which can be downloaded here (Open Source - LGPL)

(Disclaimer; I work with Ra-Ajax...)

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

How to convert ISO8859-15 to UTF8?

I got the same problem, but i find the answer in this page! it works for me, you can try it.

iconv -f cp936 -t utf-8 

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

You can get the script that SSMS provides by doing the following:

  1. Right-click on a database in SSMS and choose delete
  2. In the dialog, check the checkbox for "Close existing connections."
  3. Click the Script button at the top of the dialog.

The script will look something like this:

USE [master]
GO
ALTER DATABASE [YourDatabaseName] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
DROP DATABASE [YourDatabaseName]
GO

CSS text-decoration underline color

(for fellow googlers, copied from duplicate question) This answer is outdated since text-decoration-color is now supported by most modern browsers.

You can do this via the following CSS rule as an example:

text-decoration-color:green


If this rule isn't supported by an older browser, you can use the following solution:

Setting your word with a border-bottom:

a:link {
  color: red;
  text-decoration: none;
  border-bottom: 1px solid blue;
}
a:hover {
 border-bottom-color: green;
}

Serializing PHP object to JSON

Since your object type is custom, I would tend to agree with your solution - break it down into smaller segments using an encoding method (like JSON or serializing the content), and on the other end have corresponding code to re-construct the object.

How to get all the AD groups for a particular user?

If you have a LDAP connection with a username and password to connect to Active Directory, here is the code I used to connect properly:

using System.DirectoryServices.AccountManagement;

// ...

// Connection information
var connectionString = "LDAP://domain.com/DC=domain,DC=com";
var connectionUsername = "your_ad_username";
var connectionPassword = "your_ad_password";

// Get groups for this user
var username = "myusername";

// Split the LDAP Uri
var uri = new Uri(connectionString);
var host = uri.Host;
var container = uri.Segments.Count() >=1 ? uri.Segments[1] : "";

// Create context to connect to AD
var princContext = new PrincipalContext(ContextType.Domain, host, container, connectionUsername, connectionPassword);

// Get User
UserPrincipal user = UserPrincipal.FindByIdentity(princContext, IdentityType.SamAccountName, username);

// Browse user's groups
foreach (GroupPrincipal group in user.GetGroups())
{
    Console.Out.WriteLine(group.Name);
}

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

Dependency Walker tells all(well almost). http://www.dependencywalker.com/

It does not "install" -just get it, extract it and run the exec. It works for any x32 or x64 windows module|application.

As I recall it is fairly straightforward to see all dependencies, i.e. the dll modules, and since the appl. is a sum of the dependencies one can ascertain if it is full x64, x32(x86) or a bit of each.

Type of CPU that the module was built for is in the "CPU" column. Most 64-bit aps are still a bit of each but 32-bit ap w/b all x86.

Beautiful program for geeks/programmers and it is free...

How to Find App Pool Recycles in Event Log

IIS version 8.5 +

To enable Event Tracing for Windows for your website/application

  1. Go to Logging and ensure either ETW event only or Both log file and ETW event ...is selected.

enter image description here

  1. Enable the desired Recycle logs in the Advanced Settings for the Application Pool:

enter image description here

  1. Go to the default Custom View: WebServer filters IIS logs:

Custom Views > ServerRoles > Web Server

enter image description here

  1. ... or System logs:

Windows Logs > System

How to diff a commit with its parent?

Use:

git diff 15dc8^!

as described in the following fragment of git-rev-parse(1) manpage (or in modern git gitrevisions(7) manpage):

Two other shorthands for naming a set that is formed by a commit and its parent commits exist. The r1^@ notation means all parents of r1. r1^! includes commit r1 but excludes all of its parents.

This means that you can use 15dc8^! as a shorthand for 15dc8^..15dc8 anywhere in git where revisions are needed. For diff command the git diff 15dc8^..15dc8 is understood as git diff 15dc8^ 15dc8, which means the difference between parent of commit (15dc8^) and commit (15dc8).

Note: the description in git-rev-parse(1) manpage talks about revision ranges, where it needs to work also for merge commits, with more than one parent. Then r1^! is "r1 --not r1^@" i.e. "r1 ^r1^1 ^r1^2 ..."


Also, you can use git show COMMIT to get commit description and diff for a commit. If you want only diff, you can use git diff-tree -p COMMIT

Delete all files in directory (but not directory) - one liner solution

public class DeleteFile {
    public static void main(String[] args) {
        String path="D:\test"; 
        File file = new File(path);
        File[] files = file.listFiles(); 
        for (File f:files) 
        {if (f.isFile() && f.exists) 
            { f.delete();
system.out.println("successfully deleted");
            }else{
system.out.println("cant delete a file due to open or error");
} }  }}

Compiler error: "class, interface, or enum expected"

You forgot your class declaration:

public class MyClass {
...

Easiest way to toggle 2 classes in jQuery

Toggle between two classes 'A' and 'B' with Jquery.

$('#selecor_id').toggleClass("A B");

rsync: difference between --size-only and --ignore-times

On a Scientific Linux 6.7 system, the man page on rsync says:

--ignore-times          don't skip files that match size and time

I have two files with identical contents, but with different creation dates:

[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron

[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/new/usercron

With --size-only, the two files are regarded the same:

[root@windstorm ~]# rsync -v --size-only -n  /tmp/new/usercron /tmp/master/usercron

sent 29 bytes  received 12 bytes  82.00 bytes/sec
total size is 1595  speedup is 38.90 (DRY RUN)

With --ignore-times, the two files are regarded different:

[root@windstorm ~]# rsync -v --ignore-times -n  /tmp/new/usercron /tmp/master/usercron
usercron

sent 32 bytes  received 15 bytes  94.00 bytes/sec
total size is 1595  speedup is 33.94 (DRY RUN)

So it does not looks like --ignore-times has any effect at all.

How to increase the Java stack size?

Add this option

--driver-java-options -Xss512m

to your spark-submit command will fix this issue.

How can I use UIColorFromRGB in Swift?

You can use this:

//The color RGB #85CC4B
let newColor = UIColor(red: CGFloat(0x85)/255
                      ,green: CGFloat(0xCC)/255
                      ,blue: CGFloat(0x4B)/255
                      ,alpha: 1.0)

How do I get the directory from a file's full path?

If you are working with a FileInfo object, then there is an easy way to extract a string representation of the directory's full path via the DirectoryName property.

Description of the FileInfo.DirectoryName Property via MSDN:

Gets a string representing the directory's full path.

Sample usage:

string filename = @"C:\MyDirectory\MyFile.bat";
FileInfo fileInfo = new FileInfo(filename);
string directoryFullPath = fileInfo.DirectoryName; // contains "C:\MyDirectory"

Link to the MSDN documentation.

Android: Proper Way to use onBackPressed() with Toast

additionally, you need to dissmis dialog before calling activity.super.onBackPressed(), otherwise you'll get "Activity has leaked.." error.

Example in my case with sweetalerdialog library:

 @Override
    public void onBackPressed() {
        //super.onBackPressed();
        SweetAlertDialog progressDialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
        progressDialog.setCancelable(false);
        progressDialog.setTitleText("Are you sure you want to exit?");
        progressDialog.setCancelText("No");
        progressDialog.setConfirmText("Yes");
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
                MainActivity.super.onBackPressed();
            }
        });
        progressDialog.show();
    }

How do I open the "front camera" on the Android platform?

As of Android 2.1, Android only supports a single camera in its SDK. It is likely that this will be added in a future Android release.

Excel VBA Loop on columns

Another method to try out. Also select could be replaced when you set the initial column into a Range object. Performance wise it helps.

Dim rng as Range

Set rng = WorkSheets(1).Range("A1") '-- you may change the sheet name according to yours.

'-- here is your loop
i = 1
Do
   '-- do something: e.g. show the address of the column that you are currently in
   Msgbox rng.offset(0,i).Address 
   i = i + 1
Loop Until i > 10

** Two methods to get the column name using column number**

  • Split()

code

colName = Split(Range.Offset(0,i).Address, "$")(1)
  • String manipulation:

code

Function myColName(colNum as Long) as String
    myColName = Left(Range(0, colNum).Address(False, False), _ 
    1 - (colNum > 10)) 
End Function 

ASP.NET MVC View Engine Comparison

I know this doesn't really answer your question, but different View Engines have different purposes. The Spark View Engine, for example, aims to rid your views of "tag soup" by trying to make everything fluent and readable.

Your best bet would be to just look at some implementations. If it looks appealing to the intent of your solution, try it out. You can mix and match view engines in MVC, so it shouldn't be an issue if you decide to not go with a specific engine.

Does uninstalling a package with "pip" also remove the dependent packages?

You can install and use the pip-autoremove utility to remove a package plus unused dependencies.

# install pip-autoremove
pip install pip-autoremove
# remove "somepackage" plus its dependencies:
pip-autoremove somepackage -y

How to copy a file to multiple directories using the gnu cp command

For example if you are in the parent directory of you destination folders you can do:

for i in $(ls); do cp sourcefile $i; done