Programs & Examples On #Eclipse plugin

Eclipse is an OSGi extensible platform for tool integration. The extensions to Eclipse are Java plug-ins. Use this tag to ask about developing Eclipse plug-ins. Note that asking for plug-in recommendations is off-topic.

How to see my Eclipse version?

Go to Help -> About Eclipse Sdk

enter image description here

enter image description here

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

The new URL for the repository is now http://download.eclipse.org/tools/pdt/updates/release. In Eclipse: open Help -> install new sofware -> add. Then paste this URL in the location.

Mark the check boxes you want and click next.

How to install Hibernate Tools in Eclipse?

Once you have copied the plugins and features folder to eclipse (eg. c:\program files\eclipse (or whereever you installed it). You will see a features and plugins folder there already) you can check if hibernate has installed by going to Help > Software updates > installed software. If hibernate is not listed close eclipse and launch it again via a command window with this command "eclipse -clean".

Correct way to remove plugin from Eclipse

Correct way to remove install plug-in from Eclipse/STS :

Go to install folder of eclipse ----> plugin --> select required plugin and remove it.

Ex-

Step 1. 
E:\springsource\sts-3.4.0.RELEASE\plugins

Step 2. 
select and remove related plugins jars.

How do I set the eclipse.ini -vm option?

My solution for Ubuntu Linux:

-vm
/home/daniel/Downloads/jdk1.6.0_17/bin
-startup
plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.2.R36x_v20101019_1345
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m

"SDK Platform Tools component is missing!"

OK, here is what I did to fix the problem:

Open Eclipse. Then:
  Window > Android SDK and AVD Manager
   > Available Packages: 
     > Android Repository:
       + Android SDK Tools, revision 8
       + Android SDK Platform-tools, revision 1

[Install Selected]

Launch Failed. Binary not found. CDT on Eclipse Helios

Go to the Run->Run Configuration-> now

Under C/C++ Application you will see the name of your executable + Debug (if not, click over C/C++ Application a couple of times). Select the name (in this case projectTitle+Debug).

Under this in main Tab -> C/C++ application -> Search your project -> in binaries select your binary titled by your project....

How to save LogCat contents to file?

String filePath = folder.getAbsolutePath()+ "/logcat.txt"; 
Runtime.getRuntime().exec(new String[]{"logcat", "-f", filePath, "MyAppTAG:V", "*:E"});

How do I install Eclipse Marketplace in Eclipse Classic?

  1. Help->Install New Software...
  2. Point to Eclipse Juno Site, If not available add the site "Juno - http://download.eclipse.org/releases/juno"

  3. Select and expand general purpose tools

  4. Select and install Marketplace client

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

I removed C:\ProgramData\Oracle\Java\javapath from my path, and it worked for me.

But make sure you include x64 JDK and JRE addresses in your path.

Maven in Eclipse: step by step installation

By "use install a Maven plugin and use it" I am sure you are looking for a Eclipse plugin that will perform Maven functions within the IDE. If so, M2E is a good choice. You will find a lot of help within the Eclipse installation once you install M2E.

That said -- considering that you are starting off using Maven -- it would go a long way to have a good understanding of the basic concepts. Using M2E could hide some of the details which could lead to incomplete or incorrect interpretation of Maven's behavior and therefore problems downstream.

Some good Maven online references are:

Why do I keep getting 'SVN: Working Copy XXXX locked; try performing 'cleanup'?

This will happen when something went wrong in one of your folders in you project. You need to find out the exact folder that locked and execute svn cleanup under the specific folder. You can solve this as follows:

  1. run svn commit command to find out which folder went wrong.
  2. change directory to that folder and run svn cleanup. Then it's done.

How can I change Eclipse theme?

In the eclipse Version: 2019-09 R (4.13.0) on windows Go to Window > preferences > Appearance Select the required theme for dark theme to choose Dark and click on Ok. enter image description here

What to do about Eclipse's "No repository found containing: ..." error messages?

2019 Eclipse/CCS

After trying many of the above techniques described here I noticed this post by Edwin landwealths

The long and short of it is to add the infamous tail "/" and ALSO change "http" to "https". This fixed my issue immediately.

Eclipse fonts and background color

... on a Mac, Preferences' is under the main 'Aptana Studio 3' menu rather than the 'Windows' menu as mentioned above.

JavaScript Editor Plugin for Eclipse

Think that JavaScriptDevelopmentTools might do it. Although, I have eclipse indigo, and I'm pretty sure it does that kind of thing automatically.

Is there a good JSP editor for Eclipse?

I followed the advice of Simon Gibbs in this answer and found it worked out fine - if you're in a hurry, the "Web Page Editor (optional)" package from the Eclipse update site does the trick.

For the Eclipse-challenged (me) Help > Install New Software > Work with > Expand Web, XML, and Java EE Development > Select "Web Page Editor (optional)" and "next-through" to completion.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I also faced the above error. I used Eclipse.

After followed the below solution, it works fine for me.

Solution is,

  1. Right click project "pom.xml" in eclipse and select Maven Install.
  2. Right click on the project -> Maven -> Update Project.
  3. Refresh

How do you create a Spring MVC project in Eclipse?

You want to create a "Dynamic Web Project". Follow the steps here: Spring MVC Tutorial with Eclipse and Tomcat.

Also, here is the Eclipse documentation for Dynamic Web Projects: http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.webtools.doc.user/topics/ccwebprj.html

No server in windows>preferences

Follow the below steps:

1.Goto Help -> Install new Software
2.Give address http://download.eclipse.org/releases/oxygen and name as your choice.
3.Search for Java EE and choose 1.Eclipse Java EE Developer Tools 
4.Search for JST and choose 2.JST Server Adapters 3.JST Server Adapters 
5.Click next and accept the license agreement.

Find the server option in the window-->preferences and add server as you need

Eclipse IDE: How to zoom in on text?

I've answered it here. How can I change font size in Eclipse for Java text editors?

For Eclipse Neon

To Increase Ctrl +

To reduce Ctrl - enter image description here

Android Device Chooser -- device not showing up

I'm on a MAC and for some reason when I connected my device via USB there was a weird mount called USB-Drivers which when I UNmounted from Finder, the Androide Device Chooser instantly recognized my device.

m2eclipse not finding maven dependencies, artifacts not found

This could be a problem if you are using a custom 'Settings.xml', with a different <localRepository> configured in it.

Eclipse will be using the default installation of MAVEN, and will be using the default location for the User to look for the local Maven repository, which on Linux systems would be '/home/${USER}/.m2/'

Eclipse can be easily configured to use the customized 'Settings.xml', by doing the following: Goto -> Window -> Preferences -> Select 'Maven' -> Select 'User Settings'

  1. Under 'User Settings', select the custom 'Settings.xml' file, for 'User Settings' by clicking 'Browse' and selecting the customized 'Settings.xml'.
  2. Click on 'Update Settings', if the 'Local Repository' Textbox does not show the custom location from the file above, just key in the location and click 'Reindex'.
  3. Click 'OK'

After this, you could proceed to select your project from the 'Project Explorer', right click, Select 'Maven' > 'Update Project'. Make sure that your project is selected (ticked) in the Window, and click 'OK'.

This should help to resolve the issue, if using custom 'Settings.xml' for Maven.

Hope it helps.

Is there an Eclipse plugin to run system shell in the Console?

You can also use the Termial view to ssh/telnet to your local machine. Doesn't have that funny input box for commands.

An error occurred while collecting items to be installed (Access is denied)

None of the above worked for me.

Instead, I tried installing the plugins I needed via the Eclipse Market Place, and that worked without issue.

  1. Click "Help" Menu.
  2. Click "Eclipse Marketplace..." menu item.
  3. Enter the name of the plugin you want.
  4. Click "Install" when the plugin appears in the Marketplace List.
  5. Restart Eclipse.

Error with multiple definitions of function

You have #include "fun.cpp" in mainfile.cpp so compiling with:

g++ -o hw1 mainfile.cpp

will work, however if you compile by linking these together like

g++ -g -std=c++11 -Wall -pedantic   -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic   -c -o mainfile.o mainfile.cpp

As they mention above, adding #include "fun.hpp" will need to be done or it won't work. However, your case with the funct() function is slightly different than my problem.

I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.

Compile Views in ASP.NET MVC

Build > Run Code Analysis

Hotkey : Alt+F11

Helped me catch Razor errors.

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

Failure [INSTALL_FAILED_OLDER_SDK] basically means that the installation has failed due to the target location (AVD/Device) having an older SDK version than the targetSdkVersion specified in your app.

N/B Froyo 2.2 API 8

To fix this simply change

targetSdkVersion="17" to targetSdkVersion="8"

cheers.

importing a CSV into phpmyadmin

Using the LOAD DATA INFILE SQL statement you can import the CSV file, but you can't update data. However, there is a trick you can use.

  • Create another temporary table to use for the import
  • Load onto this table from the CSC

    LOAD DATA LOCAL INFILE '/file.csv'
    INTO TABLE temp_table
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\n'
    (field1, field2, field3); 
    
  • UPDATE the real table joining the table

    UPDATE maintable
    INNER JOIN temp_table A USING (field1)
    SET maintable.field1 = temp_table.field1
    

load external URL into modal jquery ui dialog

EDIT: This answer might be outdated if you're using a recent version of jQueryUI.

For an anchor to trigger the dialog -

<a href="http://ibm.com" class="example">

Here's the script -

$('a.example').click(function(){   //bind handlers
   var url = $(this).attr('href');
   showDialog(url);

   return false;
});

$("#targetDiv").dialog({  //create dialog, but keep it closed
   autoOpen: false,
   height: 300,
   width: 350,
   modal: true
});

function showDialog(url){  //load content and open dialog
    $("#targetDiv").load(url);
    $("#targetDiv").dialog("open");         
}

C# looping through an array

This should work:

//iterate the array
for (int i = 0; i < theData.Length; i+=3)
{
    //grab 3 items at a time and do db insert, continue until all items are gone. 'theData' will always be divisible by 3.
    var a = theData[i];
    var b = theData[i + 1];
    var c = theData[i + 2];
}

I've been downvoted for this answer once. I'm pretty sure it is related to the use of theData.Length for the upperbound. The code as is works fine because array is guaranteed to be a multiple of three as the question states. If this guarantee wasn't in place, you would need to check the upper bound with theData.Length - 2 instead.

How to check currently internet connection is available or not in android

This will show an dialog error box if there is not network connectivity

    ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        // fetch data
    } else {
        new AlertDialog.Builder(this)
            .setTitle("Connection Failure")
            .setMessage("Please Connect to the Internet")
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
    }

How do I move a redis database from one server to another?

you can also use rdd

it can dump & restore a running redis server and allow filter/match/rename dumps keys

When to use std::size_t?

short answer:

almost never

long answer:

Whenever you need to have a vector of char bigger that 2gb on a 32 bit system. In every other use case, using a signed type is much safer than using an unsigned type.

example:

std::vector<A> data;
[...]
// calculate the index that should be used;
size_t i = calc_index(param1, param2);
// doing calculations close to the underflow of an integer is already dangerous

// do some bounds checking
if( i - 1 < 0 ) {
    // always false, because 0-1 on unsigned creates an underflow
    return LEFT_BORDER;
} else if( i >= data.size() - 1 ) {
    // if i already had an underflow, this becomes true
    return RIGHT_BORDER;
}

// now you have a bug that is very hard to track, because you never 
// get an exception or anything anymore, to detect that you actually 
// return the false border case.

return calc_something(data[i-1], data[i], data[i+1]);

The signed equivalent of size_t is ptrdiff_t, not int. But using int is still much better in most cases than size_t. ptrdiff_t is long on 32 and 64 bit systems.

This means that you always have to convert to and from size_t whenever you interact with a std::containers, which not very beautiful. But on a going native conference the authors of c++ mentioned that designing std::vector with an unsigned size_t was a mistake.

If your compiler gives you warnings on implicit conversions from ptrdiff_t to size_t, you can make it explicit with constructor syntax:

calc_something(data[size_t(i-1)], data[size_t(i)], data[size_t(i+1)]);

if just want to iterate a collection, without bounds cheking, use range based for:

for(const auto& d : data) {
    [...]
}

here some words from Bjarne Stroustrup (C++ author) at going native

For some people this signed/unsigned design error in the STL is reason enough, to not use the std::vector, but instead an own implementation.

Difference between left join and right join in SQL Server

Table from which you are taking data is 'LEFT'.
Table you are joining is 'RIGHT'.
LEFT JOIN: Take all items from left table AND (only) matching items from right table.
RIGHT JOIN: Take all items from right table AND (only) matching items from left table.
So:

Select * from Table1 left join Table2 on Table1.id = Table2.id  

gives:

Id     Name       
-------------  
1      A          
2      B      

but:

Select * from Table1 right join Table2 on Table1.id = Table2.id

gives:

Id     Name       
-------------  
1      A          
2      B   
3      C  

you were right joining table with less rows on table with more rows
AND
again, left joining table with less rows on table with more rows
Try:

 If Table1.Rows.Count > Table2.Rows.Count Then  
    ' Left Join  
 Else  
    ' Right Join  
 End If  

PHP write file from input to txt

use fwrite() instead of file_put_contents()

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

I installed System.Configuration.ConfigurationManager from Nuget into my .net core 2.2 application.

I then reference using System.Configuration;

Next, I changed

WebConfigurationManager.AppSettings

to ..

ConfigurationManager.AppSettings

So far I believe this is correct. 4.5.0 is typical with .net core 2.2

I have not had any issues with this.

How to display the first few characters of a string in Python?

You can 'slice' a string very easily, just like you'd pull items from a list:

a_string = 'This is a string'

To get the first 4 letters:

first_four_letters = a_string[:4]
>>> 'This'

Or the last 5:

last_five_letters = a_string[-5:]
>>> 'string'

So applying that logic to your problem:

the_string = '416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f '
first_32_chars = the_string[:32]
>>> 416d76b8811b0ddae2fdad8f4721ddbe

Bootstrap 3 unable to display glyphicon properly

Did you choose the customized version of Bootstrap? There is an issue that the font files included in the customized package are broken (see https://github.com/twbs/bootstrap/issues/9925). If you do not want to use the CDN, you have to download them manually and replace your own fonts with the downloaded ones:

https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot

After that try a strong reload (CTRL + F5), hope it helps.

How can I make a DateTimePicker display an empty string?

this worked for me for c#

if (enableEndDateCheckBox.Checked == true)
{
    endDateDateTimePicker.Enabled = true;
    endDateDateTimePicker.Format = DateTimePickerFormat.Short;                
}
else
{
    endDateDateTimePicker.Enabled = false;
    endDateDateTimePicker.Format = DateTimePickerFormat.Custom;
    endDateDateTimePicker.CustomFormat = " ";
}

nice one guys!

How to set the custom border color of UIView programmatically?

swift 3.0

self.uiTextView.layer.borderWidth = 0.5
    self.txtItemShortDes.layer.borderColor = UIColor(red:205.0/255.0, green:205.0/255.0, blue:205.0/255.0, alpha: 1.0).cgColor

Test if string begins with a string?

The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.

The expensive regex method and the css attribute selector with starts with ^ operator

Option Explicit

Public Sub test()

    Debug.Print StartWithSubString("ab", "abc,d")

End Sub

Regex:

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft VBScript Regular Expressions
    Dim re As VBScript_RegExp_55.RegExp
    Set re = New VBScript_RegExp_55.RegExp

    re.Pattern = "^" & substring

    StartWithSubString = re.test(testString)

End Function

Css attribute selector with starts with operator

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft HTML Object Library
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument

    html.body.innerHTML = "<div test=""" & testString & """></div>"

    StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0

End Function

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

How should a model be structured in MVC?

Disclaimer: the following is a description of how I understand MVC-like patterns in the context of PHP-based web applications. All the external links that are used in the content are there to explain terms and concepts, and not to imply my own credibility on the subject.

The first thing that I must clear up is: the model is a layer.

Second: there is a difference between classical MVC and what we use in web development. Here's a bit of an older answer I wrote, which briefly describes how they are different.

What a model is NOT:

The model is not a class or any single object. It is a very common mistake to make (I did too, though the original answer was written when I began to learn otherwise), because most frameworks perpetuate this misconception.

Neither is it an Object-Relational Mapping technique (ORM) nor an abstraction of database tables. Anyone who tells you otherwise is most likely trying to 'sell' another brand-new ORM or a whole framework.

What a model is:

In proper MVC adaptation, the M contains all the domain business logic and the Model Layer is mostly made from three types of structures:

  • Domain Objects

    A domain object is a logical container of purely domain information; it usually represents a logical entity in the problem domain space. Commonly referred to as business logic.

    This would be where you define how to validate data before sending an invoice, or to compute the total cost of an order. At the same time, Domain Objects are completely unaware of storage - neither from where (SQL database, REST API, text file, etc.) nor even if they get saved or retrieved.

  • Data Mappers

    These objects are only responsible for the storage. If you store information in a database, this would be where the SQL lives. Or maybe you use an XML file to store data, and your Data Mappers are parsing from and to XML files.

  • Services

    You can think of them as "higher level Domain Objects", but instead of business logic, Services are responsible for interaction between Domain Objects and Mappers. These structures end up creating a "public" interface for interacting with the domain business logic. You can avoid them, but at the penalty of leaking some domain logic into Controllers.

    There is a related answer to this subject in the ACL implementation question - it might be useful.

The communication between the model layer and other parts of the MVC triad should happen only through Services. The clear separation has a few additional benefits:

  • it helps to enforce the single responsibility principle (SRP)
  • provides additional 'wiggle room' in case the logic changes
  • keeps the controller as simple as possible
  • gives a clear blueprint, if you ever need an external API

 

How to interact with a model?

Prerequisites: watch lectures "Global State and Singletons" and "Don't Look For Things!" from the Clean Code Talks.

Gaining access to service instances

For both the View and Controller instances (what you could call: "UI layer") to have access these services, there are two general approaches:

  1. You can inject the required services in the constructors of your views and controllers directly, preferably using a DI container.
  2. Using a factory for services as a mandatory dependency for all of your views and controllers.

As you might suspect, the DI container is a lot more elegant solution (while not being the easiest for a beginner). The two libraries, that I recommend considering for this functionality would be Syfmony's standalone DependencyInjection component or Auryn.

Both the solutions using a factory and a DI container would let you also share the instances of various servers to be shared between the selected controller and view for a given request-response cycle.

Alteration of model's state

Now that you can access to the model layer in the controllers, you need to start actually using them:

public function postLogin(Request $request)
{
    $email = $request->get('email');
    $identity = $this->identification->findIdentityByEmailAddress($email);
    $this->identification->loginWithPassword(
        $identity,
        $request->get('password')
    );
}

Your controllers have a very clear task: take the user input and, based on this input, change the current state of business logic. In this example the states that are changed between are "anonymous user" and "logged in user".

Controller is not responsible for validating user's input, because that is part of business rules and controller is definitely not calling SQL queries, like what you would see here or here (please don't hate on them, they are misguided, not evil).

Showing user the state-change.

Ok, user has logged in (or failed). Now what? Said user is still unaware of it. So you need to actually produce a response and that is the responsibility of a view.

public function postLogin()
{
    $path = '/login';
    if ($this->identification->isUserLoggedIn()) {
        $path = '/dashboard';
    }
    return new RedirectResponse($path); 
}

In this case, the view produced one of two possible responses, based on the current state of model layer. For a different use-case you would have the view picking different templates to render, based on something like "current selected of article" .

The presentation layer can actually get quite elaborate, as described here: Understanding MVC Views in PHP.

But I am just making a REST API!

Of course, there are situations, when this is a overkill.

MVC is just a concrete solution for Separation of Concerns principle. MVC separates user interface from the business logic, and it in the UI it separated handling of user input and the presentation. This is crucial. While often people describe it as a "triad", it's not actually made up from three independent parts. The structure is more like this:

MVC separation

It means, that, when your presentation layer's logic is close to none-existent, the pragmatic approach is to keep them as single layer. It also can substantially simplify some aspects of model layer.

Using this approach the login example (for an API) can be written as:

public function postLogin(Request $request)
{
    $email = $request->get('email');
    $data = [
        'status' => 'ok',
    ];
    try {
        $identity = $this->identification->findIdentityByEmailAddress($email);
        $token = $this->identification->loginWithPassword(
            $identity,
            $request->get('password')
        );
    } catch (FailedIdentification $exception) {
        $data = [
            'status' => 'error',
            'message' => 'Login failed!',
        ]
    }

    return new JsonResponse($data);
}

While this is not sustainable, when you have complicate logic for rendering a response body, this simplification is very useful for more trivial scenarios. But be warned, this approach will become a nightmare, when attempting to use in large codebases with complex presentation logic.

 

How to build the model?

Since there is not a single "Model" class (as explained above), you really do not "build the model". Instead you start from making Services, which are able to perform certain methods. And then implement Domain Objects and Mappers.

An example of a service method:

In the both approaches above there was this login method for the identification service. What would it actually look like. I am using a slightly modified version of the same functionality from a library, that I wrote .. because I am lazy:

public function loginWithPassword(Identity $identity, string $password): string
{
    if ($identity->matchPassword($password) === false) {
        $this->logWrongPasswordNotice($identity, [
            'email' => $identity->getEmailAddress(),
            'key' => $password, // this is the wrong password
        ]);

        throw new PasswordMismatch;
    }

    $identity->setPassword($password);
    $this->updateIdentityOnUse($identity);
    $cookie = $this->createCookieIdentity($identity);

    $this->logger->info('login successful', [
        'input' => [
            'email' => $identity->getEmailAddress(),
        ],
        'user' => [
            'account' => $identity->getAccountId(),
            'identity' => $identity->getId(),
        ],
    ]);

    return $cookie->getToken();
}

As you can see, at this level of abstraction, there is no indication of where the data was fetched from. It might be a database, but it also might be just a mock object for testing purposes. Even the data mappers, that are actually used for it, are hidden away in the private methods of this service.

private function changeIdentityStatus(Entity\Identity $identity, int $status)
{
    $identity->setStatus($status);
    $identity->setLastUsed(time());
    $mapper = $this->mapperFactory->create(Mapper\Identity::class);
    $mapper->store($identity);
}

Ways of creating mappers

To implement an abstraction of persistence, on the most flexible approaches is to create custom data mappers.

Mapper diagram

From: PoEAA book

In practice they are implemented for interaction with specific classes or superclasses. Lets say you have Customer and Admin in your code (both inheriting from a User superclass). Both would probably end up having a separate matching mapper, since they contain different fields. But you will also end up with shared and commonly used operations. For example: updating the "last seen online" time. And instead of making the existing mappers more convoluted, the more pragmatic approach is to have a general "User Mapper", which only update that timestamp.

Some additional comments:

  1. Database tables and model

    While sometimes there is a direct 1:1:1 relationship between a database table, Domain Object, and Mapper, in larger projects it might be less common than you expect:

    • Information used by a single Domain Object might be mapped from different tables, while the object itself has no persistence in the database.

      Example: if you are generating a monthly report. This would collect information from different of tables, but there is no magical MonthlyReport table in the database.

    • A single Mapper can affect multiple tables.

      Example: when you are storing data from the User object, this Domain Object could contain collection of other domain objects - Group instances. If you alter them and store the User, the Data Mapper will have to update and/or insert entries in multiple tables.

    • Data from a single Domain Object is stored in more than one table.

      Example: in large systems (think: a medium-sized social network), it might be pragmatic to store user authentication data and often-accessed data separately from larger chunks of content, which is rarely required. In that case you might still have a single User class, but the information it contains would depend of whether full details were fetched.

    • For every Domain Object there can be more than one mapper

      Example: you have a news site with a shared codebased for both public-facing and the management software. But, while both interfaces use the same Article class, the management needs a lot more info populated in it. In this case you would have two separate mappers: "internal" and "external". Each performing different queries, or even use different databases (as in master or slave).

  2. A view is not a template

    View instances in MVC (if you are not using the MVP variation of the pattern) are responsible for the presentational logic. This means that each View will usually juggle at least a few templates. It acquires data from the Model Layer and then, based on the received information, chooses a template and sets values.

    One of the benefits you gain from this is re-usability. If you create a ListView class, then, with well-written code, you can have the same class handing the presentation of user-list and comments below an article. Because they both have the same presentation logic. You just switch templates.

    You can use either native PHP templates or use some third-party templating engine. There also might be some third-party libraries, which are able to fully replace View instances.

  3. What about the old version of the answer?

    The only major change is that, what is called Model in the old version, is actually a Service. The rest of the "library analogy" keeps up pretty well.

    The only flaw that I see is that this would be a really strange library, because it would return you information from the book, but not let you touch the book itself, because otherwise the abstraction would start to "leak". I might have to think of a more fitting analogy.

  4. What is the relationship between View and Controller instances?

    The MVC structure is composed of two layers: ui and model. The main structures in the UI layer are views and controller.

    When you are dealing with websites that use MVC design pattern, the best way is to have 1:1 relation between views and controllers. Each view represents a whole page in your website and it has a dedicated controller to handle all the incoming requests for that particular view.

    For example, to represent an opened article, you would have \Application\Controller\Document and \Application\View\Document. This would contain all the main functionality for UI layer, when it comes to dealing with articles (of course you might have some XHR components that are not directly related to articles).

What happens to C# Dictionary<int, int> lookup if the key does not exist?

The Dictionary throws a KeyNotFound exception in the event that the dictionary does not contain your key.

As suggested, ContainsKey is the appropriate precaution. TryGetValue is also effective.

This allows the dictionary to store a value of null more effectively. Without it behaving this way, checking for a null result from the [] operator would indicate either a null value OR the non-existance of the input key which is no good.

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Yes, you can install Postman using these commands:

wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
sudo tar -xzf postman.tar.gz -C /opt
rm postman.tar.gz
sudo ln -s /opt/Postman/Postman /usr/bin/postman

You can also get Postman to show up in the Unity Launcher:

cat > ~/.local/share/applications/postman.desktop <<EOL
[Desktop Entry]
Encoding=UTF-8
Name=Postman
Exec=postman
Icon=/opt/Postman/app/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;
EOL

You don't need node.js or any other dependencies with a standard Ubuntu dev install.

See more at our blog post at https://blog.bluematador.com/posts/postman-how-to-install-on-ubuntu-1604/.

EDIT: Changed icon.png location. Latest versions of Postman changed their directory structure slightly.

Using @property versus getters and setters

[TL;DR? You can skip to the end for a code example.]

I actually prefer to use a different idiom, which is a little involved for using as a one off, but is nice if you have a more complex use case.

A bit of background first.

Properties are useful in that they allow us to handle both setting and getting values in a programmatic way but still allow attributes to be accessed as attributes. We can turn 'gets' into 'computations' (essentially) and we can turn 'sets' into 'events'. So let's say we have the following class, which I've coded with Java-like getters and setters.

class Example(object):
    def __init__(self, x=None, y=None):
        self.x = x
        self.y = y

    def getX(self):
        return self.x or self.defaultX()

    def getY(self):
        return self.y or self.defaultY()

    def setX(self, x):
        self.x = x

    def setY(self, y):
        self.y = y

    def defaultX(self):
        return someDefaultComputationForX()

    def defaultY(self):
        return someDefaultComputationForY()

You may be wondering why I didn't call defaultX and defaultY in the object's __init__ method. The reason is that for our case I want to assume that the someDefaultComputation methods return values that vary over time, say a timestamp, and whenever x (or y) is not set (where, for the purpose of this example, "not set" means "set to None") I want the value of x's (or y's) default computation.

So this is lame for a number of reasons describe above. I'll rewrite it using properties:

class Example(object):
    def __init__(self, x=None, y=None):
        self._x = x
        self._y = y

    @property
    def x(self):
        return self.x or self.defaultX()

    @x.setter
    def x(self, value):
        self._x = value

    @property
    def y(self):
        return self.y or self.defaultY()

    @y.setter
    def y(self, value):
        self._y = value

    # default{XY} as before.

What have we gained? We've gained the ability to refer to these attributes as attributes even though, behind the scenes, we end up running methods.

Of course the real power of properties is that we generally want these methods to do something in addition to just getting and setting values (otherwise there is no point in using properties). I did this in my getter example. We are basically running a function body to pick up a default whenever the value isn't set. This is a very common pattern.

But what are we losing, and what can't we do?

The main annoyance, in my view, is that if you define a getter (as we do here) you also have to define a setter.[1] That's extra noise that clutters the code.

Another annoyance is that we still have to initialize the x and y values in __init__. (Well, of course we could add them using setattr() but that is more extra code.)

Third, unlike in the Java-like example, getters cannot accept other parameters. Now I can hear you saying already, well, if it's taking parameters it's not a getter! In an official sense, that is true. But in a practical sense there is no reason we shouldn't be able to parameterize an named attribute -- like x -- and set its value for some specific parameters.

It'd be nice if we could do something like:

e.x[a,b,c] = 10
e.x[d,e,f] = 20

for example. The closest we can get is to override the assignment to imply some special semantics:

e.x = [a,b,c,10]
e.x = [d,e,f,30]

and of course ensure that our setter knows how to extract the first three values as a key to a dictionary and set its value to a number or something.

But even if we did that we still couldn't support it with properties because there is no way to get the value because we can't pass parameters at all to the getter. So we've had to return everything, introducing an asymmetry.

The Java-style getter/setter does let us handle this, but we're back to needing getter/setters.

In my mind what we really want is something that capture the following requirements:

  • Users define just one method for a given attribute and can indicate there whether the attribute is read-only or read-write. Properties fail this test if the attribute writable.

  • There is no need for the user to define an extra variable underlying the function, so we don't need the __init__ or setattr in the code. The variable just exists by the fact we've created this new-style attribute.

  • Any default code for the attribute executes in the method body itself.

  • We can set the attribute as an attribute and reference it as an attribute.

  • We can parameterize the attribute.

In terms of code, we want a way to write:

def x(self, *args):
    return defaultX()

and be able to then do:

print e.x     -> The default at time T0
e.x = 1
print e.x     -> 1
e.x = None
print e.x     -> The default at time T1

and so forth.

We also want a way to do this for the special case of a parameterizable attribute, but still allow the default assign case to work. You'll see how I tackled this below.

Now to the point (yay! the point!). The solution I came up for for this is as follows.

We create a new object to replace the notion of a property. The object is intended to store the value of a variable set to it, but also maintains a handle on code that knows how to calculate a default. Its job is to store the set value or to run the method if that value is not set.

Let's call it an UberProperty.

class UberProperty(object):

    def __init__(self, method):
        self.method = method
        self.value = None
        self.isSet = False

    def setValue(self, value):
        self.value = value
        self.isSet = True

    def clearValue(self):
        self.value = None
        self.isSet = False

I assume method here is a class method, value is the value of the UberProperty, and I have added isSet because None may be a real value and this allows us a clean way to declare there really is "no value". Another way is a sentinel of some sort.

This basically gives us an object that can do what we want, but how do we actually put it on our class? Well, properties use decorators; why can't we? Let's see how it might look (from here on I'm going to stick to using just a single 'attribute', x).

class Example(object):

    @uberProperty
    def x(self):
        return defaultX()

This doesn't actually work yet, of course. We have to implement uberProperty and make sure it handles both gets and sets.

Let's start with gets.

My first attempt was to simply create a new UberProperty object and return it:

def uberProperty(f):
    return UberProperty(f)

I quickly discovered, of course, that this doens't work: Python never binds the callable to the object and I need the object in order to call the function. Even creating the decorator in the class doesn't work, as although now we have the class, we still don't have an object to work with.

So we're going to need to be able to do more here. We do know that a method need only be represented the one time, so let's go ahead and keep our decorator, but modify UberProperty to only store the method reference:

class UberProperty(object):

    def __init__(self, method):
        self.method = method

It is also not callable, so at the moment nothing is working.

How do we complete the picture? Well, what do we end up with when we create the example class using our new decorator:

class Example(object):

    @uberProperty
    def x(self):
        return defaultX()

print Example.x     <__main__.UberProperty object at 0x10e1fb8d0>
print Example().x   <__main__.UberProperty object at 0x10e1fb8d0>

in both cases we get back the UberProperty which of course is not a callable, so this isn't of much use.

What we need is some way to dynamically bind the UberProperty instance created by the decorator after the class has been created to an object of the class before that object has been returned to that user for use. Um, yeah, that's an __init__ call, dude.

Let's write up what we want our find result to be first. We're binding an UberProperty to an instance, so an obvious thing to return would be a BoundUberProperty. This is where we'll actually maintain state for the x attribute.

class BoundUberProperty(object):
    def __init__(self, obj, uberProperty):
        self.obj = obj
        self.uberProperty = uberProperty
        self.isSet = False

    def setValue(self, value):
        self.value = value
        self.isSet = True

    def getValue(self):
        return self.value if self.isSet else self.uberProperty.method(self.obj)

    def clearValue(self):
        del self.value
        self.isSet = False

Now we the representation; how do get these on to an object? There are a few approaches, but the easiest one to explain just uses the __init__ method to do that mapping. By the time __init__ is called our decorators have run, so just need to look through the object's __dict__ and update any attributes where the value of the attribute is of type UberProperty.

Now, uber-properties are cool and we'll probably want to use them a lot, so it makes sense to just create a base class that does this for all subclasses. I think you know what the base class is going to be called.

class UberObject(object):
    def __init__(self):
        for k in dir(self):
            v = getattr(self, k)
            if isinstance(v, UberProperty):
                v = BoundUberProperty(self, v)
                setattr(self, k, v)

We add this, change our example to inherit from UberObject, and ...

e = Example()
print e.x               -> <__main__.BoundUberProperty object at 0x104604c90>

After modifying x to be:

@uberProperty
def x(self):
    return *datetime.datetime.now()*

We can run a simple test:

print e.x.getValue()
print e.x.getValue()
e.x.setValue(datetime.date(2013, 5, 31))
print e.x.getValue()
e.x.clearValue()
print e.x.getValue()

And we get the output we wanted:

2013-05-31 00:05:13.985813
2013-05-31 00:05:13.986290
2013-05-31
2013-05-31 00:05:13.986310

(Gee, I'm working late.)

Note that I have used getValue, setValue, and clearValue here. This is because I haven't yet linked in the means to have these automatically returned.

But I think this is a good place to stop for now, because I'm getting tired. You can also see that the core functionality we wanted is in place; the rest is window dressing. Important usability window dressing, but that can wait until I have a change to update the post.

I'll finish up the example in the next posting by addressing these things:

  • We need to make sure UberObject's __init__ is always called by subclasses.

    • So we either force it be called somewhere or we prevent it from being implemented.
    • We'll see how to do this with a metaclass.
  • We need to make sure we handle the common case where someone 'aliases' a function to something else, such as:

      class Example(object):
          @uberProperty
          def x(self):
              ...
    
          y = x
    
  • We need e.x to return e.x.getValue() by default.

    • What we'll actually see is this is one area where the model fails.
    • It turns out we'll always need to use a function call to get the value.
    • But we can make it look like a regular function call and avoid having to use e.x.getValue(). (Doing this one is obvious, if you haven't already fixed it out.)
  • We need to support setting e.x directly, as in e.x = <newvalue>. We can do this in the parent class too, but we'll need to update our __init__ code to handle it.

  • Finally, we'll add parameterized attributes. It should be pretty obvious how we'll do this, too.

Here's the code as it exists up to now:

import datetime

class UberObject(object):
    def uberSetter(self, value):
        print 'setting'

    def uberGetter(self):
        return self

    def __init__(self):
        for k in dir(self):
            v = getattr(self, k)
            if isinstance(v, UberProperty):
                v = BoundUberProperty(self, v)
                setattr(self, k, v)


class UberProperty(object):
    def __init__(self, method):
        self.method = method

class BoundUberProperty(object):
    def __init__(self, obj, uberProperty):
        self.obj = obj
        self.uberProperty = uberProperty
        self.isSet = False

    def setValue(self, value):
        self.value = value
        self.isSet = True

    def getValue(self):
        return self.value if self.isSet else self.uberProperty.method(self.obj)

    def clearValue(self):
        del self.value
        self.isSet = False

    def uberProperty(f):
        return UberProperty(f)

class Example(UberObject):

    @uberProperty
    def x(self):
        return datetime.datetime.now()

[1] I may be behind on whether this is still the case.

How can I style an Android Switch?

You can customize material styles by setting different color properties. For example custom application theme

<style name="CustomAppTheme" parent="Theme.AppCompat">
    <item name="android:textColorPrimaryDisableOnly">#00838f</item>
    <item name="colorAccent">#e91e63</item>
</style>

Custom switch theme

<style name="MySwitch" parent="@style/Widget.AppCompat.CompoundButton.Switch">
    <item name="android:textColorPrimaryDisableOnly">#b71c1c</item>
    <item name="android:colorControlActivated">#1b5e20</item>
    <item name="android:colorForeground">#f57f17</item>
    <item name="android:textAppearance">@style/TextAppearance.AppCompat</item>
</style>

You can customize switch track and switch thumb like below image by defining xml drawables. For more information http://www.zoftino.com/android-switch-button-and-custom-switch-examples

custom switch track and thumb

Save text file UTF-8 encoded with VBA

This writes a Byte Order Mark at the start of the file, which is unnecessary in a UTF-8 file and some applications (in my case, SAP) don't like it. Solution here: Can I export excel data with UTF-8 without BOM?

GCC dump preprocessor defines

A portable approach that works equally well on Linux or Windows (where there is no /dev/null):

echo | gcc -dM -E -

For c++ you may use (replace c++11 with whatever version you use):

echo | gcc -x c++ -std=c++11 -dM -E -

It works by telling gcc to preprocess stdin (which is produced by echo) and print all preprocessor defines (search for -dletters). If you want to know what defines are added when you include a header file you can use -dD option which is similar to -dM but does not include predefined macros:

echo "#include <stdlib.h>" | gcc -x c++ -std=c++11 -dD -E -

Note, however, that empty input still produces lots of defines with -dD option.

How to check if X server is running?

if [[ $DISPLAY ]]; then 
  …
fi

Correlation heatmap

  1. Use the 'jet' colormap for a transition between blue and red.
  2. Use pcolor() with the vmin, vmax parameters.

It is detailed in this answer: https://stackoverflow.com/a/3376734/21974

Regex match text between tags

var root = document.createElement("div");

root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var texts = [].map.call( root.querySelectorAll("b"), function(v){
    return v.textContent || v.innerText || "";
});

//["Bob", "20", "programming"]

Comparing strings in C# with OR in an if statement

Since you want to check whether textboxes contains any value or not your code should do the job. You should be more specific about the error you are having. You can also do:

if(textBox1.Text == string.Empty || textBox2.Text == string.Empty)
   {
    MessageBox.Show("You must enter a value into both boxes");
   }

EDIT 2: based on @JonSkeet comments:

Usage of string.Compare is not required as per OP's original unedited post. String.Equals should do the job if one wants to compare strings, and StringComparison may be used to ignore case for the comparison. string.Compare should be used for order comparison. Originally the question contain this comparison,

string testString = "This is a test";
string testString2 = "This is not a test";

if (testString == testString2)
{
    //do some stuff;
}

the if statement can be replaced with

if(testString.Equals(testString2))

or following to ignore case.

if(testString.Equals(testString2,StringComparison.InvariantCultureIgnoreCase)) 

Getting the 'external' IP address in Java

I am not sure if you can grab that IP from code that runs on the local machine.

You can however build code that runs on a website, say in JSP, and then use something that returns the IP of where the request came from:

request.getRemoteAddr()

Or simply use already-existing services that do this, then parse the answer from the service to find out the IP.

Use a webservice like AWS and others

import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

I had the same problem, and solved it by just adding the commons-logging.jar to the class path.

Convert MFC CString to integer

CString s;
int i;
i = _wtoi(s); // if you use wide charater formats
i = _atoi(s); // otherwise

Node.js: how to consume SOAP XML web service

I managed to use soap,wsdl and Node.js You need to install soap with npm install soap

Create a node server called server.js that will define soap service to be consumed by a remote client. This soap service computes Body Mass Index based on weight(kg) and height(m).

const soap = require('soap');
const express = require('express');
const app = express();
/**
 * this is remote service defined in this file, that can be accessed by clients, who will supply args
 * response is returned to the calling client
 * our service calculates bmi by dividing weight in kilograms by square of height in metres
 */
const service = {
  BMI_Service: {
    BMI_Port: {
      calculateBMI(args) {
        //console.log(Date().getFullYear())
        const year = new Date().getFullYear();
        const n = args.weight / (args.height * args.height);
        console.log(n);
        return { bmi: n };
      }
    }
  }
};
// xml data is extracted from wsdl file created
const xml = require('fs').readFileSync('./bmicalculator.wsdl', 'utf8');
//create an express server and pass it to a soap server
const server = app.listen(3030, function() {
  const host = '127.0.0.1';
  const port = server.address().port;
});
soap.listen(server, '/bmicalculator', service, xml);

Next, create a client.js file that will consume soap service defined by server.js. This file will provide arguments for the soap service and call the url with SOAP's service ports and endpoints.

const express = require('express');
const soap = require('soap');
const url = 'http://localhost:3030/bmicalculator?wsdl';
const args = { weight: 65.7, height: 1.63 };
soap.createClient(url, function(err, client) {
  if (err) console.error(err);
  else {
    client.calculateBMI(args, function(err, response) {
      if (err) console.error(err);
      else {
        console.log(response);
        res.send(response);
      }
    });
  }
});

Your wsdl file is an xml based protocol for data exchange that defines how to access a remote web service. Call your wsdl file bmicalculator.wsdl

<definitions name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl" 
  xmlns="http://schemas.xmlsoap.org/wsdl/" 
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
  xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <message name="getBMIRequest">
    <part name="weight" type="xsd:float"/>
    <part name="height" type="xsd:float"/>
  </message>

  <message name="getBMIResponse">
    <part name="bmi" type="xsd:float"/>
  </message>

  <portType name="Hello_PortType">
    <operation name="calculateBMI">
      <input message="tns:getBMIRequest"/>
      <output message="tns:getBMIResponse"/>
    </operation>
  </portType>

  <binding name="Hello_Binding" type="tns:Hello_PortType">
    <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="calculateBMI">
      <soap:operation soapAction="calculateBMI"/>
      <input>
        <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
      </input>
      <output>
        <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
      </output>
    </operation>
  </binding>

  <service name="BMI_Service">
    <documentation>WSDL File for HelloService</documentation>
    <port binding="tns:Hello_Binding" name="BMI_Port">
      <soap:address location="http://localhost:3030/bmicalculator/" />
    </port>
  </service>
</definitions>

Hope it helps

Center an item with position: relative

If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto

Vertical centering is a bit tricker, but possible.

Git refusing to merge unrelated histories on rebase

Firstly pull the remote changes to your local using the following command:

git pull origin branchname --allow-unrelated-histories

** branchname is master in my case.

When the pull command done, conflict occurs. You should solve the conflicts. I use Android Studio to solve conflicts. enter image description here

When conflicts solved, merge is done!

Now you can safely push.

is there any PHP function for open page in new tab

This is a trick,

function OpenInNewTab(url) {

  var win = window.open(url, '_blank');
  win.focus();
}

In most cases, this should happen directly in the onclick handler for the link to prevent pop-up blockers, and the default "new window" behavior. You could do it this way, or by adding an event listener to your DOM object.

<div onclick="OpenInNewTab();">Something To Click On</div>

What is the difference between sscanf or atoi to convert a string to an integer?

You have 3 choices:

  1. atoi

This is probably the fastest if you're using it in performance-critical code, but it does no error reporting. If the string does not begin with an integer, it will return 0. If the string contains junk after the integer, it will convert the initial part and ignore the rest. If the number is too big to fit in int, the behaviour is unspecified.

  1. sscanf

Some error reporting, and you have a lot of flexibility for what type to store (signed/unsigned versions of char/short/int/long/long long/size_t/ptrdiff_t/intmax_t).

The return value is the number of conversions that succeed, so scanning for "%d" will return 0 if the string does not begin with an integer. You can use "%d%n" to store the index of the first character after the integer that's read in another variable, and thereby check to see if the entire string was converted or if there's junk afterwards. However, like atoi, behaviour on integer overflow is unspecified.

  1. strtol and family

Robust error reporting, provided you set errno to 0 before making the call. Return values are specified on overflow and errno will be set. You can choose any number base from 2 to 36, or specify 0 as the base to auto-interpret leading 0x and 0 as hex and octal, respectively. Choices of type to convert to are signed/unsigned versions of long/long long/intmax_t.

If you need a smaller type you can always store the result in a temporary long or unsigned long variable and check for overflow yourself.

Since these functions take a pointer to pointer argument, you also get a pointer to the first character following the converted integer, for free, so you can tell if the entire string was an integer or parse subsequent data in the string if needed.


Personally, I would recommend the strtol family for most purposes. If you're doing something quick-and-dirty, atoi might meet your needs.

As an aside, sometimes I find I need to parse numbers where leading whitespace, sign, etc. are not supposed to be accepted. In this case it's pretty damn easy to roll your own for loop, eg.,

for (x=0; (unsigned)*s-'0'<10; s++) 
    x=10*x+(*s-'0');

Or you can use (for robustness):

if (isdigit(*s))
    x=strtol(s, &s, 10);
else /* error */ 

How to undo a SQL Server UPDATE query?

Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.

Then you can just review the contents pre-update and write a SQL script to do the update.

Generic List - moving an item within the list

Simplest way:

list[newIndex] = list[oldIndex];
list.RemoveAt(oldIndex);

EDIT

The question isn't very clear ... Since we don't care where the list[newIndex] item goes I think the simplest way of doing this is as follows (with or without an extension method):

    public static void Move<T>(this List<T> list, int oldIndex, int newIndex)
    {
        T aux = list[newIndex];
        list[newIndex] = list[oldIndex];
        list[oldIndex] = aux;
    }

This solution is the fastest because it doesn't involve list insertions/removals.

JQuery .hasClass for multiple values in an if statement

For anyone wondering about some of the different performance aspects with all of these different options, I've created a jsperf case here: jsperf

In short, using element.hasClass('class') is the fastest.

Next best bet is using elem.hasClass('classA') || elem.hasClass('classB'). A note on this one: order matters! If the class 'classA' is more likely to be found, list it first! OR condition statements return as soon as one of them is met.

The worst performance by far was using element.is('.class').

Also listed in the jsperf is CyberMonk's function, and Kolja's solution.

How do I find the location of my Python site-packages directory?

For Ubuntu,

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

...is not correct.

It will point you to /usr/lib/pythonX.X/dist-packages

This folder only contains packages your operating system has automatically installed for programs to run.

On ubuntu, the site-packages folder that contains packages installed via setup_tools\easy_install\pip will be in /usr/local/lib/pythonX.X/dist-packages

The second folder is probably the more useful one if the use case is related to installation or reading source code.

If you do not use Ubuntu, you are probably safe copy-pasting the first code box into the terminal.

How can I configure Logback to log different levels for a logger to different destinations?

Example of how to output colored messages of level "INFO" or higher to console and messages of level "WARN" or higher to file.

Your logback.xml file:

<?xml version="1.0" encoding="UTF-8"?>

<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>

            <!--output messages of exact level only-->
            <!--<onMatch>ACCEPT</onMatch>-->
            <!--<onMismatch>DENY</onMismatch>-->
        </filter>
        <encoder>
            <pattern>%d{yyyy-MMM-dd HH:mm:ss.SSS} [%thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n
            </pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>myfile.log</file>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>WARN</level>
        </filter>
        <append>true</append>
        <encoder>
            <pattern>%d{yyyy-MMM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE"/>
    </root>
</configuration>

Find and kill a process in one line using bash and regex

One liner:

ps aux | grep -i csp_build | awk '{print $2}' | xargs sudo kill -9

  • Print out column 2: awk '{print $2}'
  • sudo is optional
  • Run kill -9 5124, kill -9 5373 etc (kill -15 is more graceful but slightly slower)

Bonus:

I also have 2 shortcut functions defined in my .bash_profile (~/.bash_profile is for osx, you have to see what works for your *nix machine).

  1. p keyword
    • lists out all Processes containing keyword
    • usage e.g: p csp_build , p python etc

bash_profile code:

# FIND PROCESS
function p(){
        ps aux | grep -i $1 | grep -v grep
}
  1. ka keyword
    • Kills All processes that have this keyword
    • usage e.g: ka csp_build , ka python etc
    • optional kill level e.g: ka csp_build 15, ka python 9

bash_profile code:

# KILL ALL
function ka(){

    cnt=$( p $1 | wc -l)  # total count of processes found
    klevel=${2:-15}       # kill level, defaults to 15 if argument 2 is empty

    echo -e "\nSearching for '$1' -- Found" $cnt "Running Processes .. "
    p $1

    echo -e '\nTerminating' $cnt 'processes .. '

    ps aux  |  grep -i $1 |  grep -v grep   | awk '{print $2}' | xargs sudo kill -klevel
    echo -e "Done!\n"

    echo "Running search again:"
    p "$1"
    echo -e "\n"
}

Media query to detect if device is touchscreen

There is actually a property for this in the CSS4 media query draft.

The ‘pointer’ media feature is used to query about the presence and accuracy of a pointing device such as a mouse. If a device has multiple input mechanisms, it is recommended that the UA reports the characteristics of the least capable pointing device of the primary input mechanisms. This media query takes the following values:

‘none’
- The input mechanism of the device does not include a pointing device.

‘coarse’
- The input mechanism of the device includes a pointing device of limited accuracy.

‘fine’
- The input mechanism of the device includes an accurate pointing device.

This would be used as such:

/* Make radio buttons and check boxes larger if we have an inaccurate pointing device */
@media (pointer:coarse) {
    input[type="checkbox"], input[type="radio"] {
        min-width:30px;
        min-height:40px;
        background:transparent;
    }
}

I also found a ticket in the Chromium project related to this.

Browser compatibility can be tested at Quirksmode. These are my results (22 jan 2013):

  • Chrome/Win: Works
  • Chrome/iOS: Doesn't work
  • Safari/iOS6: Doesn't work

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

When i have carried my project on Xcode 11.1, i got that problem. That black screen problem may occur any presentation inter ViewControllers.

That answer helped me. Because modal presentation changed with iOS 13. If you don't get that problem before iOS 13, please try to add line below to your ViewController before its presentation;

viewController.modalPresentationStyle = .fullScreen

after your code may seem like below;

let vc = UIViewController()
vc.modalPresentationStyle = .fullScreen //or .overFullScreen for transparency
self.present(vc, animated: true, completion: nil)

Search input with an icon Bootstrap 4

you can also do in this way using input-group

<div class="input-group">
  <input class="form-control"
         placeholder="I can help you to find anything you want!">
  <div class="input-group-addon" ><i class="fa fa-search"></i></div>
</div>

codeply

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Be aware to use constant HTTPS or HTTP for all requests. I had the same error msg: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

What's the difference between subprocess Popen and call (how can I use them)?

The other answer is very complete, but here is a rule of thumb:

  • call is blocking:

    call('notepad.exe')
    print('hello')  # only executed when notepad is closed
    
  • Popen is non-blocking:

    Popen('notepad.exe')
    print('hello')  # immediately executed
    

How to check for an empty object in an AngularJS view

Try this:

angular.equals({}, $scope.card)

Add support library to Android Studio project

Android no longer downloading the libraries from the SDK manager, it has to be accessed through Google's Maven repository.

You will have to do something similar to this in your build.gradle file:

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}



dependencies {
    ...
    compile "com.android.support:support-core-utils:27.0.2"
}

Find more details about the setting up process here and about the different support library revisions here.

extract digits in a simple way from a python string

This regular expression handles floats as well

import re
re_float = re.compile(r'\d*\.?\d+')

You could also add a group to the expression that catches your weight units.

re_banana = re.compile(r'(?P<number>\d*\.?\d+)\s?(?P<uni>[a-zA-Z]+)')

You can access the named groups like this re_banana.match("200 kgm").group('number').

I think this should help you getting started.

Java how to sort a Linked List?

In java8 you no longer need to use Collections.sort method as LinkedList inherits the method sort from java.util.List, so adapting Fido's answer to Java8:

    LinkedList<String>list = new LinkedList<String>();
    list.add("abc");
    list.add("Bcd");
    list.add("aAb");

    list.sort( new Comparator<String>(){
    @Override
        public int compare(String o1,String o2){
            return Collator.getInstance().compare(o1,o2);
        }
    });

References:

http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html

http://docs.oracle.com/javase/7/docs/api/java/util/List.html

How to copy a file to another path?

I tried to copy an xml file from one location to another. Here is my code:

public void SaveStockInfoToAnotherFile()
{
    string sourcePath = @"C:\inetpub\wwwroot";
    string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
    string sourceFileName = "startingStock.xml";
    string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
    string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
    string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);

    if (!System.IO.Directory.Exists(destinationPath))
       {
         System.IO.Directory.CreateDirectory(destinationPath);
       }
    System.IO.File.Copy(sourceFile, destinationFile, true);
}

Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.

How to multiply individual elements of a list with a number?

You can use built-in map function:

result = map(lambda x: x * P, S)

or list comprehensions that is a bit more pythonic:

result = [x * P for x in S]

What do all of Scala's symbolic operators mean?

Scala inherits most of Java's arithmetic operators. This includes bitwise-or | (single pipe character), bitwise-and &, bitwise-exclusive-or ^, as well as logical (boolean) or || (two pipe characters) and logical-and &&. Interestingly, you can use the single character operators on boolean, so the java'ish logical operators are totally redundant:

true && true   // valid
true & true    // valid as well

3 & 4          // bitwise-and (011 & 100 yields 000)
3 && 4         // not valid

As pointed out in another post, calls ending in an equals sign =, are resolved (if a method with that name does not exist!) by a reassignment:

var x = 3
x += 1         // `+=` is not a method in `int`, Scala makes it `x = x + 1`

This 'double-check' makes it possible, to easily exchange a mutable for an immutable collection:

val m = collection.mutable.Set("Hallo")   // `m` a val, but holds mutable coll
var i = collection.immutable.Set("Hallo") // `i` is a var, but holds immutable coll

m += "Welt" // destructive call m.+=("Welt")
i += "Welt" // re-assignment i = i + "Welt" (creates a new immutable Set)

How to open select file dialog via js?

JS only - no need for jquery

Simply create an input element and trigger the click.

var input = document.createElement('input');
input.type = 'file';
input.click();

This is the most basic, pop a select-a-file dialog, but its no use for anything without handling the selected file...

Handling the files

Adding an onchange event to the newly created input would allow us to do stuff once the user has selected the file.

var input = document.createElement('input');
input.type = 'file';

input.onchange = e => { 
   var file = e.target.files[0]; 
}

input.click();

At the moment we have the file variable storing various information :

file.name // the file's name including extension
file.size // the size in bytes
file.type // file type ex. 'application/pdf'

Great!

But, what if we need the content of the file?

In order to get to the actual content of the file, for various reasons. place an image, load into canvas, create a window with Base64 data url, etc. we would need to use the FileReader API

We would create an instance of the FileReader, and load our user selected file reference to it.

var input = document.createElement('input');
input.type = 'file';

input.onchange = e => { 

   // getting a hold of the file reference
   var file = e.target.files[0]; 

   // setting up the reader
   var reader = new FileReader();
   reader.readAsText(file,'UTF-8');

   // here we tell the reader what to do when it's done reading...
   reader.onload = readerEvent => {
      var content = readerEvent.target.result; // this is the content!
      console.log( content );
   }

}

input.click();

Trying pasting the above code into your devtool's console window, it should produce a select-a-file dialog, after selecting the file, the console should now print the contents of the file.

Example - "Stackoverflow's new background image!"

Let's try to create a file select dialog to change stackoverflows background image to something more spicy...

var input = document.createElement('input');
input.type = 'file';

input.onchange = e => { 

   // getting a hold of the file reference
   var file = e.target.files[0]; 

   // setting up the reader
   var reader = new FileReader();
   reader.readAsDataURL(file); // this is reading as data url

   // here we tell the reader what to do when it's done reading...
   reader.onload = readerEvent => {
      var content = readerEvent.target.result; // this is the content!
      document.querySelector('#content').style.backgroundImage = 'url('+ content +')';
   }

}

input.click();

open devtools, and paste the above code into console window, this should pop a select-a-file dialog, upon selecting an image, stackoverflows content box background should change to the image selected.

Cheers!

Your branch is ahead of 'origin/master' by 3 commits

Came across this issue after I merged a pull request on Bitbucket.

Had to do

git fetch

and that was it.

MS Access: how to compact current database in VBA

Try this. It works on the same database in which the code resides. Just call the CompactDB() function shown below. Make sure that after you add the function, you click the Save button in the VBA Editor window prior to running for the first time. I only tested it in Access 2010. Ba-da-bing, ba-da-boom.

Public Function CompactDB()

    Dim strWindowTitle As String

    On Error GoTo err_Handler

    strWindowTitle = Application.Name & " - " & Left(Application.CurrentProject.Name, Len(Application.CurrentProject.Name) - 4)
    strTempDir = Environ("Temp")
    strScriptPath = strTempDir & "\compact.vbs"
    strCmd = "wscript " & """" & strScriptPath & """"

    Open strScriptPath For Output As #1
    Print #1, "Set WshShell = WScript.CreateObject(""WScript.Shell"")"
    Print #1, "WScript.Sleep 1000"
    Print #1, "WshShell.AppActivate " & """" & strWindowTitle & """"
    Print #1, "WScript.Sleep 500"
    Print #1, "WshShell.SendKeys ""%yc"""
    Close #1

    Shell strCmd, vbHide
    Exit Function

    err_Handler:
    MsgBox "Error " & Err.Number & ": " & Err.Description
    Close #1

End Function

Reset par to the default values at startup

Every time a new device is opened par() will reset, so another option is simply do dev.off() and continue.

Using a scanner to accept String input and storing in a String Array

Please correct me if I'm wrong.`

public static void main(String[] args) {

    Scanner na = new Scanner(System.in);
    System.out.println("Please enter the number of contacts: ");
    int num = na.nextInt();

    String[] contactName = new String[num];
    String[] contactPhone = new String[num];
    String[] contactAdd1 = new String[num];
    String[] contactAdd2 = new String[num];

    Scanner input = new Scanner(System.in);

    for (int i = 0; i < num; i++) {

        System.out.println("Enter contacts name: " + (i+1));
        contactName[i] = input.nextLine();

        System.out.println("Enter contacts addressline1: " + (i+1));
        contactAdd1[i] = input.nextLine();

        System.out.println("Enter contacts addressline2: " + (i+1));
        contactAdd2[i] = input.nextLine();

        System.out.println("Enter contact phone number: " + (i+1));
        contactPhone[i] = input.nextLine();

    }

    for (int i = 0; i < num; i++) {
        System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
        System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
        System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
        System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
    }
}

`

Removing legend on charts with chart.js v2

The options object can be added to the chart when the new Chart object is created.

var chart1 = new Chart(canvas, {
    type: "pie",
    data: data,
    options: {
         legend: {
            display: false
         },
         tooltips: {
            enabled: false
         }
    }
});

Basic text editor in command prompt?

In a pinch, just type 'notepad (filename)' and notepad will pop up with the file you want to edit in it. Otherwise Vim or some such will have to be installed.

How do I display local image in markdown?

Solution for Unix-like operating system.

STEP BY STEP :
  1. Create a directory named like Images and put all the images that will be rendered by the Markdown.

  2. For example, put example.png into Images.

  3. To load example.png that was located under the Images directory before.

![title](Images/example.png)

Note : Images directory must be located under the same directory of your markdown text file which has .md extension.

Type of expression is ambiguous without more context Swift

I had this message when the type of a function parameter didn't fit. In my case it was a String instead of an URL.

Apache: The requested URL / was not found on this server. Apache

Try changing Deny from all to Allow from all in your conf and see if that helps.

Example on ToggleButton

Just remove the line toggle.toggle(); from your click listener toggle() method will always reset your toggle button value.

And as you are trying to take the value of EditText in string variable which always remains same as you are getting value in onCreate() so better directly use the EditText to get the value of it in your onClick listener.

Just change your code as below its working fine now.

  btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
                       //toggle.toggle();
            if ( ed.getText().toString().equalsIgnoreCase("1")) {

                toggle.setTextOff("TOGGLE ON");
                toggle.setChecked(true);
            } else if ( ed.getText().toString().equalsIgnoreCase("0")) {

                toggle.setTextOn("TOGGLE OFF");
                toggle.setChecked(false);

            }
        }
    });

When to use Comparable and Comparator

Use Comparable:

  • if the object is in your control.
  • if the comparing behaviour is the main comparing behaviour.

Use Comparator :

  • if the object is outside your control and you cannot make them implement Comparable.
  • when you want comparing behaviour different from the default (which is specified by Comparable) behaviour.

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

Combine [NgStyle] With Condition (if..else)

Use:

[ngStyle]="{'background-image': 'url(' +1=1 ? ../../assets/img/emp-user.png : ../../assets/img/emp-default.jpg + ')'}"

IDEA: javac: source release 1.7 requires target release 1.7

check .idea/misc.xml sometimes you need to change languageLevel="JDK_1_X" attribute manually

How can I quantify difference between two images?

A trivial thing to try:

Resample both images to small thumbnails (e.g. 64 x 64) and compare the thumbnails pixel-by-pixel with a certain threshold. If the original images are almost the same, the resampled thumbnails will be very similar or even exactly the same. This method takes care of noise that can occur especially in low-light scenes. It may even be better if you go grayscale.

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])

Can you call ko.applyBindings to bind a partial view?

I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/

The interesting bit is that I apply the data-bind attribute to an element I didn't define:

    var handle = slider.slider().find(".ui-slider-handle").first();
    $(handle).attr("data-bind", "tooltip: viewModel.value");
    ko.applyBindings(viewModel.value, $(handle)[0]);

How to find specified name and its value in JSON-string from Java?

Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.

import com.google.gson.Gson;

public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"name\":\"John\"," + 
      "\"age\":\"20\"," + 
      "\"address\":\"some address\"," + 
      "\"someobject\":" +
      "{" + 
        "\"field\":\"value\"" + 
      "}" + 
    "}";

  String age;

  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Foo thing = gson.fromJson(jsonInput, Foo.class);
    if (thing.age != null)
    {
      System.out.println("age is " + thing.age);
    }
    else
    {
      System.out.println("age element not present or value is null");
    }
  }
}

How to build and fill pandas dataframe from for loop?

Make a list of tuples with your data and then create a DataFrame with it:

d = []
for p in game.players.passing():
    d.append((p, p.team, p.passer_rating()))

pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))

A list of tuples should have less overhead than a list dictionaries. I tested this below, but please remember to prioritize ease of code understanding over performance in most cases.

Testing functions:

def with_tuples(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append((x-1, x, x+1))

    return pd.DataFrame(res, columns=("a", "b", "c"))

def with_dict(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append({"a":x-1, "b":x, "c":x+1})

    return pd.DataFrame(res)

Results:

%timeit -n 10 with_tuples()
# 10 loops, best of 3: 55.2 ms per loop

%timeit -n 10 with_dict()
# 10 loops, best of 3: 130 ms per loop

What does "Table does not support optimize, doing recreate + analyze instead" mean?

OPTIMIZE TABLE works fine with InnoDB engine according to the official support article : http://dev.mysql.com/doc/refman/5.5/en/optimize-table.html

You'll notice that optimize InnoDB tables will rebuild table structure and update index statistics (something like ALTER TABLE).

Keep in mind that this message could be an informational mention only and the very important information is the status of your query : just OK !

mysql> OPTIMIZE TABLE foo;
+----------+----------+----------+-------------------------------------------------------------------+
| Table    | Op       | Msg_type | Msg_text                                                          |
+----------+----------+----------+-------------------------------------------------------------------+
| test.foo | optimize | note     | Table does not support optimize, doing recreate + analyze instead |
| test.foo | optimize | status   | OK                                                                |
+----------+----------+----------+-------------------------------------------------------------------+

How can I generate a 6 digit unique number?

Here's another one:

substr(number_format(time() * rand(),0,'',''),0,6);

mongodb how to get max value from collections

The performance of the suggested answer is fine. According to the MongoDB documentation:

When a $sort immediately precedes a $limit, the optimizer can coalesce the $limit into the $sort. This allows the sort operation to only maintain the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory.

Changed in version 4.0.

So in the case of

db.collection.find().sort({age:-1}).limit(1)

we get only the highest element WITHOUT sorting the collection because of the mentioned optimization.

How to find top three highest salary in emp table in oracle?

solution for to find top 5 salary in sq l server

select top(1) name, salary from salary where salary in(select distinct top(3) salary from salary order by salary disc)

EF 5 Enable-Migrations : No context type was found in the assembly

use -ProjectName option in Package Manager Console:

Enable-Migrations -ProjectName Toombu.DataAccess -StartUpProjectName Toombu.Web -Verbose

How to see local history changes in Visual Studio Code?

Basic Functionality

  • Automatically saved local edit history is available with the Local History extension.
  • Manually saved local edit history is available with the Checkpoints extension (this is the IntelliJ equivalent to adding tags to the local history).

Advanced Functionality

  • None of the extensions mentioned above support edit history when a file is moved or renamed.
  • The extensions above only support edit history. They do not support move/delete history, for example, like IntelliJ does.

Open Request

If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.

Mongoose query where value is not null

total count the documents where the value of the field is not equal to the specified value.

async function getRegisterUser() {
    return Login.count({"role": { $ne: 'Super Admin' }}, (err, totResUser) => {
        if (err) {
            return err;
        }
        return totResUser;
    })
}

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Sergey is correct, but if you need to get a response from your home-spun dialog(s) for evaluation in the same block of code that invoked it, you should use .showAndWait(), not .show(). Here's my rendition of a couple of the dialog types that are provided in Swing's OptionPane:

public class FXOptionPane {

public enum Response { NO, YES, CANCEL };

private static Response buttonSelected = Response.CANCEL;

private static ImageView icon = new ImageView();

static class Dialog extends Stage {
    public Dialog( String title, Stage owner, Scene scene, String iconFile ) {
        setTitle( title );
        initStyle( StageStyle.UTILITY );
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        setResizable( false );
        setScene( scene );
        icon.setImage( new Image( getClass().getResourceAsStream( iconFile ) ) );
    }
    public void showDialog() {
        sizeToScene();
        centerOnScreen();
        showAndWait();
    }
}

static class Message extends Text {
    public Message( String msg ) {
        super( msg );
        setWrappingWidth( 250 );
    }
}

public static Response showConfirmDialog( Stage owner, String message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Confirm.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button yesButton = new Button( "Yes" );
    yesButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.YES;
        }
    } );
    Button noButton = new Button( "No" );
    noButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.NO;
        }
    } );
    BorderPane bp = new BorderPane();
    HBox buttons = new HBox();
    buttons.setAlignment( Pos.CENTER );
    buttons.setSpacing( 10 );
    buttons.getChildren().addAll( yesButton, noButton );
    bp.setCenter( buttons );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, new Message( message ) );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
    return buttonSelected;
}

public static void showMessageDialog( Stage owner, String message, String title ) {
    showMessageDialog( owner, new Message( message ), title );
}
public static void showMessageDialog( Stage owner, Node message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Info.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button okButton = new Button( "OK" );
    okButton.setAlignment( Pos.CENTER );
    okButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
        }
    } );
    BorderPane bp = new BorderPane();
    bp.setCenter( okButton );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, message );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
}

}

Could not load file or assembly ... The parameter is incorrect

This can happen while referencing COM wrapper dlls. Within your Visual Studio Project, under References, select the COM wrapper dlls being referenced and ensure they have the the following property values: "Embed Interop Types": False and "Specific Version": False.

Button inside of anchor link works in Firefox but not in Internet Explorer?

The problem here is that the link sits behind the button, even when changing the z-index. This markup is also invalid (read the spec). So the reason the links dont work is because you are actually clicking the button and not the link. The solution is to change your markup around.

<button type="button"><a href="yourlink">Link</a></button>

Then style as needed. A demo is here.

How to find tag with particular text with Beautiful Soup?

A solution for finding a anchor tag if having a particular keyword would be the following:

from bs4 import BeautifulSoup
from urllib.request import urlopen,Request
from urllib.parse import urljoin,urlparse

rawLinks=soup.findAll('a',href=True)
for link in rawLinks:
    innercontent=link.text
    if keyword.lower() in innercontent.lower():
        print(link)

Differences between SP initiated SSO and IDP initiated SSO

In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.

Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html

paint() and repaint() in Java

Difference between Paint() and Repaint() method

Paint():

This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.

Repaint():

This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.

momentJS date string add 5 days

The function add() returns the old date, but changes the original date :)

startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days');
alert(new_date);

How to make a JSON call to a url?

It seems they offer a js option for the format parameter, which will return JSONP. You can retrieve JSONP like so:

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
    console.log(data);
});  

nil detection in Go

The compiler is pointing the error to you, you're comparing a structure instance and nil. They're not of the same type so it considers it as an invalid comparison and yells at you.

What you want to do here is to compare a pointer to your config instance to nil, which is a valid comparison. To do that you can either use the golang new builtin, or initialize a pointer to it:

config := new(Config) // not nil

or

config := &Config{
                  host: "myhost.com", 
                  port: 22,
                 } // not nil

or

var config *Config // nil

Then you'll be able to check if

if config == nil {
    // then
}

How can I sort a List alphabetically?

//Here is sorted List alphabetically with syncronized
package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
/**
* 
* @author manoj.kumar
*/
public class SynchronizedArrayList {
static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
@SuppressWarnings("unchecked")
public static void main(String[] args) {

List<Employee> synchronizedList = Collections.synchronizedList(new ArrayList<Employee>());
synchronizedList.add(new Employee("Aditya"));
synchronizedList.add(new Employee("Siddharth"));
synchronizedList.add(new Employee("Manoj"));
Collections.sort(synchronizedList, new Comparator() {
public int compare(Object synchronizedListOne, Object synchronizedListTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((Employee)synchronizedListOne).name
.compareTo(((Employee)synchronizedListTwo).name);
}
}); 
/*for( Employee sd : synchronizedList) {
log.info("Sorted Synchronized Array List..."+sd.name);
}*/

// when iterating over a synchronized list, we need to synchronize access to the synchronized list
synchronized (synchronizedList) {
Iterator<Employee> iterator = synchronizedList.iterator();
while (iterator.hasNext()) {
log.info("Sorted Synchronized Array List Items: " + iterator.next().name);
}
}

}
}
class Employee {
String name;
Employee (String name) {
this.name = name;

}
}

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

If you want to include the column that is the current identity, you can still do that but you have to explicitly list the columns and cast the current identity to an int (assuming it is one now), like so:

select cast (CurrentID as int) as CurrentID, SomeOtherField, identity(int) as TempID 
into #temp
from myserver.dbo.mytable

Rename a file using Java

This is an easy way to rename a file:

        File oldfile =new File("test.txt");
        File newfile =new File("test1.txt");

        if(oldfile.renameTo(newfile)){
            System.out.println("File renamed");
        }else{
            System.out.println("Sorry! the file can't be renamed");
        }

new Runnable() but no new thread?

The Runnable interface is another way in which you can implement multi-threading other than extending the Thread class due to the fact that Java allows you to extend only one class.

You can however, use the new Thread(Runnable runnable) constructor, something like this:

private Thread thread = new Thread(new Runnable() {
public void run() {
   final long start = mStartTime;
   long millis = SystemClock.uptimeMillis() - start;
   int seconds = (int) (millis / 1000);
   int minutes = seconds / 60;
   seconds     = seconds % 60;

   if (seconds < 10) {
       mTimeLabel.setText("" + minutes + ":0" + seconds);
   } else {
       mTimeLabel.setText("" + minutes + ":" + seconds);            
   }

   mHandler.postAtTime(this,
           start + (((minutes * 60) + seconds + 1) * 1000));
   }
});

thread.start();

How to replace multiple strings in a file using PowerShell

To get the post by George Howarth working properly with more than one replacement you need to remove the break, assign the output to a variable ($line) and then output the variable:

$lookupTable = @{
    'something1' = 'something1aa'
    'something2' = 'something2bb'
    'something3' = 'something3cc'
    'something4' = 'something4dd'
    'something5' = 'something5dsf'
    'something6' = 'something6dfsfds'
}

$original_file = 'path\filename.abc'
$destination_file =  'path\filename.abc.new'

Get-Content -Path $original_file | ForEach-Object {
    $line = $_

    $lookupTable.GetEnumerator() | ForEach-Object {
        if ($line -match $_.Key)
        {
            $line = $line -replace $_.Key, $_.Value
        }
    }
   $line
} | Set-Content -Path $destination_file

Passing an array as an argument to a function in C

Arrays in C are converted, in most of the cases, to a pointer to the first element of the array itself. And more in detail arrays passed into functions are always converted into pointers.

Here a quote from K&R2nd:

When an array name is passed to a function, what is passed is the location of the initial element. Within the called function, this argument is a local variable, and so an array name parameter is a pointer, that is, a variable containing an address.

Writing:

void arraytest(int a[])

has the same meaning as writing:

void arraytest(int *a)

So despite you are not writing it explicitly it is as you are passing a pointer and so you are modifying the values in the main.

For more I really suggest reading this.

Moreover, you can find other answers on SO here

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

This command with --user 0 do the job:

adb uninstall --user 0 <package_name>

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

you can try something like this, or just copy and past below piece.

boolean exception = true;
Charset charset = Charset.defaultCharset(); //Try the default one first.        
int index = 0;

while(exception) {
    try {
        lines = Files.readAllLines(f.toPath(),charset);
          for (String line: lines) {
              line= line.trim();
              if(line.contains(keyword))
                  values.add(line);
              }           
        //No exception, just returns
        exception = false; 
    } catch (IOException e) {
        exception = true;
        //Try the next charset
        if(index<Charset.availableCharsets().values().size())
            charset = (Charset) Charset.availableCharsets().values().toArray()[index];
        index ++;
    }
}

Getting an option text/value with JavaScript

var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

Creating an Arraylist of Objects

How to Creating an Arraylist of Objects.

Create an array to store the objects:

ArrayList<MyObject> list = new ArrayList<MyObject>();

In a single step:

list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list. 

or

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.

How to create an android app using HTML 5

Here is a starting point for developing Android apps with HTML5. The HTML code will be stored in the "assets/www" folder in your Android project.

https://github.com/jakewp11/HTML5_Android_Template.git

How to check if a date is in a given range?

Use the DateTime class if you have PHP 5.3+. Easier to use, better functionality.

DateTime internally supports timezones, with the other solutions is up to you to handle that.

<?php    
/**
 * @param DateTime $date Date that is to be checked if it falls between $startDate and $endDate
 * @param DateTime $startDate Date should be after this date to return true
 * @param DateTime $endDate Date should be before this date to return true
 * return bool
 */
function isDateBetweenDates(DateTime $date, DateTime $startDate, DateTime $endDate) {
    return $date > $startDate && $date < $endDate;
}

$fromUser = new DateTime("2012-03-01");
$startDate = new DateTime("2012-02-01 00:00:00");
$endDate = new DateTime("2012-04-30 23:59:59");

echo isDateBetweenDates($fromUser, $startDate, $endDate);

Google reCAPTCHA: How to get user response and validate in the server side?

A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.

Check the success field for true or false

private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
    JsonObject jsonObject = null;
    URLConnection connection = null;
    InputStream is = null;
    String charset = java.nio.charset.StandardCharsets.UTF_8.name();

    String url = "https://www.google.com/recaptcha/api/siteverify";
    try {            
        String query = String.format("secret=%s&response=%s&remoteip=%s", 
        URLEncoder.encode(secret, charset), 
        URLEncoder.encode(response, charset),
        URLEncoder.encode(remoteip, charset));

        connection = new URL(url + "?" + query).openConnection();
        is = connection.getInputStream();
        JsonReader rdr = Json.createReader(is);
        jsonObject = rdr.readObject();

    } catch (IOException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }

        }
    }
    return jsonObject;
}

What killed my process and why?

If the user or sysadmin did not kill the program the kernel may have. The kernel would only kill a process under exceptional circumstances such as extreme resource starvation (think mem+swap exhaustion).

Check if starting characters of a string are alphabetical in T-SQL

You don't need to use regex, LIKE is sufficient:

WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'

Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.

Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]. [a-z] may exclude A or Z. [A-Z] may exclude a or z.

Inserting image into IPython notebook markdown

Files inside the notebook dir are available under a "files/" url. So if it's in the base path, it would be <img src="files/image.png">, and subdirs etc. are also available: <img src="files/subdir/image.png">, etc.

Update: starting with IPython 2.0, the files/ prefix is no longer needed (cf. release notes). So now the solution <img src="image.png"> simply works as expected.

Relative instead of Absolute paths in Excel VBA

Here's my quick and simple function for getting the absolute path from a relative path.

The difference from the accepted answer is that this function can handle relative paths that moves up to parent folders.

Example:

Workbooks.Open FileName:=GetAbsolutePath("..\..\TRICATEndurance Summary.html")

Code:

' Gets an absolute path from a relative path in the active workbook
Public Function GetAbsolutePath(relativePath As String) As String
    
    Dim absPath As String
    Dim pos As Integer
    
    absPath = ActiveWorkbook.Path
    
    ' Make sure paths are in correct format
    relativePath = Replace(relativePath, "/", "\")
    absPath = Replace(absPath, "/", "\")
    
    Do While Left$(relativePath, 3) = "..\"
    
        ' Remove level from relative path
        relativePath = Mid$(relativePath, 4)
        
        ' Remove level from absolute path
        pos = InStrRev(absPath, "\")
        absPath = Left$(absPath, pos - 1)
    
    Loop
    
    GetAbsolutePath = PathCombine(absPath, relativePath)
    
End Function

HttpClient - A task was cancelled?

Another reason can be that if you are running the service (API) and put a breakpoint in the service (and your code is stuck at some breakpoint (e.g Visual Studio solution is showing Debugging instead of Running)). and then hitting the API from the client code. So if the service code a paused on some breakpoint, you just hit F5 in VS.

Use SELECT inside an UPDATE query

I did want to add one more answer that utilizes a VBA function, but it does get the job done in one SQL statement. Though, it can be slow.

UPDATE FUNCTIONS
SET FUNCTIONS.Func_TaxRef = DLookUp("MinOfTax_Code", "SELECT
FUNCTIONS.Func_ID,Min(TAX.Tax_Code) AS MinOfTax_Code
FROM TAX, FUNCTIONS
WHERE (((FUNCTIONS.Func_Pure)<=[Tax_ToPrice]) AND ((FUNCTIONS.Func_Year)=[Tax_Year]))
GROUP BY FUNCTIONS.Func_ID;", "FUNCTIONS.Func_ID=" & Func_ID)

Determine if Python is running inside virtualenv

(edited) I found that way, what do you think of it ? (it also returns the venv base path and works even for readthedocs where checking the env variable does not):

import os
import sys
from distutils.sysconfig import get_config_vars


def get_venv_basedir():
    """Returns the base directory of the virtualenv, useful to read configuration and plugins"""

    exec_prefix = get_config_vars()['exec_prefix']

    if hasattr(sys, 'real_prefix') is False or exec_prefix.startswith(sys.real_prefix):
        raise EnvironmentError('You must be in a virtual environment')

    return os.path.abspath(get_config_vars()['exec_prefix'] + '/../')

How can I compile my Perl script so it can be executed on systems without perl installed?

pp can create an executable that includes perl and your script (and any module dependencies), but it will be specific to your architecture, so you couldn't run it on both Windows and linux for instance.

From its doc:

To make a stand-alone executable, suitable for running on a machine that doesn't have perl installed:

   % pp -o packed.exe source.pl        # makes packed.exe
   # Now, deploy 'packed.exe' to target machine...
   $ packed.exe                        # run it

(% and $ there are command prompts on different machines).

Bootstrap full responsive navbar with logo or brand name text

Just set the height and width where you are adding that logo. I tried and its working fine

MVC [HttpPost/HttpGet] for Action

Let's say you have a Login action which provides the user with a login screen, then receives the user name and password back after the user submits the form:

public ActionResult Login() {
    return View();
}

public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.

Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.

[HttpGet]
public ActionResult Login() {
    return View();
}

[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

You can also combine the request method attributes if your action serves requests from multiple verbs:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)].

Git commit with no commit message

And if you add an alias for it then it's even better right?

git config --global alias.nccommit 'commit -a --allow-empty-message -m ""'

Now you just do an nccommit, nc because of no comment, and everything should be commited.

Input and Output binary streams using JERSEY?

I managed to get a ZIP file or a PDF file by extending the StreamingOutput object. Here is some sample code:

@Path("PDF-file.pdf/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getPDF() throws Exception {
    return new StreamingOutput() {
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                PDFGenerator generator = new PDFGenerator(getEntity());
                generator.generatePDF(output);
            } catch (Exception e) {
                throw new WebApplicationException(e);
            }
        }
    };
}

The PDFGenerator class (my own class for creating the PDF) takes the output stream from the write method and writes to that instead of a newly created output stream.

Don't know if it's the best way to do it, but it works.

How do you pass view parameters when navigating from an action in JSF2?

You can do it using Primefaces like this :

<p:button 
      outcome="/page2.xhtml?faces-redirect=true&amp;id=#{myBean.id}">
</p:button>

What is this spring.jpa.open-in-view=true property in Spring Boot?

This property will register an OpenEntityManagerInViewInterceptor, which registers an EntityManager to the current thread, so you will have the same EntityManager until the web request is finished. It has nothing to do with a Hibernate SessionFactory etc.

Official way to ask jQuery wait for all images to load before executing something

This way you can execute an action when all images inside body or any other container (that depends of your selection) are loaded. PURE JQUERY, no pluggins needed.

var counter = 0;
var size = $('img').length;

$("img").load(function() { // many or just one image(w) inside body or any other container
    counter += 1;
    counter === size && $('body').css('background-color', '#fffaaa'); // any action
}).each(function() {
  this.complete && $(this).load();        
});

Reset MySQL root password using ALTER USER statement after install on Mac

Maybe try that ?

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('XXX');

or

SET PASSWORD FOR 'root'@'%' = PASSWORD('XXX');

Depending on which access you use.

(and not sure you should change yourself field names...)

https://dev.mysql.com/doc/refman/5.0/en/set-password.html

How to hide code from cells in ipython notebook visualized with nbviewer?

With all the solutions above even though you're hiding the code, you'll still get the [<matplotlib.lines.Line2D at 0x128514278>] crap above your figure which you probably don't want.

If you actually want to get rid of the input rather than just hiding it, I think the cleanest solution is to save your figures to disk in hidden cells, and then just including the images in Markdown cells using e.g. ![Caption](figure1.png).

RestSharp JSON Parameter Posting

If you have a List of objects, you can serialize them to JSON as follow:

List<MyObjectClass> listOfObjects = new List<MyObjectClass>();

And then use addParameter:

requestREST.AddParameter("myAssocKey", JsonConvert.SerializeObject(listOfObjects));

And you wil need to set the request format to JSON:

requestREST.RequestFormat = DataFormat.Json;

xampp MySQL does not start

If you have previously installed MySQL Workbench the problem is that another MySQL instance is running at 3306 port.

So uninstall MySQL and XAMPP and after that, reinstall only XAMPP.

This worked for me.

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

The possible reason is the context of the alert dialog. You may be finished that activity so its trying to open in that context but which is already closed. Try changing the context of that dialog to you first activity beacause it won't be finished till the end.

e.g

rather than this.

AlertDialog alertDialog = new AlertDialog.Builder(this).create();

try to use

AlertDialog alertDialog = new AlertDialog.Builder(FirstActivity.getInstance()).create();

How to determine the Boost version on a system?

Include #include <boost/version.hpp>

std::cout << "Using Boost "     
          << BOOST_VERSION / 100000     << "."  // major version
          << BOOST_VERSION / 100 % 1000 << "."  // minor version
          << BOOST_VERSION % 100                // patch level
          << std::endl;

Possible output: Using Boost 1.75.0

Tested with Boost 1.51.0 to 1.63, 1.71.0 and 1.75.0:

Find the maximum value in a list of tuples in Python

In addition to max, you can also sort:

>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)

Passing Objects By Reference or Value in C#

Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.

When you pass an instance as an argument to the method it passes the copy of the instance. Now, if the instance you pass is a value type(resides in the stack) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.

LINQ to Entities does not recognize the method

If anyone is looking for a VB.Net answer (as I was initially), here it is:

Public Function IsSatisfied() As Expression(Of Func(Of Charity, String, String, Boolean))

Return Function(charity, name, referenceNumber) (String.IsNullOrWhiteSpace(name) Or
                                                         charity.registeredName.ToLower().Contains(name.ToLower()) Or
                                                         charity.alias.ToLower().Contains(name.ToLower()) Or
                                                         charity.charityId.ToLower().Contains(name.ToLower())) And
                                                    (String.IsNullOrEmpty(referenceNumber) Or
                                                     charity.charityReference.ToLower().Contains(referenceNumber.ToLower()))
End Function

What is the worst real-world macros/pre-processor abuse you've ever come across?

The driver code for an ASIC I used about 10 years ago had a lot of sections that looked like:

int foo(state_t *state) {
    int a, b, rval;

    $
    if (state->thing == whatever) {
        $
        do_whatever(state);
    }
    // more code

    $
    return rval;
}

After a lot of head scratching we finally found the definition:

#if DEBUG
#define $ dolog("%s %d", __FILE__, __LINE__);
#else
#define $
#endif

This was hard to find, because none of the source files that used it had any include files. There was a file called top.c source file that looked like:

#include <namechanged.h>
#include <foo.c>
#include <bar.c>
#include <baz.c>

Sure enough, this was the only file referenced in the Makefile. Whenever you changed anything, you had to recompile everything. This was "to make the code faster".

How do I import a pre-existing Java project into Eclipse and get up and running?

I think you'll have to import the project via the file->import wizard:

http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse

It's not the last step, but it will start you on your way.

I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).

What is the maximum number of edges in a directed graph with n nodes?

Undirected is N^2. Simple - every node has N options of edges (himself included), total of N nodes thus N*N

Find if variable is divisible by 2

Please write the following code in your console:

var isEven = function(deep) {

  if (deep % 2 === 0) {
        return true;  
    }
    else {
        return false;    
    }
};
isEven(44);

Please Note: It will return true, if the entered number is even otherwise false.

SQL Server Express CREATE DATABASE permission denied in database 'master'

If you got the same error in Sql server 2008 management studio than below link will resolve this error after so much effort i found this link: http://social.msdn.microsoft.com/Forums/en-US/sqlexpress/thread/76fc84f9-437c-4e71-ba3d-3c9ae794a7c4/

PHP json_decode() returns NULL with valid JSON?

As stated by Jürgen Math using the preg_replace method listed by user2254008 fixed it for me as well.

This is not limited to Chrome, it appears to be a character set conversion issue (at least in my case, Unicode -> UTF8) This fixed all the issues i was having.

As a future node, the JSON Object i was decoding came from Python's json.dumps function. This in turn caused some other unsanitary data to make it across though it was easily dealt with.

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

How to enable file sharing for my app?

According to apple doc:

File-Sharing Support
File-sharing support lets apps make user data files available in iTunes 9.1 and later. An app that declares its support for file sharing makes the contents of its /Documents directory available to the user. The user can then move files in and out of this directory as needed from iTunes. This feature does not allow your app to share files with other apps on the same device; that behavior requires the pasteboard or a document interaction controller object.

To enable file sharing for your app, do the following:

  1. Add the UIFileSharingEnabled key to your app’s Info.plist file, and set the value of the key to YES. (The actual key name is "Application supports iTunes file sharing")

  2. Put whatever files you want to share in your app’s Documents directory.

  3. When the device is plugged into the user’s computer, iTunes displays a File Sharing section in the Apps tab of the selected device.

  4. The user can add files to this directory or move files to the desktop.

Apps that support file sharing should be able to recognize when files have been added to the Documents directory and respond appropriately. For example, your app might make the contents of any new files available from its interface. You should never present the user with the list of files in this directory and ask them to decide what to do with those files.

For additional information about the UIFileSharingEnabled key, see Information Property List Key Reference.

Using a RegEx to match IP addresses in Python

I came across the same situation, I found the answer with use of socket library helpful but it doesn't provide support for ipv6 addresses. Found a better way for it:

Unfortunately it Works for python3 only

import ipaddress

def valid_ip(address):
    try: 
        print ipaddress.ip_address(address)
        return True
    except:
        return False

print valid_ip('10.10.20.30')
print valid_ip('2001:DB8::1')
print valid_ip('gibberish')

Save and load MemoryStream to/from a file

Save into a file

Car car = new Car();
car.Name = "Some fancy car";
MemoryStream stream = Serializer.SerializeToStream(car);
System.IO.File.WriteAllBytes(fileName, stream.ToArray());

Load from a file

using (var stream = new MemoryStream(System.IO.File.ReadAllBytes(fileName)))
{
    Car car = (Car)Serializer.DeserializeFromStream(stream);
}

where

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Serialization
{
    public class Serializer
    {
        public static MemoryStream SerializeToStream(object o)
        {
            MemoryStream stream = new MemoryStream();
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, o);
            return stream;
        }

        public static object DeserializeFromStream(MemoryStream stream)
        {
            IFormatter formatter = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin);
            object o = formatter.Deserialize(stream);
            return o;
        }
    }
}

Originally the implementation of this class has been posted here

and

[Serializable]
public class Car
{
    public string Name;
}

How to know user has clicked "X" or the "Close" button?

if (this.DialogResult == DialogResult.Cancel)
        {

        }
        else
        {
            switch (e.CloseReason)
            {
                case CloseReason.UserClosing:
                    e.Cancel = true;
                    break;
            }
        }

if condition will execute when user clicks 'X' or close button on form. The else can be used when user clicks Alt+f4 for any other purpose

How to [recursively] Zip a directory in PHP?

Great solution but for my Windows I need make a modifications. Below the modify code

function Zip($source, $destination){

if (!extension_loaded('zip') || !file_exists($source)) {
    return false;
}

$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
    return false;
}

$source = str_replace('\\', '/', realpath($source));

if (is_dir($source) === true)
{
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($files as $file)
    {
        $file = str_replace('\\', '/', $file);

        // Ignore "." and ".." folders
        if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
            continue;

        if (is_dir($file) === true)
        {
            $zip->addEmptyDir(str_replace($source . '/', '', $file));
        }
        else if (is_file($file) === true)
        {

            $str1 = str_replace($source . '/', '', '/'.$file);
            $zip->addFromString($str1, file_get_contents($file));

        }
    }
}
else if (is_file($source) === true)
{
    $zip->addFromString(basename($source), file_get_contents($source));
}

return $zip->close();
}

how to make a specific text on TextView BOLD

Here is my complete solution for dynamic String values with case check.

/**
 * Makes a portion of String formatted in BOLD.
 *
 * @param completeString       String from which a portion needs to be extracted and formatted.<br> eg. I am BOLD.
 * @param targetStringToFormat Target String value to format. <br>eg. BOLD
 * @param matchCase Match by target character case or not. If true, BOLD != bold
 * @return A string with a portion formatted in BOLD. <br> I am <b>BOLD</b>.
 */
public static SpannableStringBuilder formatAStringPortionInBold(String completeString, String targetStringToFormat, boolean matchCase) {
    //Null complete string return empty
    if (TextUtils.isEmpty(completeString)) {
        return new SpannableStringBuilder("");
    }

    SpannableStringBuilder str = new SpannableStringBuilder(completeString);
    int start_index = 0;

    //if matchCase is true, match exact string
    if (matchCase) {
        if (TextUtils.isEmpty(targetStringToFormat) || !completeString.contains(targetStringToFormat)) {
            return str;
        }

        start_index = str.toString().indexOf(targetStringToFormat);
    } else {
        //else find in lower cases
        if (TextUtils.isEmpty(targetStringToFormat) || !completeString.toLowerCase().contains(targetStringToFormat.toLowerCase())) {
            return str;
        }

        start_index = str.toString().toLowerCase().indexOf(targetStringToFormat.toLowerCase());
    }

    int end_index = start_index + targetStringToFormat.length();
    str.setSpan(new StyleSpan(BOLD), start_index, end_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return str;
}

Eg. completeString = "I am BOLD"

CASE I if *targetStringToFormat* = "bold" and *matchCase* = true

returns "I am BOLD" (since bold != BOLD)

CASE II if *targetStringToFormat* = "bold" and *matchCase* = false

returns "I am BOLD"

To Apply:

myTextView.setText(formatAStringPortionInBold("I am BOLD", "bold", false))

Hope that helps!

Adding three months to a date in PHP

The following should work, but you may need to change the format:

echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));

How to provide animation when calling another activity in Android?

You must use OverridePendingTransition method to achieve it, which is in the Activity class. Sample Animations in the apidemos example's res/anim folder. Check it. More than check the demo in ApiDemos/App/Activity/animation.

Example:

@Override
public void onResume(){
    // TODO LC: preliminary support for views transitions
    this.overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}

What is the difference between XAMPP or WAMP Server & IIS?

WAMP: acronym for Windows Operating System, Apache(Web server), MySQL Database and PHP Language.

XAMPP: acronym for X (any Operating System), Apache (Web server), MySQL Database, PHP Language and PERL.


XAMPP and WampServer are both free packages of WAMP, with additional applications/tools, put together by different people.

Their differences are in the format/structure of the package, the configurations, and the included management applications.

In short: XAMPP supports more OSes and includes more features

Conversion failed when converting the varchar value 'simple, ' to data type int

If you are converting a varchar to int make sure you do not have decimal places.

For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem.

CONVERT(int, replace(FIELD_NAME,'.0',''))

How to fit in an image inside span tag?

Try using a div tag and block for span!

<div>
  <span style="padding-right:3px; padding-top: 3px; display:block;">
    <img class="manImg" src="images/ico_mandatory.gif"></img>
  </span>
</div>

Google Chrome "window.open" workaround?

menubar must no, or 0, for Google Chrome to open in new window instead of tab.

Jquery href click - how can I fire up an event?

Try:

$(document).ready(function(){
   $('a .sign_new').click(function(){
      alert('Sign new href executed.'); 
   }); 
});

You've mixed up the class and href names / selector type.

Sites not accepting wget user agent header

You need to set both the user-agent and the referer:

 wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer  connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip

Iterate a certain number of times without storing the iteration number anywhere

This will print 'hello' 3 times without storing i...

[print('hello') for i in range(3)]

get index of DataTable column with name

You can simply use DataColumnCollection.IndexOf

So that you can get the index of the required column by name then use it with your row:

row[dt.Columns.IndexOf("ColumnName")] = columnValue;

Locking pattern for proper use of .NET MemoryCache

Console example of MemoryCache, "How to save/get simple class objects"

Output after launching and pressing Any key except Esc :

Saving to cache!
Getting from cache!
Some1
Some2

    class Some
    {
        public String text { get; set; }

        public Some(String text)
        {
            this.text = text;
        }

        public override string ToString()
        {
            return text;
        }
    }

    public static MemoryCache cache = new MemoryCache("cache");

    public static string cache_name = "mycache";

    static void Main(string[] args)
    {

        Some some1 = new Some("some1");
        Some some2 = new Some("some2");

        List<Some> list = new List<Some>();
        list.Add(some1);
        list.Add(some2);

        do {

            if (cache.Contains(cache_name))
            {
                Console.WriteLine("Getting from cache!");
                List<Some> list_c = cache.Get(cache_name) as List<Some>;
                foreach (Some s in list_c) Console.WriteLine(s);
            }
            else
            {
                Console.WriteLine("Saving to cache!");
                cache.Set(cache_name, list, DateTime.Now.AddMinutes(10));                   
            }

        } while (Console.ReadKey(true).Key != ConsoleKey.Escape);

    }

Change MySQL root password in phpMyAdmin

I had to do 2 steps:

  • follow Tiep Phan solution ... edit config.inc.php file ...

  • follow Mahmoud Zalt solution ... change password within phpmyadmin

Numpy: Divide each row by a vector element

Pythonic way to do this is ...

np.divide(data.T,vector).T

This takes care of reshaping and also the results are in floating point format. In other answers results are in rounded integer format.

#NOTE: No of columns in both data and vector should match

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

load iframe in bootstrap modal

$('.modal').on('shown.bs.modal',function(){      //correct here use 'shown.bs.modal' event which comes in bootstrap3
  $(this).find('iframe').attr('src','http://www.google.com')
})

As shown above use 'shown.bs.modal' event which comes in bootstrap 3.

EDIT :-

and just try to open some other url from iframe other than google.com ,it will not allow you to open google.com due to some security threats.

The reason for this is, that Google is sending an "X-Frame-Options: SAMEORIGIN" response header. This option prevents the browser from displaying iFrames that are not hosted on the same domain as the parent page.

Change size of text in text input tag?

This works, too.

<input style="width:300px; height:55px; font-size:50px;" />

A CSS stylesheet looks better though, and can easily be used over multiple pages.

Eclipse Intellisense?

I once had the same problem, and then I searched and found this and it worked for me:

I had got some of the boxes unchecked, so I checked them again, then it worked. Just go to

Windows > Preferences > Java > Editor > Content Assist > Advanced

and check the boxes which you want .

How to commit changes to a new branch

If I understand right, you've made a commit to changed_branch and you want to copy that commit to other_branch? Easy:

git checkout other_branch
git cherry-pick changed_branch

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

How do I push a new local branch to a remote Git repository and track it too?

Simply put, to create a new local branch, do:

git branch <branch-name>

To push it to the remote repository, do:

git push -u origin <branch-name>

how to check confirm password field in form without reloading page

try using jquery like this

$('input[type=submit]').click(function(e){
if($("#password").val() == "")
{
alert("please enter password");
return false;
}
});

also add this line in head of html

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

how to read value from string.xml in android?

Solution 1

Context context;
String mess = context.getString(R.string.mess_1)

Solution 2

String mess = getString(R.string.mess_1)

What exactly does += do in python?

x += 5 is not exactly the same as saying x = x + 5 in Python.

Note here:

In [1]: x = [2, 3, 4]    
In [2]: y = x    
In [3]: x += 7, 8, 9    
In [4]: x
Out[4]: [2, 3, 4, 7, 8, 9]    
In [5]: y
Out[5]: [2, 3, 4, 7, 8, 9]    
In [6]: x += [44, 55]    
In [7]: x
Out[7]: [2, 3, 4, 7, 8, 9, 44, 55]    
In [8]: y
Out[8]: [2, 3, 4, 7, 8, 9, 44, 55]    
In [9]: x = x + [33, 22]    
In [10]: x
Out[10]: [2, 3, 4, 7, 8, 9, 44, 55, 33, 22]    
In [11]: y
Out[11]: [2, 3, 4, 7, 8, 9, 44, 55]

See for reference: Why does += behave unexpectedly on lists?

IIS7 Settings File Locations

Also check this answer from here: Cannot manually edit applicationhost.config

The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.

So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.

How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.

Maximum length for MD5 input/output

You can have any length, but of course, there can be a memory issue on the computer if the String input is too long. The output is always 32 characters.

How to send FormData objects with Ajax-requests in jQuery?

Instead of - fd.append( 'userfile', $('#userfile')[0].files[0]);

Use - fd.append( 'file', $('#userfile')[0].files[0]);

Vim 80 column layout concerns

Well, looking at the :help columns, it's not really being made to mess with.

In console, it's usually determined by console setting (i.e. it's detected automatically) ; in GUI, it determines (and is determined by) the width of the gvim windows.

So normally you just let consoles and window managers doing their jobs by commented out the set columns

I am not sure what you mean by "see and anticipate line overflow". If you want EOL to be inserted roughly column 80, use either set textwidth or set wrapmargin; if you just want soft wrap (i.e. line is wrapped, but no actual EOL), then play with set linebreak and set showbreak.

Count distinct values

Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.

I also thought of the SELECT DISTINCT... thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.

So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY clause.

Imagine you have the table customer_pets like this:

+-----------------------+
|  customer  |   pets   |
+------------+----------+
| customer1  |    2     |
| customer2  |    3     |
| customer3  |    2     |
| customer4  |    2     |
| customer5  |    3     |
| customer6  |    4     |
+------------+----------+

then

SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets

would return:

+----------------------------+
|  num_customers  |   pets   |
+-----------------+----------+
|        3        |    2     |
|        2        |    3     |
|        1        |    4     |
+-----------------+----------+

as you need.

How can I list all the deleted files in a Git repository?

If you're only interested in seeing the currently deleted files, you can use this:

git ls-files --deleted

if you then want to remove them (in case you deleted them not using "git rm") pipe that result to xargs git rm

git ls-files --deleted | xargs git rm

Converting XDocument to XmlDocument and vice versa

You could try writing the XDocument to an XmlWriter piped to an XmlReader for an XmlDocument.

If I understand the concepts properly, a direct conversion is not possible (the internal structure is different / simplified with XDocument). But then, I might be wrong...

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

The code you have posted doesn't include a call to mysql_fetch_array(). However, what is most likely going wrong is that you are issuing a query that returns an error message, in which case the return value from the query function is false, and attempting to call mysql_fetch_array() on it doesn't work (because boolean false is not a mysql result object).

Repeat string to certain length

Not that there haven't been enough answers to this question, but there is a repeat function; just need to make a list of and then join the output:

from itertools import repeat

def rep(s,n):
  ''.join(list(repeat(s,n))

How are zlib, gzip and zip related? What do they have in common and how are they different?

The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.

If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.

On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

I have same issue, I found a working solution as below:

The reason is

    if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, ""empty string, false, NaN

never use number type like id as

      if (id) {}

for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.

So for id type, we must use following:

   if ((Id !== undefined) && (Id !== null) && (Id !== "")){
                                                                                
                                                                            } else {

                                                                            }
                                                                            

for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.

       if (string_type_variable) { }

LF will be replaced by CRLF in git - What is that and is it important?

If you want, you can deactivate this feature in your git core config using

git config core.autocrlf false

But it would be better to just get rid of the warnings using

git config core.autocrlf true

android set button background programmatically

Old thread, but learned something new, hope this might help someone.

If you want to change the background color but retain other styles, then below might help.

button.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);

How to tag an older commit in Git?

The answer by @Phrogz is great, but doesn't work on Windows. Here's how to tag an old commit with the commit's original date using Powershell:

git checkout 9fceb02
$env:GIT_COMMITTER_DATE = git show --format=%aD | Select -First 1
git tag v1.2
git checkout master

Generate unique random numbers between 1 and 100

Implementing this as a generator makes it pretty nice to work with. Note, this implementation differs from ones that require the entire input array to be shuffled first.

This sample function works lazily, giving you 1 random item per iteration up to N items you ask for. This is nice because if you just want 3 items from a list of 1000, you don't have to touch all 1000 items first.

_x000D_
_x000D_
// sample :: Integer -> [a] -> [a]_x000D_
const sample = n => function* (xs) {_x000D_
  let ys = xs.slice(0);_x000D_
  let len = xs.length;_x000D_
  while (n > 0 && len > 0) {_x000D_
    let i = (Math.random() * len) >> 0;_x000D_
    yield ys.splice(i,1)[0];_x000D_
    n--; len--;_x000D_
  }_x000D_
}_x000D_
_x000D_
// example inputs_x000D_
let items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];_x000D_
let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];_x000D_
_x000D_
// get 3 random items_x000D_
for (let i of sample(3) (items))_x000D_
  console.log(i); // f g c_x000D_
_x000D_
// partial application_x000D_
const lotto = sample(3);_x000D_
for (let i of lotto(numbers))_x000D_
  console.log(i); // 3 8 7_x000D_
_x000D_
// shuffle an array_x000D_
const shuffle = xs => Array.from(sample (Infinity) (xs))_x000D_
console.log(shuffle(items)) // [b c g f d e a]
_x000D_
_x000D_
_x000D_

I chose to implement sample in a way that does not mutate the input array, but you could easily argue that a mutating implementation is favourable.

For example, the shuffle function might wish to mutate the original input array. Or you might wish to sample from the same input at various times, updating the input each time.

_x000D_
_x000D_
// sample :: Integer -> [a] -> [a]_x000D_
const sample = n => function* (xs) {_x000D_
  let len = xs.length;_x000D_
  while (n > 0 && len > 0) {_x000D_
    let i = (Math.random() * len) >> 0;_x000D_
    yield xs.splice(i,1)[0];_x000D_
    n--; len--;_x000D_
  }_x000D_
}_x000D_
_x000D_
// deal :: [Card] -> [Card]_x000D_
const deal = xs => Array.from(sample (2) (xs));_x000D_
_x000D_
// setup a deck of cards (13 in this case)_x000D_
// cards :: [Card]_x000D_
let cards = 'A234567890JQK'.split('');_x000D_
_x000D_
// deal 6 players 2 cards each_x000D_
// players :: [[Card]]_x000D_
let players = Array.from(Array(6), $=> deal(cards))_x000D_
_x000D_
console.log(players);_x000D_
// [K, J], [6, 0], [2, 8], [Q, 7], [5, 4], [9, A]_x000D_
_x000D_
// `cards` has been mutated. only 1 card remains in the deck_x000D_
console.log(cards);_x000D_
// [3]
_x000D_
_x000D_
_x000D_

sample is no longer a pure function because of the array input mutation, but in certain circumstances (demonstrated above) it might make more sense.


Another reason I chose a generator instead of a function that just returns an array is because you may want to continue sampling until some specific condition.

Perhaps I want the first prime number from a list of 1,000,000 random numbers.

  • "How many should I sample?" – you don't have to specify
  • "Do I have to find all the primes first and then select a random prime?" – Nope.

Because we're working with a generator, this task is trivial

const randomPrimeNumber = listOfNumbers => {
  for (let x of sample(Infinity) (listOfNumbers)) {
    if (isPrime(x))
      return x;
  }
  return NaN;
}

This will continuously sample 1 random number at a time, x, check if it's prime, then return x if it is. If the list of numbers is exhausted before a prime is found, NaN is returned.


Note:

This answer was originally shared on another question that was closed as a duplicate of this one. Because it's very different from the other solutions provided here, I've decided to share it here as well

Is there a way to get the git root directory in one command?

Pre-Configured Shell Aliases in Shell Frameworks

If you use a shell framework, there might already be a shell alias available:

  • $ grt in oh-my-zsh (68k) (cd $(git rev-parse --show-toplevel || echo "."))
  • $ git-root in prezto (8.8k) (displays the path to the working tree root)
  • $ g.. zimfw (1k) (changes the current directory to the top level of the working tree.)

Simple division in Java - is this a bug or a feature?

I find letter identifiers to be more readable and more indicative of parsed type:

1 - 7f / 10
1 - 7 / 10f

or:

1 - 7d / 10
1 - 7 / 10d

Implementing multiple interfaces with Java - is there a way to delegate?

There's no pretty way. You might be able to use a proxy with the handler having the target methods and delegating everything else to them. Of course you'll have to use a factory because there'll be no constructor.

Determine the data types of a data frame's columns

Simply pass your data frame into the following function:

data_types <- function(frame) {
  res <- lapply(frame, class)
  res_frame <- data.frame(unlist(res))
  barplot(table(res_frame), main="Data Types", col="steelblue", ylab="Number of Features")
}

to produce a plot of all data types in your data frame. For the iris dataset we get the following:

data_types(iris)

enter image description here

How to get file URL using Storage facade in laravel 5?

Well, weeks ago I made a very similiar question (Get CDN url from uploaded file via Storage): I wanted the CDN url to show the image in my view (as you are requiring ).

However, after review the package API I confirmed that there is no way do this task. So, my solution was avoid using flysystem. In my case, I needed to play with RackSpace. So, finally decide to create my use package and make my own storage package using The PHP SDK for OpenStack.

By this way, you have full access for functions that you need like getPublicUrl() in order to get the public URL from a cdn container:

/** @var DataObject $file */
$file = \OpenCloud::container('cdn')->getObject('screenshots/1.jpg');

// $url:  https://d224d291-8316ade.ssl.cf1.rackcdn.com/screenshots/1.jpg
$url = (string) $file->getPublicUrl(UrlType::SSL);

In conclusion, if need to take storage service to another level, then flysystem is not enough. For local purposes, you can try @nXu's solution

What is uintptr_t data type

uintptr_t is an unsigned integer type that is capable of storing a data pointer. Which typically means that it's the same size as a pointer.

It is optionally defined in C++11 and later standards.

A common reason to want an integer type that can hold an architecture's pointer type is to perform integer-specific operations on a pointer, or to obscure the type of a pointer by providing it as an integer "handle".

Add vertical scroll bar to panel

Assuming you're using winforms, default panel components does not offer you a way to disable the horizontal scrolling components. A workaround of this is to disable the auto scrolling and add a scrollbar yourself:

ScrollBar vScrollBar1 = new VScrollBar();
vScrollBar1.Dock = DockStyle.Right;
vScrollBar1.Scroll += (sender, e) => { panel1.VerticalScroll.Value = vScrollBar1.Value; };
panel1.Controls.Add(vScrollBar1);

Detailed discussion here.

Formula to determine brightness of RGB color

For clarity, the formulas that use a square root need to be

sqrt(coefficient * (colour_value^2))

not

sqrt((coefficient * colour_value))^2

The proof of this lies in the conversion of a R=G=B triad to greyscale R. That will only be true if you square the colour value, not the colour value times coefficient. See Nine Shades of Greyscale

Has anyone gotten HTML emails working with Twitter Bootstrap?

Hi Brian Armstrong, visit this link.

This blog tells you how to integrate Rails with Bootstrap less (using premailer-rails).

If you're using bootstrap sass, you could do the same:

start by importing some Bootstrap sass files into email.css.scss

@import "bootstrap-sprockets";
@import "bootstrap/variables";
@import "bootstrap/mixins";
@import "bootstrap/scaffolding";
@import "bootstrap/type";
@import "bootstrap/buttons";
@import "bootstrap/alerts";
@import 'bootstrap/normalize';
@import 'bootstrap/tables';
@import 'bootstrap/progress-bars';

and then in your view <head> section add <%= stylesheet_link_tag "email" %>

How to disable XDebug

Apache/2.4.33 (Win64) PHP/7.2.4 myHomeBrew stack

At end of php.ini I use the following to manage Xdebug for use with PhpStorm

; jch ~ Sweet analizer at https://xdebug.org/wizard.php for matching xdebug to php version.
; jch ~ When upgrading php versions check if newer xdebug.dll is needed in ext directory.
; jch Renamed... zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug-2.6.0-7.2-vc15-x86_64.dll

zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug.dll

; jch !!!! Added the following for Xdebug with PhpStorm

[Xdebug]
; zend_extension=<full_path_to_xdebug_extension>
; xdebug.remote_host=<the host where PhpStorm is running (e.g. localhost)>
; xdebug.remote_port=<the port to which Xdebug tries to connect on the host where PhpStorm is running (default 9000)>

xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000

xdebug.profiler_enable=1
xdebug.profiler_output_dir="E:\x64Stack\Xdebug_profiler_output"
xdebug.idekey=PHPSTORM
xdebug.remote_autostart=1

; jch ~~~~~~~~~To turn Xdebug off(disable) uncomment the following 3 lines restart Apache~~~~~~~~~ 
;xdebug.remote_autostart=0  
;xdebug.remote_enable=0
;xdebug.profiler_enable=0

; !!! Might get a little more speed by also commenting out this line above... 
;;; zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug.dll
; so that Xdebug is both disabled AND not loaded

What is content-type and datatype in an AJAX request?

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.

dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.

If you're posting something like:

{"name":"John Doe"}

and expecting back:

{"success":true}

Then you should have:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "json",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        alert(result.success); // result is an object which is created from the returned JSON
    },
});

If you're expecting the following:

<div>SUCCESS!!!</div>

Then you should do:

var data = {"name":"John Doe"}
$.ajax({
    dataType : "html",
    contentType: "application/json; charset=utf-8",
    data : JSON.stringify(data),
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

One more - if you want to post:

name=John&age=34

Then don't stringify the data, and do:

var data = {"name":"John", "age": 34}
$.ajax({
    dataType : "html",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
    data : data,
    success : function(result) {
        jQuery("#someContainer").html(result); // result is the HTML text
    },
});

VBA for clear value in specific range of cell and protected cell from being wash away formula

You could define a macro containing the following code:

Sub DeleteA5X50()   
    Range("A5:X50").Select
    Selection.ClearContents
end sub

Running the macro would select the range A5:x50 on the active worksheet and clear all the contents of the cells within that range.

To leave your formulas intact use the following instead:

Sub DeleteA5X50()   
    Range("A5:X50").Select
    Selection.SpecialCells(xlCellTypeConstants, 23).Select
    Selection.ClearContents
end sub

This will first select the overall range of cells you are interested in clearing the contents from and will then further limit the selection to only include cells which contain what excel considers to be 'Constants.'

You can do this manually in excel by selecting the range of cells, hitting 'f5' to bring up the 'Go To' dialog box and then clicking on the 'Special' button and choosing the 'Constants' option and clicking 'Ok'.

How to stretch in width a WPF user control to its window?

This worked for me. don't assign any width or height to the UserControl and define row and column definition in the parent window.

<UserControl x:Class="MySampleApp.myUC"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d"  
        >
   <Grid>

    </Grid>
</UserControl>


 <Window xmlns:MySampleApp="clr-namespace:MySampleApp"  x:Class="MySampleApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="auto" Width="auto" MinWidth="1000" >
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />           
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />            
    </Grid.ColumnDefinitions>
    <MySampleApp:myUC Grid.Column="0" Grid.Row="0" />       
</Grid>

laravel 5 : Class 'input' not found

This clean code snippet works fine for me:

use Illuminate\Http\Request;
Route::post('/register',function(Request $request){

   $user = new \App\User;
   $user->username = $request->input('username');
   $user->email  = $request->input('email');
   $user->password = Hash::make($request->input('username'));
   $user->designation = $request->input('designation');
   $user->save();
});

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>