Programs & Examples On #Serviceinstall

How to uninstall with msiexec using product id guid without .msi file present

There's no reason for the {} command not to work. The semi-obvious questions are:

  1. You are sure that the product is actually installed! There's something in ARP/Programs&Features.

  2. The original install is in fact visible in the current context. It looks as if it might have been a per-user install, and if you are logged in as somebody else now then it won't know about it - you'd need to log in under the same account as the original install.

  3. If the \windows\installer directory was damaged the cached file would be missing, and that's used to do the uninstall.

How to install ADB driver for any android device?

If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID instead of HardwareID in the driver's INF Models section

How to make a .NET Windows Service start right after the installation?

I've posted a step-by-step procedure for creating a Windows service in C# here. It sounds like you're at least to this point, and now you're wondering how to start the service once it is installed. Setting the StartType property to Automatic will cause the service to start automatically after rebooting your system, but it will not (as you've discovered) automatically start your service after installation.

I don't remember where I found it originally (perhaps Marc Gravell?), but I did find a solution online that allows you to install and start your service by actually running your service itself. Here's the step-by-step:

  1. Structure the Main() function of your service like this:

    static void Main(string[] args)
    {
        if (args.Length == 0) {
            // Run your service normally.
            ServiceBase[] ServicesToRun = new ServiceBase[] {new YourService()};
            ServiceBase.Run(ServicesToRun);
        } else if (args.Length == 1) {
            switch (args[0]) {
                case "-install":
                    InstallService();
                    StartService();
                    break;
                case "-uninstall":
                    StopService();
                    UninstallService();
                    break;
                default:
                    throw new NotImplementedException();
            }
        }
    }
    
  2. Here is the supporting code:

    using System.Collections;
    using System.Configuration.Install;
    using System.ServiceProcess;
    
    private static bool IsInstalled()
    {
        using (ServiceController controller = 
            new ServiceController("YourServiceName")) {
            try {
                ServiceControllerStatus status = controller.Status;
            } catch {
                return false;
            }
            return true;
        }
    }
    
    private static bool IsRunning()
    {
        using (ServiceController controller = 
            new ServiceController("YourServiceName")) {
            if (!IsInstalled()) return false;
            return (controller.Status == ServiceControllerStatus.Running);
        }
    }
    
    private static AssemblyInstaller GetInstaller()
    {
        AssemblyInstaller installer = new AssemblyInstaller(
            typeof(YourServiceType).Assembly, null);
        installer.UseNewContext = true;
        return installer;
    }
    
  3. Continuing with the supporting code...

    private static void InstallService()
    {
        if (IsInstalled()) return;
    
        try {
            using (AssemblyInstaller installer = GetInstaller()) {
                IDictionary state = new Hashtable();
                try {
                    installer.Install(state);
                    installer.Commit(state);
                } catch {
                    try {
                        installer.Rollback(state);
                    } catch { }
                    throw;
                }
            }
        } catch {
            throw;
        }
    }
    
    private static void UninstallService()
    {
        if ( !IsInstalled() ) return;
        try {
            using ( AssemblyInstaller installer = GetInstaller() ) {
                IDictionary state = new Hashtable();
                try {
                    installer.Uninstall( state );
                } catch {
                    throw;
                }
            }
        } catch {
            throw;
        }
    }
    
    private static void StartService()
    {
        if ( !IsInstalled() ) return;
    
        using (ServiceController controller = 
            new ServiceController("YourServiceName")) {
            try {
                if ( controller.Status != ServiceControllerStatus.Running ) {
                    controller.Start();
                    controller.WaitForStatus( ServiceControllerStatus.Running, 
                        TimeSpan.FromSeconds( 10 ) );
                }
            } catch {
                throw;
            }
        }
    }
    
    private static void StopService()
    {
        if ( !IsInstalled() ) return;
        using ( ServiceController controller = 
            new ServiceController("YourServiceName")) {
            try {
                if ( controller.Status != ServiceControllerStatus.Stopped ) {
                    controller.Stop();
                    controller.WaitForStatus( ServiceControllerStatus.Stopped, 
                         TimeSpan.FromSeconds( 10 ) );
                }
            } catch {
                throw;
            }
        }
    }
    
  4. At this point, after you install your service on the target machine, just run your service from the command line (like any ordinary application) with the -install command line argument to install and start your service.

I think I've covered everything, but if you find this doesn't work, please let me know so I can update the answer.

How to change Navigation Bar color in iOS 7?

If you want to use a hex code, here is the best way to do so.

First, define this at the top of your class:

#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

Then inside the "application didFinishLaunchingWithOptions", put this:

[[UINavigationBar appearance] setBarTintColor:UIColorFromRGB(0x00b0f0)];

Put you hex code in place of the 00b0f0.

Inline style to act as :hover in CSS

I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.

I should mention that technically you should be able to do it according to the CSS spec, but most browsers don't support it

Edit: I just did a quick test with this:

<a href="test.html" style="{color: blue; background: white} 
            :visited {color: green}
            :hover {background: yellow}
            :visited:hover {color: purple}">Test</a>

And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?

Explaining Python's '__enter__' and '__exit__'

This is called context manager and I just want to add that similar approaches exist for other programming languages. Comparing them could be helpful in understanding the context manager in python. Basically, a context manager is used when we are dealing with some resources (file, network, database) that need to be initialized and at some point, tear downed (disposed). In Java 7 and above we have automatic resource management that takes the form of:

//Java code
try (Session session = new Session())
{
  // do stuff
}

Note that Session needs to implement AutoClosable or one of its (many) sub-interfaces.

In C#, we have using statements for managing resources that takes the form of:

//C# code
using(Session session = new Session())
{
  ... do stuff.
}

In which Session should implement IDisposable.

In python, the class that we use should implement __enter__ and __exit__. So it takes the form of:

#Python code
with Session() as session:
    #do stuff

And as others pointed out, you can always use try/finally statement in all the languages to implement the same mechanism. This is just syntactic sugar.

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

Android TextView padding between lines

Adding android:lineSpacingMultiplier="0.8" can make the line spacing to 80%.

How do I download a package from apt-get without installing it?

Try

apt-get -d install <packages>

It is documented in man apt-get.

Just for clarification; the downloaded packages are located in the apt package cache at

/var/cache/apt/archives

XSLT - How to select XML Attribute by Attribute?

I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t

<xsl:variable name="myVarANode" select="root//DataSet/Data[@Value1='2']" />
<xsl:value-of select="$myVarANode/@Value2"/>

Everyone else's answers are right too - more right in fact since I didn't notice the extra slash in your XPATH that would mess things up. Still, this will also work , and might work for different things, so keep this method in your toolbox.

What is the .idea folder?

As of year 2020, JetBrains suggests to commit the .idea folder.
The JetBrains IDEs (webstorm, intellij, android studio, pycharm, clion, etc.) automatically add that folder to your git repository (if there's one).
Inside the folder .idea, has been already created a .gitignore, updated by the IDE itself to avoid to commit user related settings that may contains privacy/password data.

It is safe (and usually useful) to commit the .idea folder.

In Angular, how do you determine the active route?

With the new Angular router, you can add a [routerLinkActive]="['your-class-name']" attribute to all your links:

<a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>

Or the simplified non-array format if only one class is needed:

<a [routerLink]="['/home']" [routerLinkActive]="'is-active'">Home</a>

Or an even simpler format if only one class is needed:

<a [routerLink]="['/home']" routerLinkActive="is-active">Home</a>

See the poorly documented routerLinkActive directive for more info. (I mostly figured this out via trial-and-error.)

UPDATE: Better documentation for the routerLinkActive directive can now be found here. (Thanks to @Victor Hugo Arango A. in the comments below.)

SOAP Action WSDL

the service have 4 operations: 1. GetServiceDetails 2. GetArrivalBoard 3. GetDepartureBoard 4. GetArrivalDepartureBoard

Implementation of web service

How can I kill a process by name instead of PID?

To kill with grep:

kill -9 `pgrep myprocess`

@selector() in Swift?

Using #selector will check your code at compile time to make sure the method you want to call actually exists. Even better, if the method doesn’t exist, you’ll get a compile error: Xcode will refuse to build your app, thus banishing to oblivion another possible source of bugs.

override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem =
            UIBarButtonItem(barButtonSystemItem: .Add, target: self,
                            action: #selector(addNewFireflyRefernce))
    }

    func addNewFireflyReference() {
        gratuitousReferences.append("Curse your sudden but inevitable betrayal!")
    }

How can I position my jQuery dialog to center?

Following position parameter worked for me

position: { my: "right bottom", at: "center center", of: window },

Good luck!

How to check if one of the following items is in a list?

Best I could come up with:

any([True for e in (1, 2) if e in a])

AngularJS directive does not update on scope variable changes

I know this an old subject but in case any finds this like myself:

I used the following code when i needed my directive to update values when the "parent scope" updated. Please by all means correct me if am doing something wrong as i am still learning angular, but this did what i needed;

directive:

directive('dateRangePrint', function(){
    return {
        restrict: 'E',
        scope:{
        //still using the single dir binding
            From: '@rangeFrom',
            To: '@rangeTo',
            format: '@format'
        },
        controller: function($scope, $element){

            $scope.viewFrom = function(){
                    return formatDate($scope.From, $scope.format);
                }

            $scope.viewTo = function(){
                    return formatDate($scope.To, $scope.format);
                }

            function formatDate(date, format){
                format = format || 'DD-MM-YYYY';

                //do stuff to date...

                return date.format(format);
            }

        },
        replace: true,
        // note the parenthesis after scope var
        template: '<span>{{ viewFrom() }} - {{ viewTo() }}</span>'
    }
})

Upload file to SFTP using PowerShell

Using PuTTY's pscp.exe (which I have in an $env:path directory):

pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*

Java: Check if enum contains a given string?

Guavas Enums could be your friend

Like e.g. this:

enum MyData {
    ONE,
    TWO
}

@Test
public void test() {

    if (!Enums.getIfPresent(MyData.class, "THREE").isPresent()) {
        System.out.println("THREE is not here");
    }
}

Store List to session

Try this..

    List<Cat> cats = new List<Cat>
    {
        new Cat(){ Name = "Sylvester", Age=8 },
        new Cat(){ Name = "Whiskers", Age=2 },
        new Cat(){ Name = "Sasha", Age=14 }
    };
    Session["data"] = cats;
    foreach (Cat c in cats)
        System.Diagnostics.Debug.WriteLine("Cats>>" + c.Name);     //DEBUGGG

Strip off URL parameter with PHP

very simple

$link = "http://example.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0"
echo substr($link, 0, strpos($link, "return") - 1);
//output : http://example.com/index.php?id=115&Itemid=283

get string from right hand side

the pattern maybe looks like this :

substr(STRING, ( length(STRING) - (TOTAL_GET_LENGTH - 1) ),TOTAL_GET_LENGTH)

in your case , it will like this :

substr('299123456789', (length('299123456789')-(9 - 1)),9)

substr('299123456789', (12-8),9)

substr('299123456789', 4,9)

the result ? of course '123456789'

the length is dynamic , voila :)

Spring Security exclude url patterns in security annotation configurartion

Found the solution in Spring security examples posted in Github.

WebSecurityConfigurerAdapter has a overloaded configure message that takes WebSecurity as argument which accepts ant matchers on requests to be ignored.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/authFailure");
}

See Spring Security Samples for more details

PHP Fatal error: Call to undefined function json_decode()

you might also consider avoiding the core PHP module altogether.

It is quite common to use the guzzle json tools as a library in PHP apps these days. If your app is a composer app, it is trivial to include them as a part of a composer build. The guzzle tool, as a library, would be a turnkey replacement for the json tool, if you tell PHP to autoinclude the tool.

http://docs.guzzlephp.org/en/stable/search.html?q=json_encode#

http://apigen.juzna.cz/doc/guzzle/guzzle/function-GuzzleHttp.json_decode.html

Length of array in function argument

Best example is here

thanks #define SIZE 10

void size(int arr[SIZE])
{
    printf("size of array is:%d\n",sizeof(arr));
}

int main()
{
    int arr[SIZE];
    size(arr);
    return 0;
}

jQuery: Return data after ajax call success

See jquery docs example: http://api.jquery.com/jQuery.ajax/ (about 2/3 the page)

You may be looking for following code:

    $.ajax({
     url: 'ajax/test.html',
     success: function(data) {
     $('.result').html(data);
     alert('Load was performed.');
   }
});

Same page...lower down.

How to replace multiple strings in a file using PowerShell

With version 3 of PowerShell you can chain the replace calls together:

 (Get-Content $sourceFile) | ForEach-Object {
    $_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
 } | Set-Content $destinationFile

Moment JS start and end of given month

Don't really think there is some direct method to get the last day but you could do something like this:

var dateInst = new moment();
/**
 * adding 1 month from the present month and then subtracting 1 day, 
 * So you would get the last day of this month 
 */
dateInst.add(1, 'months').date(1).subtract(1, 'days');
/* printing the last day of this month's date */
console.log(dateInst.format('YYYY MM DD'));

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

One easy trick that can help with most deadlocks is sorting the operations in a specific order.

You get a deadlock when two transactions are trying to lock two locks at opposite orders, ie:

  • connection 1: locks key(1), locks key(2);
  • connection 2: locks key(2), locks key(1);

If both run at the same time, connection 1 will lock key(1), connection 2 will lock key(2) and each connection will wait for the other to release the key -> deadlock.

Now, if you changed your queries such that the connections would lock the keys at the same order, ie:

  • connection 1: locks key(1), locks key(2);
  • connection 2: locks key(1), locks key(2);

it will be impossible to get a deadlock.

So this is what I suggest:

  1. Make sure you have no other queries that lock access more than one key at a time except for the delete statement. if you do (and I suspect you do), order their WHERE in (k1,k2,..kn) in ascending order.

  2. Fix your delete statement to work in ascending order:

Change

DELETE FROM onlineusers 
WHERE datetime <= now() - INTERVAL 900 SECOND

To

DELETE FROM onlineusers 
WHERE id IN (
    SELECT id FROM onlineusers
    WHERE datetime <= now() - INTERVAL 900 SECOND 
    ORDER BY id
) u;

Another thing to keep in mind is that mysql documentation suggest that in case of a deadlock the client should retry automatically. you can add this logic to your client code. (Say, 3 retries on this particular error before giving up).

Relation between CommonJS, AMD and RequireJS?

RequireJS implements the AMD API (source).

CommonJS is a way of defining modules with the help of an exports object, that defines the module contents. Simply put, a CommonJS implementation might work like this:

// someModule.js
exports.doSomething = function() { return "foo"; };

//otherModule.js
var someModule = require('someModule'); // in the vein of node    
exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };

Basically, CommonJS specifies that you need to have a require() function to fetch dependencies, an exports variable to export module contents and a module identifier (which describes the location of the module in question in relation to this module) that is used to require the dependencies (source). CommonJS has various implementations, including Node.js, which you mentioned.

CommonJS was not particularly designed with browsers in mind, so it doesn't fit in the browser environment very well (I really have no source for this--it just says so everywhere, including the RequireJS site.) Apparently, this has something to do with asynchronous loading, etc.

On the other hand, RequireJS implements AMD, which is designed to suit the browser environment (source). Apparently, AMD started as a spinoff of the CommonJS Transport format and evolved into its own module definition API. Hence the similarities between the two. The new feature in AMD is the define() function that allows the module to declare its dependencies before being loaded. For example, the definition could be:

define('module/id/string', ['module', 'dependency', 'array'], 
function(module, factory function) {
  return ModuleContents;  
});

So, CommonJS and AMD are JavaScript module definition APIs that have different implementations, but both come from the same origins.

  • AMD is more suited for the browser, because it supports asynchronous loading of module dependencies.
  • RequireJS is an implementation of AMD, while at the same time trying to keep the spirit of CommonJS (mainly in the module identifiers).

To confuse you even more, RequireJS, while being an AMD implementation, offers a CommonJS wrapper so CommonJS modules can almost directly be imported for use with RequireJS.

define(function(require, exports, module) {
  var someModule = require('someModule'); // in the vein of node    
  exports.doSomethingElse = function() { return someModule.doSomething() + "bar"; };
});

I hope this helps to clarify things!

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

I'm pretty sure this isn't the BEST way, but you could set the MinimumSize and MaximimSize properties to the same value. That will stop it.

SQL Server CTE and recursion example

    --DROP TABLE #Employee
    CREATE TABLE #Employee(EmpId BIGINT IDENTITY,EmpName VARCHAR(25),Designation VARCHAR(25),ManagerID BIGINT)

    INSERT INTO #Employee VALUES('M11M','Manager',NULL)
    INSERT INTO #Employee VALUES('P11P','Manager',NULL)

    INSERT INTO #Employee VALUES('AA','Clerk',1)
    INSERT INTO #Employee VALUES('AB','Assistant',1)
    INSERT INTO #Employee VALUES('ZC','Supervisor',2)
    INSERT INTO #Employee VALUES('ZD','Security',2)


    SELECT * FROM #Employee (NOLOCK)

    ;
    WITH Emp_CTE 
    AS
    (
        SELECT EmpId,EmpName,Designation, ManagerID
              ,CASE WHEN ManagerID IS NULL THEN EmpId ELSE ManagerID END ManagerID_N
        FROM #Employee  
    )
    select EmpId,EmpName,Designation, ManagerID
    FROM Emp_CTE
    order BY ManagerID_N, EmpId

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

Mark all the desired projects in solution explorer.

Press Alt-F7 or right click in solution explorer and select "Properties"

Configurations:All Configurations

Click on the Preprocessor Definitions line to invoke its editor

Choose Edit...

Copy "_CRT_SECURE_NO_WARNINGS" into the Preprocessor Definitions white box on the top.

enter image description here

How to set up Android emulator proxy settings

Install Proxifier in your host computer. Setup proxifier to use your proxy. You don't need to do anything else. You will be fine. Proxifier traps the calls from the system (including the android emulator) and route it through the configured proxy.

Why is the gets function so dangerous that it should not be used?

You can't remove API functions without breaking the API. If you would, many applications would no longer compile or run at all.

This is the reason that one reference gives:

Reading a line that overflows the array pointed to by s results in undefined behavior. The use of fgets() is recommended.

Camera access through browser

In iOS6, Apple supports this via the <input type="file"> tag. I couldn't find a useful link in Apple's developer documentation, but there's an example here.

It looks like overlays and more advanced functionality is not yet available, but this should work for a lot of use cases.

EDIT: The w3c has a spec that iOS6 Safari seems to implement a subset of. The capture attribute is notably missing.

Sending files using POST with HttpURLConnection

I found using okHttp a lot easier as I could not get any of these solutions to work: https://stackoverflow.com/a/37942387/447549

Applying CSS styles to all elements inside a DIV

.yourWrapperClass * {
 /* your styles for ALL */
}

This code will apply styles all elements inside .yourWrapperClass.

Replace Default Null Values Returned From Left Outer Join

MySQL

COALESCE(field, 'default')

For example:

  SELECT
    t.id,
    COALESCE(d.field, 'default')
  FROM
     test t
  LEFT JOIN
     detail d ON t.id = d.item

Also, you can use multiple columns to check their NULL by COALESCE function. For example:

mysql> SELECT COALESCE(NULL, 1, NULL);
        -> 1
mysql> SELECT COALESCE(0, 1, NULL);
        -> 0
mysql> SELECT COALESCE(NULL, NULL, NULL);
        -> NULL

JavaFX 2.1 TableView refresh items

I had a similar problem with refreshing. My solution was to restrict the operations on the ObservableList to those which work correctly with bind().

Assume ObservableList obsList is the underlying list for the TableView.

Then
obsList.clear() (inherited from java.util.List<>) will not update the TableView correctly but.

Also calling setItem(obsList) did not work to trigger a refresh...but...

obsList.removeAll(obsList) (overwritten by ObservableList) works fine because it fires the changeEvent correctly.

Refilling a list with completely new content then works as follows:

  • obsList.removeAll(obsList);
  • obsList.add(...); //e.g. in a loop...

or

  • obsList.removeAll(obsList);
  • FXCollections.copy(obsList, someSourceList)

Best regards Ingo

An array of List in c#

I can suggest that you both create and initialize your array at the same line using linq:

List<int>[] a = new List<int>[100].Select(item=>new List<int>()).ToArray();

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

jQuery select child element by class with unknown path

$('#thisElement').find('.classToSelect') will find any descendents of #thisElement with class classToSelect.

Generate a unique id

Here is a 'YouTube-video-id' like id generator e.g. "UcBKmq2XE5a"

StringBuilder builder = new StringBuilder();
Enumerable
   .Range(65, 26)
    .Select(e => ((char)e).ToString())
    .Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
    .Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
    .OrderBy(e => Guid.NewGuid())
    .Take(11)
    .ToList().ForEach(e => builder.Append(e));
string id = builder.ToString();

It creates random ids of size 11 characters. You can increase/decrease that as well, just change the parameter of Take method.

0.001% duplicates in 100 million.

Changing the interval of SetInterval while it's running

Use setTimeout() instead. The callback would then be responsible for firing the next timeout, at which point you can increase or otherwise manipulate the timing.

EDIT

Here's a generic function you can use to apply a "decelerating" timeout for ANY function call.

function setDeceleratingTimeout(callback, factor, times)
{
    var internalCallback = function(tick, counter) {
        return function() {
            if (--tick >= 0) {
                window.setTimeout(internalCallback, ++counter * factor);
                callback();
            }
        }
    }(times, 0);

    window.setTimeout(internalCallback, factor);
};

// console.log() requires firebug    
setDeceleratingTimeout(function(){ console.log('hi'); }, 10, 10);
setDeceleratingTimeout(function(){ console.log('bye'); }, 100, 10);

How to view .img files?

With *nix, usually, you don't need a software to view an .img file. You can use the loop device to mount it and then every file manager to navigate it. Here you can find how. Sometime you need to install some package to manage strange filesystem like squashfs.

system("pause"); - Why is it wrong?

It's all a matter of style. It's useful for debugging but otherwise it shouldn't be used in the final version of the program. It really doesn't matter on the memory issue because I'm sure that those guys who invented the system("pause") were anticipating that it'd be used often. In another perspective, computers get throttled on their memory for everything else we use on the computer anyways and it doesn't pose a direct threat like dynamic memory allocation, so I'd recommend it for debugging code, but nothing else.

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

How to limit the number of dropzone.js files uploaded?

I thought that the most intuitive single file upload process was to replace the previous file upon a new entry.

  $(".drop-image").dropzone({
    url: '/cart?upload-engraving=true',
    maxFiles: 1,
    maxfilesexceeded: function(file) {
        this.removeAllFiles();
        this.addFile(file);
    }
})

Using external images for CSS custom cursors

It wasn't working because your image was too big - there are restrictions on the image dimensions. In Firefox, for example, the size limit is 128x128px. See this page for more details.

Additionally, you also have to add in auto.

jsFiddle demo here - note that's an actual image, and not a default cursor.

_x000D_
_x000D_
.test {_x000D_
  background:gray;_x000D_
  width:200px;_x000D_
  height:200px;_x000D_
  cursor:url(http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif), auto;_x000D_
}
_x000D_
<div class="test">TEST</div>
_x000D_
_x000D_
_x000D_

How to determine MIME type of file in android?

// new processing the mime type out of Uri which may return null in some cases
String mimeType = getContentResolver().getType(uri);
// old processing the mime type out of path using the extension part if new way returned null
if (mimeType == null){mimeType URLConnection.guessContentTypeFromName(path);}

Best way to handle multiple constructors in Java

You need to specify what are the class invariants, i.e. properties which will always be true for an instance of the class (for example, the title of a book will never be null, or the size of a dog will always be > 0).

These invariants should be established during construction, and be preserved along the lifetime of the object, which means that methods shall not break the invariants. The constructors can set these invariants either by having compulsory arguments, or by setting default values:

class Book {
    private String title; // not nullable
    private String isbn;  // nullable

    // Here we provide a default value, but we could also skip the 
    // parameterless constructor entirely, to force users of the class to
    // provide a title
    public Book()
    {
        this("Untitled"); 
    }

    public Book(String title) throws IllegalArgumentException
    {
        if (title == null) 
            throw new IllegalArgumentException("Book title can't be null");
        this.title = title;
        // leave isbn without value
    }
    // Constructor with title and isbn
}

However, the choice of these invariants highly depends on the class you're writing, how you'll use it, etc., so there's no definitive answer to your question.

How do I get the day month and year from a Windows cmd.exe script?

The only reliably way I know is to use VBScript to do the heavy work for you. There is no portable way of getting the current date in a usable format with a batch file alone. The following VBScript file

Wscript.Echo("set Year=" & DatePart("yyyy", Date))
Wscript.Echo("set Month=" & DatePart("m", Date))
Wscript.Echo("set Day=" & DatePart("d", Date))

and this batch snippet

for /f "delims=" %%x in ('cscript /nologo date.vbs') do %%x
echo %Year%-%Month%-%Day%

should work, though.

While you can get the current date in a batch file with either date /t or the %date% pseudo-variable, both follow the current locale in what they display. Which means you get the date in potentially any format and you have no way of parsing that.

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

Another solution could be:

var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference).AsEnumerable()
   .Where(x => x.DateTimeStart.Date == currentDate.Date).AsQueryable();

Customize list item bullets using CSS

This method moves the disc out of the text flow where the original disc was, but is adjustable.

ul{
    list-style-type: none;
    
    li{ 
        position: relative;
      }
    li:before {
        position: absolute;
        top: .1rem;
        left: -.8em;
        content: '\2022';
        font-size: 1.2rem;
    }
}

How to get a float result by dividing two integer values using T-SQL?

Use this

select cast((1*1.00)/3 AS DECIMAL(16,2)) as Result

Here in this sql first convert to float or multiply by 1.00 .Which output will be a float number.Here i consider 2 decimal places. You can choose what you need.

Is there a "do ... while" loop in Ruby?

From what I gather, Matz does not like the construct

begin
    <multiple_lines_of_code>
end while <cond>

because, it's semantics is different than

<single_line_of_code> while <cond>

in that the first construct executes the code first before checking the condition, and the second construct tests the condition first before it executes the code (if ever). I take it Matz prefers to keep the second construct because it matches one line construct of if statements.

I never liked the second construct even for if statements. In all other cases, the computer executes code left-to-right (eg. || and &&) top-to-bottom. Humans read code left-to-right top-to-bottom.

I suggest the following constructs instead:

if <cond> then <one_line_code>      # matches case-when-then statement

while <cond> then <one_line_code>

<one_line_code> while <cond>

begin <multiple_line_code> end while <cond> # or something similar but left-to-right

I don't know if those suggestions will parse with the rest of the language. But in any case I prefere keeping left-to-right execution as well as language consistency.

RegEx for matching "A-Z, a-z, 0-9, _" and "."

You could simply use ^[\w.]+ to match A-Z, a-z, 0-9 and _

What is the difference between an int and a long in C++?

It is implementation dependent.

For example, under Windows they are the same, but for example on Alpha systems a long was 64 bits whereas an int was 32 bits. This article covers the rules for the Intel C++ compiler on variable platforms. To summarize:

  OS           arch           size
Windows       IA-32        4 bytes
Windows       Intel 64     4 bytes
Windows       IA-64        4 bytes
Linux         IA-32        4 bytes
Linux         Intel 64     8 bytes
Linux         IA-64        8 bytes
Mac OS X      IA-32        4 bytes
Mac OS X      Intel 64     8 bytes  

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

Using REQUIRES_NEW is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED - it will create a new transaction.

That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional, it will create a new transaction.

So, with that in mind, if using REQUIRES_NEW makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.

On rollback - using REQUIRES_NEW will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.

Spring MVC: How to perform validation?

If you have same error handling logic for different method handlers, then you would end up with lots of handlers with following code pattern:

if (validation.hasErrors()) {
  // do error handling
}
else {
  // do the actual business logic
}

Suppose you're creating RESTful services and want to return 400 Bad Request along with error messages for every validation error case. Then, the error handling part would be same for every single REST endpoint that requires validation. Repeating that very same logic in every single handler is not so DRYish!

One way to solve this problem is to drop the immediate BindingResult after each To-Be-Validated bean. Now, your handler would be like this:

@RequestMapping(...)
public Something doStuff(@Valid Somebean bean) { 
    // do the actual business logic
    // Just the else part!
}

This way, if the bound bean was not valid, a MethodArgumentNotValidException will be thrown by Spring. You can define a ControllerAdvice that handles this exception with that same error handling logic:

@ControllerAdvice
public class ErrorHandlingControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public SomeErrorBean handleValidationError(MethodArgumentNotValidException ex) {
        // do error handling
        // Just the if part!
    }
}

You still can examine the underlying BindingResult using getBindingResult method of MethodArgumentNotValidException.

Hide/encrypt password in bash file to stop accidentally seeing it

  • indent it off the edge of your screen (assuming you don't use line wrapping and you have a consistant editor width)

or

  • store it in a separate file and read it in.

Why is "throws Exception" necessary when calling a function?

Basically, if you are not handling the exception in the same place as you are throwing it, then you can use "throws exception" at the definition of the function.

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

I was facing the same issue where my current branch was dev and I was checking out to MR branch and doing git pull thereafter. An easy workaround that I took was I created a new folder for MR Branch and did git pull there followed by git clone.

So basically I maintained different folders for pushing code to different branch.

generate random string for div id

Or you could use Cripto since it's already built in(except in IE11, I swear these guys havent updated in years!)

https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples

var id = new Uint32Array(10);
window.crypto.getRandomValues(array);

I also found this:

https://gist.github.com/6174/6062387#gistcomment-3255605

let length = 32;
let id = crypto.randomBytes(length).toString("base64");

There's a lot of ways to do this, but for most people, there's no reason to reinvent the wheel :)

HttpContext.Current.Session is null when routing requests

What @Bogdan Maxim said. Or change to use InProc if you're not using an external sesssion state server.

<sessionState mode="InProc" timeout="20" cookieless="AutoDetect" />

Look here for more info on the SessionState directive.

Types in MySQL: BigInt(20) vs Int(20)

As far as I know, there is only one small difference is when you are trying to insert value which is out of range.

In examples I'll use 401421228216, which is 101110101110110100100011101100010111000 (length 39 characters)

  • If you have INT(20) for system this means allocate in memory minimum 20 bits. But if you'll insert value that bigger than 2^20, it will be stored successfully, only if it's less then INT(32) -> 2147483647 (or 2 * INT(32) -> 4294967295 for UNSIGNED)

Example:

mysql> describe `test`;
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| id    | int(20) unsigned | YES  |     | NULL    |       |
+-------+------------------+------+-----+---------+-------+
1 row in set (0,00 sec)

mysql> INSERT INTO `test` (`id`) VALUES (401421228216);
ERROR 1264 (22003): Out of range value for column 'id' at row 1

mysql> SET sql_mode = '';
Query OK, 0 rows affected, 1 warning (0,00 sec)

mysql> INSERT INTO `test` (`id`) VALUES (401421228216);
Query OK, 1 row affected, 1 warning (0,06 sec)

mysql> SELECT * FROM `test`;
+------------+
| id         |
+------------+
| 4294967295 |
+------------+
1 row in set (0,00 sec)
  • If you have BIGINT(20) for system this means allocate in memory minimum 20 bits. But if you'll insert value that bigger than 2^20, it will be stored successfully, if it's less then BIGINT(64) -> 9223372036854775807 (or 2 * BIGINT(64) -> 18446744073709551615 for UNSIGNED)

Example:

mysql> describe `test`;
+-------+---------------------+------+-----+---------+-------+
| Field | Type                | Null | Key | Default | Extra |
+-------+---------------------+------+-----+---------+-------+
| id    | bigint(20) unsigned | YES  |     | NULL    |       |
+-------+---------------------+------+-----+---------+-------+
1 row in set (0,00 sec)

mysql> INSERT INTO `test` (`id`) VALUES (401421228216);
Query OK, 1 row affected (0,04 sec)

mysql> SELECT * FROM `test`;
+--------------+
| id           |
+--------------+
| 401421228216 |
+--------------+
1 row in set (0,00 sec)

REST API Best practices: Where to put parameters?

Here is my opinion.

Query params are used as meta data to a request. They act as filter or modifier to an existing resource call.

Example:

/calendar/2014-08-08/events

should give calendar events for that day.

If you want events for a specific category

/calendar/2014-08-08/events?category=appointments

or if you need events of longer than 30 mins

/calendar/2014-08-08/events?duration=30

A litmus test would be to check if the request can still be served without an query params.

How to get current foreground activity context in android?

getCurrentActivity() is also in ReactContextBaseJavaModule.
(Since the this question was initially asked, many Android app also has ReactNative component - hybrid app.)

class ReactContext in ReactNative has the whole set of logic to maintain mCurrentActivity which is returned in getCurrentActivity().

Note: I wish getCurrentActivity() is implemented in Android Application class.

What is the best way to modify a list in a 'foreach' loop?

You can't change the enumerable collection while it is being enumerated, so you will have to make your changes before or after enumerating.

The for loop is a nice alternative, but if your IEnumerable collection does not implement ICollection, it is not possible.

Either:

1) Copy collection first. Enumerate the copied collection and change the original collection during the enumeration. (@tvanfosson)

or

2) Keep a list of changes and commit them after the enumeration.

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Like stated in other answers, create a Twitter app to get the token, key and secret. Using the code bellow, you can modify request parameters from one spot and avoid typos and similar errors (change $request array in returnTweet() function).

function buildBaseString($baseURI, $method, $params) {
    $r = array();
    ksort($params);
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth) {
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    $r .= implode(', ', $values);
    return $r;
}

function returnTweet(){
    $oauth_access_token         = "x";
    $oauth_access_token_secret  = "x";
    $consumer_key               = "x";
    $consumer_secret            = "x";

    $twitter_timeline           = "user_timeline";  //  mentions_timeline / user_timeline / home_timeline / retweets_of_me

    //  create request
        $request = array(
            'screen_name'       => 'budidino',
            'count'             => '3'
        );

    $oauth = array(
        'oauth_consumer_key'        => $consumer_key,
        'oauth_nonce'               => time(),
        'oauth_signature_method'    => 'HMAC-SHA1',
        'oauth_token'               => $oauth_access_token,
        'oauth_timestamp'           => time(),
        'oauth_version'             => '1.0'
    );

    //  merge request and oauth to one array
        $oauth = array_merge($oauth, $request);

    //  do some magic
        $base_info              = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
        $composite_key          = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
        $oauth_signature            = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
        $oauth['oauth_signature']   = $oauth_signature;

    //  make request
        $header = array(buildAuthorizationHeader($oauth), 'Expect:');
        $options = array( CURLOPT_HTTPHEADER => $header,
                          CURLOPT_HEADER => false,
                          CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_SSL_VERIFYPEER => false);

        $feed = curl_init();
        curl_setopt_array($feed, $options);
        $json = curl_exec($feed);
        curl_close($feed);

    return json_decode($json, true);
}

and then just call returnTweet()

printf not printing on console

You could try writing to stderr, rather than stdout.

fprintf(stderr, "Hello, please enter your age\n");

You should also have a look at this relevant thread.

Jquery Smooth Scroll To DIV - Using ID value from Link

You can do this:

$('.searchbychar').click(function () {
    var divID = '#' + this.id;
    $('html, body').animate({
        scrollTop: $(divID).offset().top
    }, 2000);
});

F.Y.I.

  • You need to prefix a class name with a . (dot) like in your first line of code.
  • $( 'searchbychar' ).click(function() {
  • Also, your code $('.searchbychar').attr('id') will return a string ID not a jQuery object. Hence, you can not apply .offset() method to it.

How to add background-image using ngStyle (angular2)?

import {BrowserModule, DomSanitizer} from '@angular/platform-browser'

  constructor(private sanitizer:DomSanitizer) {
    this.name = 'Angular!'
    this.backgroundImg = sanitizer.bypassSecurityTrustStyle('url(http://www.freephotos.se/images/photos_medium/white-flower-4.jpg)');
  }
<div [style.background-image]="backgroundImg"></div>

See also

FileNotFoundError: [Errno 2] No such file or directory

You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.

Try using the exact, or absolute, path.

Effective way to find any file's Encoding

The StreamReader.CurrentEncoding property rarely returns the correct text file encoding for me. I've had greater success determining a file's endianness, by analyzing its byte order mark (BOM). If the file does not have a BOM, this cannot determine the file's encoding.

*UPDATED 4/08/2020 to include UTF-32LE detection and return correct encoding for UTF-32BE

/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM).
/// Defaults to ASCII when detection of the text file's endianness fails.
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding.</returns>
public static Encoding GetEncoding(string filename)
{
    // Read the BOM
    var bom = new byte[4];
    using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
    {
        file.Read(bom, 0, 4);
    }

    // Analyze the BOM
    if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
    if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
    if (bom[0] == 0xff && bom[1] == 0xfe && bom[2] == 0 && bom[3] == 0) return Encoding.UTF32; //UTF-32LE
    if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
    if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
    if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return new UTF32Encoding(true, true);  //UTF-32BE

    // We actually have no idea what the encoding is if we reach this point, so
    // you may wish to return null instead of defaulting to ASCII
    return Encoding.ASCII;
}

jQuery UI Datepicker - Multiple Date Selections

http://t1m0n.name/air-datepicker/docs/? I've have tried several method of multi datepicker but only this works

Check if PHP session has already started

This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.

function start_session() {
  if(version_compare(phpversion(), "5.4.0") != -1){
    if (session_status() == PHP_SESSION_NONE) {
      session_start();
    }
  } else {
    if(session_id() == '') {
      session_start();
    }
  }
}

How can I use grep to show just filenames on Linux?

For a simple file search you could use grep's -l and -r options:

grep -rl "mystring"

All the search is done by grep. Of course, if you need to select files on some other parameter, find is the correct solution:

find . -iname "*.php" -execdir grep -l "mystring" {} +

The execdir option builds each grep command per each directory, and concatenates filenames into only one command (+).

How to get RegistrationID using GCM in android

In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.

In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.

How to position a DIV in a specific coordinates?

You can also use position fixed css property.

<!-- html code --> 
<div class="box" id="myElement"></div>

/* css code */
.box {
    position: fixed;
}

// js code

document.getElementById('myElement').style.top = 0; //or whatever 
document.getElementById('myElement').style.left = 0; // or whatever

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

You can also use query scopes to make things a bit tidier, so you can do something like:

Invoice::where('account', 27)->notPaidAt($date)->get();

Then in your model

public function scopeNotPaidAt($query, $asAt)
{
    $query = $query->where(function ($query) use ($asAt) { 
        $query->where('paid', '=', '0000-00-00')->orWhere('paid', '>=', $asAt); 
    });
    return $query;    
}

What's the difference between Git Revert, Checkout and Reset?

These three commands have entirely different purposes. They are not even remotely similar.

git revert

This command creates a new commit that undoes the changes from a previous commit. This command adds new history to the project (it doesn't modify existing history).

git checkout

This command checks-out content from the repository and puts it in your work tree. It can also have other effects, depending on how the command was invoked. For instance, it can also change which branch you are currently working on. This command doesn't make any changes to the history.

git reset

This command is a little more complicated. It actually does a couple of different things depending on how it is invoked. It modifies the index (the so-called "staging area"). Or it changes which commit a branch head is currently pointing at. This command may alter existing history (by changing the commit that a branch references).

Using these commands

If a commit has been made somewhere in the project's history, and you later decide that the commit is wrong and should not have been done, then git revert is the tool for the job. It will undo the changes introduced by the bad commit, recording the "undo" in the history.

If you have modified a file in your working tree, but haven't committed the change, then you can use git checkout to checkout a fresh-from-repository copy of the file.

If you have made a commit, but haven't shared it with anyone else and you decide you don't want it, then you can use git reset to rewrite the history so that it looks as though you never made that commit.

These are just some of the possible usage scenarios. There are other commands that can be useful in some situations, and the above three commands have other uses as well.

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

In summary the answer is: set the font size of the form elements to at least 16px

Why does git say "Pull is not possible because you have unmerged files"?

If you dont want any of your local branch changes i think this is the best approach

git clean -df
git reset --hard
git checkout REMOTE_BRANCH_NAME
git pull origin REMOTE_BRANCH_NAME

Python locale error: unsupported locale setting

You probably do not have any de_DE locale available.

You can view a list of available locales with the locale -a command. For example, on my machine:

$ locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8
it_CH.utf8
it_IT.utf8
POSIX

Note that if you want to set the locale to it_IT you must also specify the .utf8:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'it_IT')   # error!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/locale.py", line 539, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting
>>> locale.setlocale(locale.LC_ALL, 'it_IT.utf8')
'it_IT.utf8'

To install a new locale use:

sudo apt-get install language-pack-id

where id is the language code (taken from here)

After you have installed the locale you should follow Julien Palard advice and reconfigure the locales with:

sudo dpkg-reconfigure locales

What is ":-!!" in C code?

Some people seem to be confusing these macros with assert().

These macros implement a compile-time test, while assert() is a runtime test.

Remove duplicates from an array of objects in JavaScript

I believe a combination of reduce with JSON.stringify to perfectly compare Objects and selectively adding those who are not already in the accumulator is an elegant way.

Keep in mind that JSON.stringify might become a performance issue in extreme cases where the array has many Objects and they are complex, BUT for majority of the time, this is the shortest way to go IMHO.

_x000D_
_x000D_
var collection= [{a:1},{a:2},{a:1},{a:3}]_x000D_
_x000D_
var filtered = collection.reduce((filtered, item) => {_x000D_
  if( !filtered.some(filteredItem => JSON.stringify(filteredItem) == JSON.stringify(item)) )_x000D_
    filtered.push(item)_x000D_
  return filtered_x000D_
}, [])_x000D_
_x000D_
console.log(filtered)
_x000D_
_x000D_
_x000D_

Another way of writing the same (but less efficient):

collection.reduce((filtered, item) => 
  filtered.some(filteredItem => 
    JSON.stringify(filteredItem ) == JSON.stringify(item)) 
      ? filtered
      : [...filtered, item]
, [])

A process crashed in windows .. Crash dump location

I have observed on Windows 2008 the Windows Error Reporting crash dumps get staged in the folder:

C:\Users\All Users\Microsoft\Windows\WER\ReportQueue

Which, starting with Windows Vista, is an alias for:

C:\ProgramData\Microsoft\Windows\WER\ReportQueue

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

Adding external library into Qt Creator project

If you want to deploy your application on machines of customers, rather than using your application only yourself, we find that the LIBS+= -Lxxx -lyyy method can lead to confusion if not problems.

We develop applications for Linux, Mac and Windows using Qt. We ship complete, stand-alone applications. So all non-system libraries should be included in the deployment package. We want our customers to be able to run the application from the same USB stick for all OSs. For reasons of platform compatibility the USB stick must then be formatted as FAT32, which does not support (Linux) symlinks.

We found the LIBS+= -Lxxx -lyyy idiom too much of a black box:

  1. We do not exactly know what the filepath is of the (static or dynamic) library that has been found by the linker. This is inconvenient. Our Mac linker regularly found libs different from the ones we thought that should be used. This happened several times with OpenSSL libraries where the Mac linker found and used its own - older, incompatible - OpenSSL version rather than our requested version.

  2. We cannot afford that the linker uses symlinks to libraries as this would break the deployment package.

  3. We want to see from the name of the library whether we link a static or a dynamic library.

So for our particular case we use only absolute filepaths and check whether they exist. We remove all symlinks.

First we find out what operating system we are using and put this in the CONFIG variable. And, for instance for Linux 64bit, then:

linux64 {
    LIBSSL= $$OPENSSLPATH/linux64/lib/libssl.a
    !exists($$LIBSSL): error ("Not existing $$LIBSSL")
    LIBS+= $$LIBSSL
    LIBCRYPTO= $$OPENSSLPATH/linux64/lib/libcrypto.a
    !exists($$LIBCRYPTO): error ("Not existing $$LIBCRYPTO")
    LIBS+= $$LIBCRYPTO
}

All the dependencies can be copied into deployment package as we know their filepaths.

Object creation on the stack/heap?

In both your examples, local variables of Object* type are allocated on the stack. The compiler is free to produce the same code from both snippets if there is no way for your program to detect a difference.

The memory area for global variables is the same as the memory area for static variables - it's neither on the stack nor on the heap. You can place variables in that area by declaring them static inside the function. The consequence of doing so is that the instance becomes shared among concurrent invocations of your function, so you need to carefully consider synchronization when you use statics.

Here is a link to a discussion of the memory layout of a running C program.

How can I count the rows with data in an Excel sheet?

If you don't mind VBA, here is a function that will do it for you. Your call would be something like:

=CountRows(1:10) 
Function CountRows(ByVal range As range) As Long

Application.ScreenUpdating = False
Dim row As range
Dim count As Long

For Each row In range.Rows
    If (Application.WorksheetFunction.CountBlank(row)) - 256 <> 0 Then
        count = count + 1
    End If
Next

CountRows = count
Application.ScreenUpdating = True

End Function

How it works: I am exploiting the fact that there is a 256 row limit. The worksheet formula CountBlank will tell you how many cells in a row are blank. If the row has no cells with values, then it will be 256. So I just minus 256 and if it's not 0 then I know there is a cell somewhere that has some value.

How do I search within an array of hashes by hash values in ruby?

this will return first match

@fathers.detect {|f| f["age"] > 35 }

Get all object attributes in Python?

You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values

usage :

for att in dir(your_object):
    print (att, getattr(your_object,att))

How and when to use ‘async’ and ‘await’

Showing the above explanations in action in a simple console program:

class Program
{
    static void Main(string[] args)
    {
        TestAsyncAwaitMethods();
        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }

    public async static void TestAsyncAwaitMethods()
    {
        await LongRunningMethod();
    }

    public static async Task<int> LongRunningMethod()
    {
        Console.WriteLine("Starting Long Running method...");
        await Task.Delay(5000);
        Console.WriteLine("End Long Running method...");
        return 1;
    }
}

And the output is:

Starting Long Running method...
Press any key to exit...
End Long Running method...

Thus,

  1. Main starts the long running method via TestAsyncAwaitMethods. That immediately returns without halting the current thread and we immediately see 'Press any key to exit' message
  2. All this while, the LongRunningMethod is running in the background. Once its completed, another thread from Threadpool picks up this context and displays the final message

Thus, not thread is blocked.

When 1 px border is added to div, Div size increases, Don't want to do that

Try changing border to outline:

outline: 1px solid black;

Best way of invoking getter by reflection

You can invoke reflections and also, set order of sequence for getter for values through annotations

public class Student {

    private String grade;

    private String name;

    private String id;

    private String gender;

    private Method[] methods;

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Order {
        int value();
    }

    /**
     * Sort methods as per Order Annotations
     * 
     * @return
     */
    private void sortMethods() {

        methods = Student.class.getMethods();

        Arrays.sort(methods, new Comparator<Method>() {
            public int compare(Method o1, Method o2) {
                Order or1 = o1.getAnnotation(Order.class);
                Order or2 = o2.getAnnotation(Order.class);
                if (or1 != null && or2 != null) {
                    return or1.value() - or2.value();
                }
                else if (or1 != null && or2 == null) {
                    return -1;
                }
                else if (or1 == null && or2 != null) {
                    return 1;
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

    /**
     * Read Elements
     * 
     * @return
     */
    public void readElements() {
        int pos = 0;
        /**
         * Sort Methods
         */
        if (methods == null) {
            sortMethods();
        }
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
                pos++;
                String value = "";
                try {
                    value = (String) method.invoke(this);
                }
                catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                System.out.println(name + " Pos: " + pos + " Value: " + value);
            }
        }
    }

    // /////////////////////// Getter and Setter Methods

    /**
     * @param grade
     * @param name
     * @param id
     * @param gender
     */
    public Student(String grade, String name, String id, String gender) {
        super();
        this.grade = grade;
        this.name = name;
        this.id = id;
        this.gender = gender;
    }

    /**
     * @return the grade
     */
    @Order(value = 4)
    public String getGrade() {
        return grade;
    }

    /**
     * @param grade the grade to set
     */
    public void setGrade(String grade) {
        this.grade = grade;
    }

    /**
     * @return the name
     */
    @Order(value = 2)
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the id
     */
    @Order(value = 1)
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the gender
     */
    @Order(value = 3)
    public String getGender() {
        return gender;
    }

    /**
     * @param gender the gender to set
     */
    public void setGender(String gender) {
        this.gender = gender;
    }

    /**
     * Main
     * 
     * @param args
     * @throws IOException
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Student student = new Student("A", "Anand", "001", "Male");
        student.readElements();
    }
  }

Output when sorted

getId Pos: 1 Value: 001
getName Pos: 2 Value: Anand
getGender Pos: 3 Value: Male
getGrade Pos: 4 Value: A

Is it possible to specify a different ssh port when using rsync?

I was not able to get rsync to connect via ssh on a different port, but I was able to redirect the ssh connection to the computer I wanted via iptables. This is not the solution I was looking for, but it solved my problem.

How to autoplay HTML5 mp4 video on Android?

Can add muted tag.

<video autoplay muted>
  <source src="video.webm" type="video/webm" />
  <source src="video.mp4" type="video/mp4" />
</video>

reference https://developers.google.com/web/updates/2016/07/autoplay

How to make a WPF window be on top of all other windows of my app (not system wide)?

You can add this to your windows tags

WindowStartupLocation="CenterScreen"

Then you can also display it if you want your users to acknowledge it in order to proceed

YourWindow.ShowDialog();

First try it without TopMost parameters and see the results.

how to delete the content of text file without deleting itself

Simple, write nothing!

FileOutputStream writer = new FileOutputStream("file.txt");
writer.write(("").getBytes());
writer.close();

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

set NODE_ENV=production & nodemon app/app.js

will cause NODE_ENV to contain a space at the end:

process.env.NODE_ENV == 'production'; //false
process.env.NODE_ENV == 'production '; //true

As mentioned in a comment here, use this instead:

NODE_ENV=production&& nodemon app/app.js

Under which circumstances textAlign property works in Flutter?

You can use the container, It will help you to set the alignment.

Widget _buildListWidget({Map reminder}) {
return Container(
  color: Colors.amber,
  alignment: Alignment.centerLeft,
  padding: EdgeInsets.all(20),
  height: 80,
  child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      Container(
        alignment: Alignment.centerLeft,
        child: Text(
          reminder['title'],
          textAlign: TextAlign.left,
          style: TextStyle(
            fontSize: 16,
            color: Colors.black,
            backgroundColor: Colors.blue,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
      Container(
        alignment: Alignment.centerRight,
        child: Text(
          reminder['Date'],
          textAlign: TextAlign.right,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey,
            backgroundColor: Colors.blue,
            fontWeight: FontWeight.normal,
          ),
        ),
      ),
    ],
  ),
);
}

Using subprocess to run Python script on Windows

When you are running a python script on windows in subprocess you should use python in front of the script name. Try:

process = subprocess.Popen("python /the/script.py")

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

Inserting data into a temporary table

insert into #temptable (col1, col2, col3)
select col1, col2, col3 from othertable

Note that this is considered poor practice:

insert into #temptable 
select col1, col2, col3 from othertable

If the definition of the temp table were to change, the code could fail at runtime.

How can I write variables inside the tasks file in ansible

Whenever you have a module followed by a variable on the same line in ansible the parser will treat the reference variable as the beginning of an in-line dictionary. For example:

- name: some example
  command: {{ myapp }} -a foo

The default here is to parse the first part of {{ myapp }} -a foo as a dictionary instead of a string and you will get an error.

So you must quote the argument like so:

- name: some example
  command: "{{ myapp }} -a foo"

Get all child elements

Yes, you can use find_elements_by_ to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html

Example HTML:

<ul class="bar">
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

You can use the find_elements_by_ like so:

parentElement = driver.find_element_by_class_name("bar")
elementList = parentElement.find_elements_by_tag_name("li")

If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.

HTML - how can I show tooltip ONLY when ellipsis is activated

This is what I did. Most tooltip scripts require you to execute a function that stores the tooltips. This is a jQuery example:

$.when($('*').filter(function() {
   return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
   if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
      $(this).attr('title', $(this).text());
   }
})).done(function(){ 
   setupTooltip();
});

If you didn't want to check for ellipsis css, you could simplify like:

$.when($('*').filter(function() {
   return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
   $(this).attr('title', $(this).text());
})).done(function(){ 
   setupTooltip();
});

I have the "when" around it, so that the "setupTooltip" function doesn't execute until all titles have been updated. Replace the "setupTooltip", with your tooltip function and the * with the elements you want to check. * will go through them all if you leave it.

If you simply want to just update the title attributes with the browsers tooltip, you can simplify like:

$('*').filter(function() {
   return $(this).css('text-overflow') == 'ellipsis';
}).each(function() {
   if (this.offsetWidth < this.scrollWidth && !$(this).attr('title')) {
      $(this).attr('title', $(this).text());
   }
});

Or without check for ellipsis:

$.when($('*').filter(function() {
   return (this.offsetWidth < this.scrollWidth && !$(this).attr('title'));
}).each(function() {
   $(this).attr('title', $(this).text());
});

Get current URL/URI without some of $_GET variables

Yii2

Url::current([], true);

or

Url::current();

How can I get the current date and time in UTC or GMT in Java?

If you want to avoid parsing the date and just want a timestamp in GMT, you could use:

final Date gmt = new Timestamp(System.currentTimeMillis()
            - Calendar.getInstance().getTimeZone()
                    .getOffset(System.currentTimeMillis()));

Programmatically get height of navigation bar

Handy Swift 4 extension, in case it's helpful to someone else. Works even if the current view controller does not display a navigation bar.

import UIKit

extension UINavigationController {
  static public func navBarHeight() -> CGFloat {
    let nVc = UINavigationController(rootViewController: UIViewController(nibName: nil, bundle: nil))
    let navBarHeight = nVc.navigationBar.frame.size.height
    return navBarHeight
  }
}

Usage:

UINavigationController.navBarHeight()

Timestamp to human readable format

Hours, minutes and seconds depend on the time zone of your operating system. In GMT (UST) it's 22:00:00 but in different timezones it can be anything. So add the timezone offset to the time to create the GMT date:

var d = new Date();
date = new Date(timestamp*1000 + d.getTimezoneOffset() * 60000)

How to use \n new line in VB msgbox() ...?

An alternative to Environment.NewLine is to use :

Regex.Unescape("\n\tHello World\n")

from System.Text.RegularExpressions

This allows you to escape Text without Concatenating strings as you can in C#, C, java

/usr/bin/ld: cannot find

Add -L/opt/lib to your compiler parameters, this makes the compiler and linker search that path for libcalc.so in that folder.

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

In my case (AWS EC2 instance, Ubuntu) helped:

$ sudo mkdir -p /data/db/
$ sudo chown `USERNAME` /data/db

And after that everything worked fine.

Return a string method in C#

You're currently trying to access a method like a property

Console.WriteLine("{0}",x.fullNameMethod);

It should be

Console.WriteLine("{0}",x.fullNameMethod());

Alternatively you could turn it into a property using

public string fullName
{
   get
   {
        string x = firstName + " " + lastName;
        return x;
   }
}

PHP Composer behind http proxy

Try this:

export HTTPS_PROXY_REQUEST_FULLURI=false

solved this issue for me working behind a proxy at a company few weeks ago.

TypeError: worker() takes 0 positional arguments but 1 was given

class KeyStatisticCollection(DataDownloadUtilities.DataDownloadCollection):
def GenerateAddressStrings(self):
    pass    
def worker(self):
    pass
def DownloadProc(self):
    pass

Simplest way to form a union of two lists

I think this is all you really need to do:

var listB = new List<int>{3, 4, 5};
var listA = new List<int>{1, 2, 3, 4, 5};

var listMerged = listA.Union(listB);

using BETWEEN in WHERE condition

$this->db->where('accommodation BETWEEN '' . $sdate . '' AND '' . $edate . ''');

this is my solution

R cannot be resolved - Android error

What worked for me is installing "Android SDK Build-tools". Open the Android SDK Manager and install the Android SDK build-tools. It also helped to update the Andriod Development Platform in Eclipse: Help > check for updates

PostgreSQL: days/months/years between two dates

SELECT date_part ('year', f) * 12
     + date_part ('month', f)
FROM age ('2015-06-12'::DATE, '2014-12-01'::DATE) f

Result: 6

Clear git local cache

All .idea files that are explicitly ignored are still showing up to commit

you have to remove them from the staging area

git rm --cached .idea

now you have to commit those changes and they will be ignored from this point on.
Once git start to track changes it will not "stop" tracking them even if they were added to the .gitignore file later on.

You must explicitly remove them and then commit your removal manually in order to fully ignore them.


enter image description here

enter image description here

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

Kotlin DSL: add to your build.gradle.kts

tasks.withType<Test> {
        useJUnitPlatform()
}

Gradle DSL: add to your build.gradle

test {
    useJUnitPlatform()
}

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...

http://www.jetbrains.com/idea/features/editions_comparison_matrix.html

it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.

I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.

Anyway this tells that story too... http://www.jetbrains.com/products.html

Spring default behavior for lazy-init

When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".

If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

cout is in std namespace, you shall use std::cout in your code. And you shall not add using namespace std; in your header file, it's bad to mix your code with std namespace, especially don't add it in header file.

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

This Proxy will expose the buffer as any of the TypedArrays, without any copy. :

https://www.npmjs.com/package/node-buffer-as-typedarray

It only works on LE, but can be easily ported to BE. Also, never got to actually test how efficient this is.

php delete a single file in directory

// This code was tested by me (Helio Barbosa)

    // this directory (../backup) is for try only.
    // it is necessary create it and put files into him.

    $hDir = '../backup';
    if ($handle = opendir( $hDir )) {
        echo "Manipulador de diretório: $handle\n";
        echo "Arquivos:\n";

        /* Esta é a forma correta de varrer o diretório */
        /* Here is the correct form to do find files into the directory */
        while (false !== ($file = readdir($handle))) {
            // echo($file . "</br>");
            $filepath = $hDir . "/" . $file ;
            // echo( $filepath . "</br>" );
            if(is_file($filepath))
            {
                echo("Deleting:" . $file . "</br>");
                unlink($filepath);
            }           
        }

        closedir($handle);
    }

Correct way to focus an element in Selenium WebDriver using Java

The focus only works if the window is focused.

Use ((JavascriptExecutor)webDriver).executeScript("window.focus();"); to be sure.

Write to Windows Application Event Log

Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.

*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.

I used this code to write directly to the event log Application:

using (EventLog eventLog = new EventLog("Application")) 
{
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 
}

As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.

What are good examples of genetic algorithms/genetic programming solutions?

I am part of a team investigating the use of Evolutionary Computation (EC) to automatically fix bugs in existing programs. We have successfully repaired a number of real bugs in real world software projects (see this project's homepage).

We have two applications of this EC repair technique.

  • The first (code and reproduction information available through the project page) evolves the abstract syntax trees parsed from existing C programs and is implemented in Ocaml using our own custom EC engine.

  • The second (code and reproduction information available through the project page), my personal contribution to the project, evolves the x86 assembly or Java byte code compiled from programs written in a number of programming languages. This application is implemented in Clojure and also uses its own custom built EC engine.

One nice aspect of Evolutionary Computation is the simplicity of the technique makes it possible to write your own custom implementations without too much difficulty. For a good freely available introductory text on Genetic Programming see the Field Guide to Genetic Programming.

How to compare two strings are equal in value, what is the best method?

You should use some form of the String#equals(Object) method. However, there is some subtlety in how you should do it:

If you have a string literal then you should use it like this:

"Hello".equals(someString);

This is because the string literal "Hello" can never be null, so you will never run into a NullPointerException.

If you have a string and another object then you should use:

myString.equals(myObject);

You can make sure you are actually getting string equality by doing this. For all you know, myObject could be of a class that always returns true in its equals method!

Start with the object less likely to be null because this:

String foo = null;
String bar = "hello";
foo.equals(bar);

will throw a NullPointerException, but this:

String foo = null;
String bar = "hello";
bar.equals(foo);

will not. String#equals(Object) will correctly handle the case when its parameter is null, so you only need to worry about the object you are dereferencing--the first object.

Including JavaScript class definition from another file in Node.js

Another way in addition to the ones provided here for ES6

module.exports = class TEST{
    constructor(size) {
        this.map = new MAp();
        this.size = size;

    }

    get(key) {
        return this.map.get(key);
    }

    length() {
        return this.map.size;
    }    

}

and include the same as

var TEST= require('./TEST');
var test = new TEST(1);

Can't escape the backslash with regex?

The backslash \ is the escape character for regular expressions. Therefore a double backslash would indeed mean a single, literal backslash.

\ (backslash) followed by any of [\^$.|?*+(){} escapes the special character to suppress its special meaning.

ref : http://www.regular-expressions.info/reference.html

Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS

If use this on capitalized text;

p text-transform: lowercase;

Then show the text, it is lowercase but if you copy that lower-cased text, and paste it, it change back to original capitalized.

Still Reachable Leak detected by Valgrind

Since there is some routine from the the pthread family on the bottom (but I don't know that particular one), my guess would be that you have launched some thread as joinable that has terminated execution.

The exit state information of that thread is kept available until you call pthread_join. Thus, the memory is kept in a loss record at program termination, but it is still reachable since you could use pthread_join to access it.

If this analysis is correct, either launch these threads detached, or join them before terminating your program.

Edit: I ran your sample program (after some obvious corrections) and I don't have errors but the following

==18933== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
--18933-- 
--18933-- used_suppression:      2 dl-hack3-cond-1
--18933-- used_suppression:      2 glibc-2.5.x-on-SUSE-10.2-(PPC)-2a

Since the dl- thing resembles much of what you see I guess that you see a known problem that has a solution in terms of a suppression file for valgrind. Perhaps your system is not up to date, or your distribution doesn't maintain these things. (Mine is ubuntu 10.4, 64bit)

What properties can I use with event.target?

An easy way to see all the properties on a particular DOM node in Chrome (I'm on v.69) is to right click on the element, select inspect, and then instead of viewing the "Style" tab click on "Properties".

Inside of the Properties tab you will see all the properties for your particular element.

How to import existing Git repository into another?

I was in a situation where I was looking for -s theirs but of course, this strategy doesn't exist. My history was that I had forked a project on GitHub, and now for some reason, my local master could not be merged with upstream/master although I had made no local changes to this branch. (Really don't know what happened there -- I guess upstream had done some dirty pushes behind the scenes, maybe?)

What I ended up doing was

# as per https://help.github.com/articles/syncing-a-fork/
git fetch upstream
git checkout master
git merge upstream/master
....
# Lots of conflicts, ended up just abandonging this approach
git reset --hard   # Ditch failed merge
git checkout upstream/master
# Now in detached state
git branch -d master # !
git checkout -b master   # create new master from upstream/master

So now my master is again in sync with upstream/master (and you could repeat the above for any other branch you also want to sync similarly).

Generate a random letter in Python

>>> import random
>>> import string
>>> random.choice(string.ascii_letters)
'g'

How to develop or migrate apps for iPhone 5 screen resolution?

Use the Auto Layout feature for views. It will adjust automatically to all resolutions.

Create two xibs for a controller having controller name with suffix either ~iphone or ~ipad. At compile time, Xcode will take the right xib based on the device.

Use size classes, if you want to create a single xib for both iPhone and iPad, if the view is simple enough to port to iPhone and iPad.

ORA-00907: missing right parenthesis

I would recommend separating out all of the foreign-key constraints from your CREATE TABLE statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.

You can add an FK constraint to a table using SQL like the following:

ALTER TABLE orders ADD CONSTRAINT orders_FK
  FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);

In particular, your formats and library tables both have foreign-key constraints on one another. The two CREATE TABLE statements to create these two tables can never run successfully, as each will only work when the other table has already been created.

Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.

Arrays.fill with multidimensional array in Java

This is because a double[][] is an array of double[] which you can't assign 0.0 to (it would be like doing double[] vector = 0.0). In fact, Java has no true multidimensional arrays.

As it happens, 0.0 is the default value for doubles in Java, thus the matrix will actually already be filled with zeros when you get it from new. However, if you wanted to fill it with, say, 1.0 you could do the following:

I don't believe the API provides a method to solve this without using a loop. It's simple enough however to do it with a for-each loop.

double[][] matrix = new double[20][4];

// Fill each row with 1.0
for (double[] row: matrix)
    Arrays.fill(row, 1.0);

How do I resolve "Please make sure that the file is accessible and that it is a valid assembly or COM component"?

'It' requires a dll file called cvextern.dll . 'It' can be either your own cs file or some other third party dll which you are using in your project.

To call native dlls to your own cs file, copy the dll into your project's root\lib directory and add it as an existing item. (Add -Existing item) and use Dllimport with correct location.

For third party , copy the native library to the folder where the third party library resides and add it as an existing item.

After building make sure that the required dlls are appearing in Build folder. In some cases it may not appear or get replaced in Build folder. Delete the Build folder manually and build again.

IIS Manager in Windows 10

Launch Windows Features On/Off and select your IIS options for installation.

For custom site configuration, ensure IIS Management Console is marked for installation under Web Management Tools.

When to use Comparable and Comparator

Use Comparable if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this.

Use Comparator if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour.

How to write text in ipython notebook?

Simply Enter Esc and type m it will convert to text cell.

iterating through Enumeration of hastable keys throws NoSuchElementException error

Every time you call e.nextElement() you take the next object from the iterator. You have to check e.hasMoreElement() between each call.


Example:

while(e.hasMoreElements()){
    String param = e.nextElement();
    System.out.println(param);
}

Test iOS app on device without apple developer program or jailbreak

The JailCoder references above point to a site that does not exist any more. Looks like you should use http://oneiros.altervista.org/jailcoder/ or https://www.facebook.com/jailcoder

How to pass ArrayList of Objects from one to another activity using Intent in android?

Pass your object via Parcelable. And here is a good tutorial to get you started.
First Question should implements Parcelable like this and add the those lines:

public class Question implements Parcelable{
    public Question(Parcel in) {
        // put your data using = in.readString();
  this.operands = in.readString();;
    this.choices = in.readString();;
    this.userAnswerIndex = in.readString();;

    }

    public Question() {
    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(operands);
        dest.writeString(choices);
        dest.writeString(userAnswerIndex);
    }

    public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {

        @Override
        public Question[] newArray(int size) {
            return new Question[size];
        }

        @Override
        public Question createFromParcel(Parcel source) {
            return new Question(source);
        }
    };

}

Then pass your data like this:

Question question = new Question();
// put your data
  Intent resultIntent = new Intent(this, ResultActivity.class);
  resultIntent.putExtra("QuestionsExtra", question);
  startActivity(resultIntent);

And get your data like this:

Question question = new Question();
Bundle extras = getIntent().getExtras();
if(extras != null){
    question = extras.getParcelable("QuestionsExtra");
}

This will do!

Chrome blocks different origin requests

This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).

To avoid it, the browser check the Same-origin policy

Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:

Learning to write a compiler

Big List of Resources:

Legend:

  • ¶ Link to a PDF file
  • $ Link to a printed book

An existing connection was forcibly closed by the remote host - WCF

After pulling my hair out for like 6 hours of this completely useless error, my problem ended up being that my data transfer objects were too complex. Start with uber simple properties like public long Id { get; set;} that's it... nothing fancy.

How to set the background image of a html 5 canvas to .png image

You can use this plugin, but for printing purpose i have added some code like <button onclick="window.print();">Print</button> and for saving image <button onclick="savePhoto();">Save Picture</button>

     function savePhoto() {
     var canvas = document.getElementById("canvas");
     var img    = canvas.toDataURL("image/png");
     window.location = img;}

checkout this plugin http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app

Setting dropdownlist selecteditem programmatically

Well if I understood correctly your question. The Solution for setting the value for a given dropdownlist will be:

dropdownlist1.Text="Your Value";

This will work only if the value is existing in the data-source of the dropdownlist.

'router-outlet' is not a known element

Assuming you are using Angular 6 with angular-cli and you have created a separate routing module which is responsible for routing activities - configure your routes in Routes array.Make sure that you are declaring RouterModule in exports array. Code would look like this:

@NgModule({
      imports: [
      RouterModule,
      RouterModule.forRoot(appRoutes)
     // other imports here
     ],
     exports: [RouterModule]
})
export class AppRoutingModule { }

git remove merge commit from history

Do git rebase -i <sha before the branches diverged> this will allow you to remove the merge commit and the log will be one single line as you wanted. You can also delete any commits that you do not want any more. The reason that your rebase wasn't working was that you weren't going back far enough.

WARNING: You are rewriting history doing this. Doing this with changes that have been pushed to a remote repo will cause issues. I recommend only doing this with commits that are local.

Spring - download response as a file

It is possible to download a file using XHR request. You can use angular $http to load the file and then use Blob feature of HTML5 to make browser save it. There is a library that can help you with saving: FileSaver.js.

How to display a list using ViewBag

I had the problem that I wanted to use my ViewBag to send a list of elements through a RenderPartial as the object, and to this you have to do the cast first, I had to cast the ViewBag in the controller and in the View too.

In the Controller:

ViewBag.visitList = (List<CLIENTES_VIP_DB.VISITAS.VISITA>)                                                                 
visitaRepo.ObtenerLista().Where(m => m.Id_Contacto == id).ToList()

In the View:

List<CLIENTES_VIP_DB.VISITAS.VISITA> VisitaList = (List<CLIENTES_VIP_DB.VISITAS.VISITA>)ViewBag.visitList ;

How can I refresh or reload the JFrame?

Here's a short code that might help.

    <yourJFrameName> main = new <yourJFrameName>();    

    main.setVisible(true);
    this.dispose();

where...

main.setVisible(true);

will run the JFrame again.

this.dispose();

will terminate the running window.

Referring to a Column Alias in a WHERE Clause

If you don't want to list all your columns in CTE, another way to do this would be to use outer apply:

select
    s.logcount, s.logUserID, s.maxlogtm,
    a.daysdiff
from statslogsummary as s
    outer apply (select datediff(day, s.maxlogtm, getdate()) as daysdiff) as a
where a.daysdiff > 120

Is there a way to change the spacing between legend items in ggplot2?

I think the best option is to use guide_legend within guides:

p + guides(fill=guide_legend(
                 keywidth=0.1,
                 keyheight=0.1,
                 default.unit="inch")
      )

Note the use of default.unit , no need to load grid package.

What's a good way to extend Error in JavaScript?

In ES6:

class MyError extends Error {
  constructor(message) {
    super(message);
    this.name = 'MyError';
  }
}

source

Removing empty lines in Notepad++

This worked for me:

  1. Press ctrl + h (Shortcut for replace)
  2. Write one of the following regex in find what box. [\n\r]+$ or ^[\n\r]+
  3. Leave Replace with box blank
  4. In Search Mode, select Regex
  5. Click on Replace All

    Done!

How to produce an csv output file from stored procedure in SQL Server

I think it is possible to use bcp command. I am also new to this command but I followed this link and it worked for me.

Excel VBA - select a dynamic cell range

So it depends on how you want to pick the incrementer, but this should work:

Range("A1:" & Cells(1, i).Address).Select

Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)

If you want the beginning to be dynamic as well, you can try this:

Sub SelectCols()

    Dim Col1 As Integer
    Dim Col2 As Integer

    Col1 = 2
    Col2 = 4

    Range(Cells(1, Col1), Cells(1, Col2)).Select

End Sub

How do I install Python packages on Windows?

Newer versions of Python for Windows come with the pip package manager. (source)

pip is already installed if you're using Python 2 >=2.7.9 or Python 3 >=3.4

Use that to install packages:

cd C:\Python\Scripts\
pip.exe install <package-name>

So in your case it'd be:

pip.exe install mechanize

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

jquery fill dropdown with json data

In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)

    <script>

        $(document).ready(function(){

            GetData('DLState',data,'stateid','statename');
        });

        var data = [{"stateid" : "1","statename" : "Mumbai"},
                    {"stateid" : "2","statename" : "Panjab"},
                    {"stateid" : "3","statename" : "Pune"},
                     {"stateid" : "4","statename" : "Nagpur"},
                     {"stateid" : "5","statename" : "kanpur"}];

        var Did=document.getElementById("DLState");

        function GetData(Did,data,valkey,textkey){
          var str= "";
          for (var i = 0; i <data.length ; i++){

            console.log(data);


            str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";

          }
          $("#"+Did).append(str);
        };    </script>

</head>
<body>
  <select id="DLState">
  </select>
</body>
</html>

Change color of Back button in navigation bar

Swift 4.2

Change complete app theme

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        UINavigationBar.appearance().tintColor = .white

        return true
    }

Change specific controller

let navController = UINavigationController.init(rootViewController: yourViewController) 
navController.navigationBar.tintColor = .red

present(navController, animated: true, completion: nil)

Find integer index of rows with NaN in pandas dataframe

One line solution. However it works for one column only.

df.loc[pandas.isna(df["b"]), :].index

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

CROSS JOIN vs INNER JOIN in SQL

It depends on the output you expect.

A cross join matches all rows in one table to all rows in another table. An inner join matches on a field or fields. If you have one table with 10 rows and another with 10 rows then the two joins will behave differently.

The cross join will have 100 rows returned and they won't be related, just what is called a Cartesian product. The inner join will match records to each other. Assuming one has a primary key and that is a foreign key in the other you would get 10 rows returned.

A cross join has limited general utility, but exists for completeness and describes the result of joining tables with no relations added to the query. You might use a cross join to make lists of combinations of words or something similar. An inner join on the other hand is the most common join.

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

All of the current answers are addressing the symptom (shared memory pool exhaustion), and not the problem, which is likely not using bind variables in your sql \ JDBC queries, even when it does not seem necessary to do so. Passing queries without bind variables causes Oracle to "hard parse" the query each time, determining its plan of execution, etc.

https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:528893984337

Some snippets from the above link:

"Java supports bind variables, your developers must start using prepared statements and bind inputs into it. If you want your system to ultimately scale beyond say about 3 or 4 users -- you will do this right now (fix the code). It is not something to think about, it is something you MUST do. A side effect of this - your shared pool problems will pretty much disappear. That is the root cause. "

"The way the Oracle shared pool (a very important shared memory data structure) operates is predicated on developers using bind variables."

" Bind variables are SO MASSIVELY important -- I cannot in any way shape or form OVERSTATE their importance. "

CSS @font-face not working with Firefox, but working with Chrome and IE

This is a problem with how you setup your font-face's paths. Since you didn't start the path with a "/", Firefox will attempt to find the font's based on the path the stylesheet's in. So basically, Firefox is looking for your font in the "root/css/font" directory instead of the "root/font" directory. You can easily fix this by either moving the font folder to the css folder, or adding a / to the beginning of your font paths.

Try this out:

@font-face {
    font-family: "DroidSerif Regular";
    src: url("/font/droidserif-regular-webfont.eot");
    src: local("DroidSerif Regular"), url("/font/droidserif-regular-webfont.woff") format("woff"), url("/font/droidserif-regular-webfont.ttf") format("truetype"), url("/font/droidserif-regular-webfont.svg#webfontpB9xBi8Q") format("svg");
    font-weight: normal;
    font-style: normal;
}
@font-face {
    font-family: "DroidSerif Bold";
    src: url("/font/droidserif-bold-webfont.eot");
    src: local("DroidSerif Bold"), url("/font/droidserif-bold-webfont.woff") format("woff"), url("/font/droidserif-bold-webfont.ttf") format("truetype"), url("/font/droidserif-bold-webfont.svg#webfontpB9xBi8Q") format("svg");
    font-weight: normal;
    font-style: normal;
}


body {
    font-family: "DroidSerif Regular" , serif;
}
h1 {
    font-weight: bold;
    font-family: "DroidSerif Bold";
}

How can I enable or disable the GPS programmatically on Android?

the GPS can be toggled by exploiting a bug in the power manager widget. see this xda thread for discussion.

here's some example code i use

private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

use the following to test if the existing version of the power control widget is one which will allow you to toggle the gps.

private boolean canToggleGPS() {
    PackageManager pacman = getPackageManager();
    PackageInfo pacInfo = null;

    try {
        pacInfo = pacman.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
    } catch (NameNotFoundException e) {
        return false; //package not found
    }

    if(pacInfo != null){
        for(ActivityInfo actInfo : pacInfo.receivers){
            //test if recevier is exported. if so, we can toggle GPS.
            if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
                return true;
            }
        }
    }

    return false; //default
}

CodeIgniter -> Get current URL relative to base url

In CI v3, you can try:

function partial_uri($start = 0) {
    return join('/',array_slice(get_instance()->uri->segment_array(), $start));
}

This will drop the number of URL segments specified by the $start argument. If your URL is http://localhost/dropbox/derrek/shopredux/ahahaha/hihihi, then:

partial_uri(3);  # returns "ahahaha/hihihi"

Date vs DateTime

Create a wrapper class. Something like this:

public class Date:IEquatable<Date>,IEquatable<DateTime>
    {
        public Date(DateTime date)
        {
            value = date.Date;
        }

        public bool Equals(Date other)
        {
            return other != null && value.Equals(other.value);
        }

        public bool Equals(DateTime other)
        {
            return value.Equals(other);
        }

        public override string ToString()
        {
            return value.ToString();
        }
        public static implicit operator DateTime(Date date)
        {
            return date.value;
        }
        public static explicit operator Date(DateTime dateTime)
        {
            return new Date(dateTime);
        }

        private DateTime value;
    }

And expose whatever of value you want.

How to convert from Hex to ASCII in JavaScript?

You can use this..

_x000D_
_x000D_
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){_x000D_
      return String.fromCharCode(parseInt(v, 16));_x000D_
    }).join('');_x000D_
    _x000D_
document.write(asciiVal);
_x000D_
_x000D_
_x000D_

Unclosed Character Literal error

Character only takes one value dude! like: char y = 'h'; and maybe you typed like char y = 'hello'; or smthg. good luck. for the question asked above the answer is pretty simple u have to use DOUBLE QUOTES to give a string value. easy enough;)

Rename master branch for both local and remote Git repositories

Good. My 2 cents. How about loggin in at the server, going to the git directory and renaming the branch in the bare repository. This does not have all the problems associated with reuploading the same branch. Actually, the 'clients' will automatically recognize the modified name and change their remote reference. Afterwards (or before) you can also modify the local name of the branch.

What is the best way to convert an array to a hash in Ruby

NOTE: For a concise and efficient solution, please see Marc-André Lafortune's answer below.

This answer was originally offered as an alternative to approaches using flatten, which were the most highly upvoted at the time of writing. I should have clarified that I didn't intend to present this example as a best practice or an efficient approach. Original answer follows.


Warning! Solutions using flatten will not preserve Array keys or values!

Building on @John Topley's popular answer, let's try:

a3 = [ ['apple', 1], ['banana', 2], [['orange','seedless'], 3] ]
h3 = Hash[*a3.flatten]

This throws an error:

ArgumentError: odd number of arguments for Hash
        from (irb):10:in `[]'
        from (irb):10

The constructor was expecting an Array of even length (e.g. ['k1','v1,'k2','v2']). What's worse is that a different Array which flattened to an even length would just silently give us a Hash with incorrect values.

If you want to use Array keys or values, you can use map:

h3 = Hash[a3.map {|key, value| [key, value]}]
puts "h3: #{h3.inspect}"

This preserves the Array key:

h3: {["orange", "seedless"]=>3, "apple"=>1, "banana"=>2}

How do I dynamically assign properties to an object in TypeScript?

I tend to put any on the other side i.e. var foo:IFoo = <any>{}; So something like this is still typesafe:

interface IFoo{
    bar:string;
    baz:string;
    boo:string;     
}

// How I tend to intialize 
var foo:IFoo = <any>{};

foo.bar = "asdf";
foo.baz = "boo";
foo.boo = "boo";

// the following is an error, 
// so you haven't lost type safety
foo.bar = 123; 

Alternatively you can mark these properties as optional:

interface IFoo{
    bar?:string;
    baz?:string;
    boo?:string;    
}

// Now your simple initialization works
var foo:IFoo = {};

Try it online

How is a CRC32 checksum calculated?

A CRC is pretty simple; you take a polynomial represented as bits and the data, and divide the polynomial into the data (or you represent the data as a polynomial and do the same thing). The remainder, which is between 0 and the polynomial is the CRC. Your code is a bit hard to understand, partly because it's incomplete: temp and testcrc are not declared, so it's unclear what's being indexed, and how much data is running through the algorithm.

The way to understand CRCs is to try to compute a few using a short piece of data (16 bits or so) with a short polynomial -- 4 bits, perhaps. If you practice this way, you'll really understand how you might go about coding it.

If you're doing it frequently, a CRC is quite slow to compute in software. Hardware computation is much more efficient, and requires just a few gates.

How do the post increment (i++) and pre increment (++i) operators work in Java?

Presuming that you meant

int a=5; int i;

i=++a + ++a + a++;

System.out.println(i);

a=5;

i=a++ + ++a + ++a;

System.out.println(i);

a=5;

a=++a + ++a + a++;

System.out.println(a);

This evaluates to:

i = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)

so i is 6 + 7 + 7 = 20 and so 20 is printed.

i = (5, a is now 6) + (7, a is now 7) + (8, a is now 8)

so i is 5 + 7 + 8 = 20 and so 20 is printed again.

a = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)

and after all of the right hand side is evaluated (including setting a to 8) THEN a is set to 6 + 7 + 7 = 20 and so 20 is printed a final time.

How do I remove the height style from a DIV using jQuery?

$('div#someDiv').removeAttr("height");

How do I rotate text in css?

Using writing-mode and transform.

.rotate {
     writing-mode: vertical-lr;
    -webkit-transform: rotate(-180deg);
    -moz-transform: rotate(-180deg);
}


<span class="rotate">Hello</span>

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

I still remember the first weeks of my programming courses and I totally understand how you feel. Here is the code that solves your problem. In order to learn from this answer, try to run it adding several 'print' in the loop, so you can see the progress of the variables.

import java.util.*;
import java.lang.*;

public class foo
{

   public static void main(String[] args)
   { 
      double[] alpha = new double[50];
      int count = 0;

      for (int i=0; i<50; i++)
      {
          // System.out.print("variable i = " + i + "\n");
          if (i < 25)
          {
                alpha[i] = i*i;
          }
          else {
                alpha[i] = 3*i;
          }

          if (count < 10)
          {
            System.out.print(alpha[i]+ " "); 
          }  
          else {
            System.out.print("\n"); 
            System.out.print(alpha[i]+ " "); 
            count = 0;
          }

          count++;
      }

      System.out.print("\n"); 

    }
}

Default background color of SVG root element

I'm currently working on a file like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/css" href="style.css" ?>
<svg
  xmlns="http://www.w3.org/2000/svg"
  version="1.1"
  width="100%"
  height="100%"
  viewBox="0 0 600 600">
...

And I tried to put this into style.css:

svg {
  background: #bf1f1f;
}

It's working on Chromium and Firefox, but I don't think that it's a good practice. EyeOfGnome image viewer doesn't render it, and Inkscape uses a special namespace to store such a background:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
    xmlns="http://www.w3.org/2000/svg"
    xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
    version="1.1"
    ...
  <sodipodi:namedview
     pagecolor="#480000" ... >

Well, it seems that SVG root element is not part of paintable elements in SVG recommandations.

So I'd suggest to use the "rect" solution provided by Robert Longson because I guess that it is not a simple "hack". It seems to be the standard way to set a background with SVG.

Oracle SQL Developer and PostgreSQL

I've just downloaded SQL Developer 4.0 for OS X (10.9), it just got out of beta. I also downloaded the latest Postgres JDBC jar. On a lark I decided to install it (same method as other third party db drivers in SQL Dev), and it accepted it. Whenever I click "new connection", there is a tab now for Postgres... and clicking it shows a panel that asks for the database connection details.

The answer to this question has changed, whether or not it is supported, it seems to work. There is a "choose database" button, that if clicked, gives you a dropdown list filled with available postgres databases. You create the connection, open it, and it lists the schemas in that database. Most postgres commands seem to work, though no psql commands (\list, etc).

Those who need a single tool to connect to multiple database engines can now use SQL Developer.

How to uncheck a radio button?

Use this

$("input[name='nameOfYourRadioButton']").attr("checked", false);

How to get the user input in Java?

This is a simple code that uses the System.in.read() function. This code just writes out whatever was typed. You can get rid of the while loop if you just want to take input once, and you could store answers in a character array if you so choose.

package main;

import java.io.IOException;

public class Root 
{   
    public static void main(String[] args)
    {
        new Root();
    }

    public Root()
    {
        while(true)
        {
            try
            {
                for(int y = 0; y < System.in.available(); ++y)
                { 
                    System.out.print((char)System.in.read()); 
                }
            }
            catch(IOException ex)
            {
                ex.printStackTrace(System.out);
                break;
            }
        }
    }   
}    

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

Can a local variable's memory be accessed outside its scope?

How can it be? Isn't the memory of a local variable inaccessible outside its function?

You rent a hotel room. You put a book in the top drawer of the bedside table and go to sleep. You check out the next morning, but "forget" to give back your key. You steal the key!

A week later, you return to the hotel, do not check in, sneak into your old room with your stolen key, and look in the drawer. Your book is still there. Astonishing!

How can that be? Aren't the contents of a hotel room drawer inaccessible if you haven't rented the room?

Well, obviously that scenario can happen in the real world no problem. There is no mysterious force that causes your book to disappear when you are no longer authorized to be in the room. Nor is there a mysterious force that prevents you from entering a room with a stolen key.

The hotel management is not required to remove your book. You didn't make a contract with them that said that if you leave stuff behind, they'll shred it for you. If you illegally re-enter your room with a stolen key to get it back, the hotel security staff is not required to catch you sneaking in. You didn't make a contract with them that said "if I try to sneak back into my room later, you are required to stop me." Rather, you signed a contract with them that said "I promise not to sneak back into my room later", a contract which you broke.

In this situation anything can happen. The book can be there -- you got lucky. Someone else's book can be there and yours could be in the hotel's furnace. Someone could be there right when you come in, tearing your book to pieces. The hotel could have removed the table and book entirely and replaced it with a wardrobe. The entire hotel could be just about to be torn down and replaced with a football stadium, and you are going to die in an explosion while you are sneaking around.

You don't know what is going to happen; when you checked out of the hotel and stole a key to illegally use later, you gave up the right to live in a predictable, safe world because you chose to break the rules of the system.

C++ is not a safe language. It will cheerfully allow you to break the rules of the system. If you try to do something illegal and foolish like going back into a room you're not authorized to be in and rummaging through a desk that might not even be there anymore, C++ is not going to stop you. Safer languages than C++ solve this problem by restricting your power -- by having much stricter control over keys, for example.

UPDATE

Holy goodness, this answer is getting a lot of attention. (I'm not sure why -- I considered it to be just a "fun" little analogy, but whatever.)

I thought it might be germane to update this a bit with a few more technical thoughts.

Compilers are in the business of generating code which manages the storage of the data manipulated by that program. There are lots of different ways of generating code to manage memory, but over time two basic techniques have become entrenched.

The first is to have some sort of "long lived" storage area where the "lifetime" of each byte in the storage -- that is, the period of time when it is validly associated with some program variable -- cannot be easily predicted ahead of time. The compiler generates calls into a "heap manager" that knows how to dynamically allocate storage when it is needed and reclaim it when it is no longer needed.

The second method is to have a “short-lived” storage area where the lifetime of each byte is well known. Here, the lifetimes follow a “nesting” pattern. The longest-lived of these short-lived variables will be allocated before any other short-lived variables, and will be freed last. Shorter-lived variables will be allocated after the longest-lived ones, and will be freed before them. The lifetime of these shorter-lived variables is “nested” within the lifetime of longer-lived ones.

Local variables follow the latter pattern; when a method is entered, its local variables come alive. When that method calls another method, the new method's local variables come alive. They'll be dead before the first method's local variables are dead. The relative order of the beginnings and endings of lifetimes of storages associated with local variables can be worked out ahead of time.

For this reason, local variables are usually generated as storage on a "stack" data structure, because a stack has the property that the first thing pushed on it is going to be the last thing popped off.

It's like the hotel decides to only rent out rooms sequentially, and you can't check out until everyone with a room number higher than you has checked out.

So let's think about the stack. In many operating systems you get one stack per thread and the stack is allocated to be a certain fixed size. When you call a method, stuff is pushed onto the stack. If you then pass a pointer to the stack back out of your method, as the original poster does here, that's just a pointer to the middle of some entirely valid million-byte memory block. In our analogy, you check out of the hotel; when you do, you just checked out of the highest-numbered occupied room. If no one else checks in after you, and you go back to your room illegally, all your stuff is guaranteed to still be there in this particular hotel.

We use stacks for temporary stores because they are really cheap and easy. An implementation of C++ is not required to use a stack for storage of locals; it could use the heap. It doesn't, because that would make the program slower.

An implementation of C++ is not required to leave the garbage you left on the stack untouched so that you can come back for it later illegally; it is perfectly legal for the compiler to generate code that turns back to zero everything in the "room" that you just vacated. It doesn't because again, that would be expensive.

An implementation of C++ is not required to ensure that when the stack logically shrinks, the addresses that used to be valid are still mapped into memory. The implementation is allowed to tell the operating system "we're done using this page of stack now. Until I say otherwise, issue an exception that destroys the process if anyone touches the previously-valid stack page". Again, implementations do not actually do that because it is slow and unnecessary.

Instead, implementations let you make mistakes and get away with it. Most of the time. Until one day something truly awful goes wrong and the process explodes.

This is problematic. There are a lot of rules and it is very easy to break them accidentally. I certainly have many times. And worse, the problem often only surfaces when memory is detected to be corrupt billions of nanoseconds after the corruption happened, when it is very hard to figure out who messed it up.

More memory-safe languages solve this problem by restricting your power. In "normal" C# there simply is no way to take the address of a local and return it or store it for later. You can take the address of a local, but the language is cleverly designed so that it is impossible to use it after the lifetime of the local ends. In order to take the address of a local and pass it back, you have to put the compiler in a special "unsafe" mode, and put the word "unsafe" in your program, to call attention to the fact that you are probably doing something dangerous that could be breaking the rules.

For further reading:

git still shows files as modified after adding to .gitignore

The solutions offered here and in other places didn't work for me, so I'll add to the discussion for future readers. I admittedly don't fully understand the procedure yet, but have finally solved my (similar) problem and want to share.

I had accidentally cached some doc-directories with several hundred files when working with git in IntelliJ IDEA on Windows 10, and after adding them to .gitignore (and PROBABLY moving them around a bit) I couldn't get them removed from the Default Changelist.

I first commited the actual changes I had made, then went about solving this - took me far too long. I tried git rm -r --cached . but would always get path-spec ERRORS, with different variations of the path-spec as well as with the -f and -r flags.

git status would still show the filenames, so I tried using some of those verbatim with git rm -cached, but no luck. Stashing and unstashing the changes seemed to work, but they got queued again after a time (I'm a bity hazy on the exact timeframe). I have finally removed these entries for good using

git reset

I assume this is only a GOOD IDEA when you have no changes staged/cached that you actually want to commit.

Python function as a function argument?

Decorators are very powerful in Python since it allows programmers to pass function as argument and can also define function inside another function.

def decorator(func):
      def insideFunction():
        print("This is inside function before execution")
        func()
      return insideFunction

def func():
    print("I am argument function")

func_obj = decorator(func) 
func_obj()

Output

  • This is inside function before execution
  • I am argument function