Programs & Examples On #Cloud

Cloud computing is about hardware-based services involving computing, network and storage capacities. These services are provided on-demand, hosted by the cloud provider and can easily scale up and down.

how to use free cloud database with android app?

As Wingman said, Google App Engine is a great solution for your scenario.

You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android

And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4

What is the difference between Cloud Computing and Grid Computing?

Cloud Computing is For Service Oriented where as Grid Computing is for Application Oriented. Grid computing is used to build Virtual supercomputer using a middler ware to achieve a common task that can be shared among several resources. most probably this task will be kind of computing or data storage.

Cloud computing is providing services over the internet through several servers uses Virtualization.In cloud computing either you can provide service in three types Iaas , Paas, Saas . This will give you solution when you don't have any resources for a short time Business service over the Internet.

What does ECU units, CPU core and memory mean when I launch a instance

For linuxes I've figured out that ECU could be measured by sysbench:

sysbench --num-threads=128 --test=cpu --cpu-max-prime=50000 --max-requests=50000 run

Total time (t) should be calculated by formula:

ECU=1925/t

And my example test results:

|   instance type   |   time   |   ECU   |
|-------------------|----------|---------|
| m1.small          |  1735,62 |       1 |
| m3.xlarge         |   147,62 |      13 |
| m3.2xlarge        |    74,61 |      26 |
| r3.large          |   295,84 |       7 |
| r3.xlarge         |   148,18 |      13 |
| m4.xlarge         |   146,71 |      13 |
| m4.2xlarge        |    73,69 |      26 |
| c4.xlarge         |   123,59 |      16 |
| c4.2xlarge        |    61,91 |      31 |
| c4.4xlarge        |    31,14 |      62 |

What is the recommended way to delete a large number of items from DynamoDB?

According to the DynamoDB documentation you could just delete the full table.

See below:

"Deleting an entire table is significantly more efficient than removing items one-by-one, which essentially doubles the write throughput as you do as many delete operations as put operations"

If you wish to delete only a subset of your data, then you could make separate tables for each month, year or similar. This way you could remove "last month" and keep the rest of your data intact.

This is how you delete a table in Java using the AWS SDK:

DeleteTableRequest deleteTableRequest = new DeleteTableRequest()
  .withTableName(tableName);
DeleteTableResult result = client.deleteTable(deleteTableRequest);

What is the difference between Cloud, Grid and Cluster?

Cluster differs from Cloud and Grid in that a cluster is a group of computers connected by a local area network (LAN), whereas cloud and grid are more wide scale and can be geographically distributed. Another way to put it is to say that a cluster is tightly coupled, whereas a Grid or a cloud is loosely coupled. Also, clusters are made up of machines with similar hardware, whereas clouds and grids are made up of machines with possibly very different hardware configurations.

To know more about cloud computing, I recommend reading this paper: «Above the Clouds: A Berkeley View of Cloud Computing», Michael Armbrust, Armando Fox, Rean Griffith, Anthony D. Joseph, Randy H. Katz, Andrew Konwinski, Gunho Lee, David A. Patterson, Ariel Rabkin, Ion Stoica and Matei Zaharia. The following is an abstract from the above paper:

Cloud Computing refers to both the applications delivered as services over the Internet and the hardware and systems software in the datacenters that provide those services. The services themselves have long been referred to as Software as a Service (SaaS). The datacenter hardware and software is what we call a Cloud. When a Cloud is made available in a pay-as-you-go manner to the general public, we call it a Public Cloud; the service being sold is Utility Computing. We use the term Private Cloud to refer to internal datacenters of a business or other organization, not made available to the general public. Thus, Cloud Computing is the sum of SaaS and Utility Computing, but does not include Private Clouds. People can be users or providers of SaaS, or users or providers of Utility Computing.

The difference between a cloud and a grid can be expressed as below:

  1. Resource distribution: Cloud computing is a centralized model whereas grid computing is a decentralized model where the computation could occur over many administrative domains.

  2. Ownership: A grid is a collection of computers which is owned by multiple parties in multiple locations and connected together so that users can share the combined power of resources. Whereas a cloud is a collection of computers usually owned by a single party.

Examples of Clouds: Amazon Web Services (AWS), Google App Engine.

Examples of Grids: FutureGrid.

Examples of cloud computing services: Dropbox, Gmail, Facebook, Youtube, RapidShare.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

What is SaaS, PaaS and IaaS? With examples

I know this question has been answered a while ago but this could help.

What do the following terms mean?

SaaS

Software as a Service - Essentially, any application that runs with its contents from the cloud is referred to as Software as a Service, As long as you do not own it.

Some examples are Gmail, Netflix, OneDrive etc.

AUDIENCE: End users, everybody

IaaS

Infrastructure as a Service means that the provider allows a portion of their computing power to its customers, It is purchased by the potency of the computing power and they are bundled in Virtual Machines. A company like Google Cloud platform, AWS, Alibaba Cloud can be referred to as IaaS providers because they sell processing powers (servers, storage, networking) to their users in terms of Virtual Machines.

AUDIENCE: IT professionals, System Admins

PaaS

Platform as a Service is more like the middle-man between IaaS and SaaS, Instead of a customer having to deal with the nitty-gritty of servers, networks and storage, everything is readily available by the PaaS providers. Essentially a development environment is initialized to make building applications easier.

Examples would be Heroku, AWS Elastic Beanstalk, Google App Engine etc

AUDIENCE: Software developers.

There are various cloud services available today, such as Amazon's EC2 and AWS, Apache Hadoop, Microsoft Azure and many others. Which category does each belong to and why?

Amazon EC2 and AWS - is an Infrastructure as a Service because you'll need System Administrators to manage the working process of your operating system. There is no abstraction to build a fully featured app ordinarily. Microsoft Azure would also fall under this category following the aforementioned guidelines.

I really haven't used Apache Hadoop, so I really cannot say.

Which programming language for cloud computing?

Of the languages you mention Java, PHP, Python, Ruby, Perl are certainly more platform independent than C/C++ (and ASP.NET).

Lots of platform-specific differences also come from what libraries are available for a given platform.

In practice however, I think you will always develop on the same or at least very similar platform (operating system flavour) as the system where your code will run, i.e. the cloud will not take source code and compile it for you before running it.

Personally I would go for Java or Python (probably also Ruby) as they have a vast number of libraries available for all kinds of tasks and are very platform independent.

Using floats with sprintf() in embedded C

Yes you can. However, it depends on the C-library that you are linking against and you need to be aware of the consequences.

Since you are programming for embedded applications, realise that floating-point support is emulated for a lot of embedded architectures. Compiling in this floating-point support will end up increasing the size of your executable significantly.

Declare a dictionary inside a static class

The correct syntax ( as tested in VS 2008 SP1), is this:

public static class ErrorCode
{
    public static IDictionary<string, string> ErrorCodeDic;
     static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

Socket accept - "Too many open files"

When your program has more open descriptors than the open files ulimit (ulimit -a will list this), the kernel will refuse to open any more file descriptors. Make sure you don't have any file descriptor leaks - for example, by running it for a while, then stopping and seeing if any extra fds are still open when it's idle - and if it's still a problem, change the nofile ulimit for your user in /etc/security/limits.conf

Pass table as parameter into sql server UDF

Cutting to the bottom line, you want a query like SELECT x FROM y to be passed into a function that returns the values as a comma separated string.

As has already been explained you can do this by creating a table type and passing a UDT into the function, but this needs a multi-line statement.

You can pass XML around without declaring a typed table, but this seems to need a xml variable which is still a multi-line statement i.e.

DECLARE @MyXML XML = (SELECT x FROM y FOR XML RAW);
SELECT Dbo.CreateCSV(@MyXml);

The "FOR XML RAW" makes the SQL give you it's result set as some xml.

But you can bypass the variable using Cast(... AS XML). Then it's just a matter of some XQuery and a little concatenation trick:

CREATE FUNCTION CreateCSV (@MyXML XML) 
RETURNS VARCHAR(MAX)
BEGIN
    DECLARE @listStr VARCHAR(MAX);
    SELECT 
            @listStr = 
                COALESCE(@listStr+',' ,'') + 
                c.value('@Value[1]','nvarchar(max)') 
        FROM @myxml.nodes('/row') as T(c)
    RETURN @listStr
END
GO

-- And you call it like this:
SELECT Dbo.CreateCSV(CAST((    SELECT x FROM y    FOR XML RAW) AS XML));

-- Or a working example
SELECT Dbo.CreateCSV(CAST((
        SELECT DISTINCT number AS Value 
        FROM master..spt_values 
        WHERE type = 'P' 
            AND number <= 20
    FOR XML RAW) AS XML));

As long as you use FOR XML RAW all you need do is alias the column you want as Value, as this is hard coded in the function.

How can I run another application within a panel of my C# program?

Another interesting solution to luch an exeternal application with a WinForm container is the follow:

[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);


private void Form1_Load(object sender, EventArgs e)
{
    ProcessStartInfo psi = new ProcessStartInfo("notepad.exe");
    psi.WindowStyle = ProcessWindowStyle.Minimized;
    Process p = Process.Start(psi);
    Thread.Sleep(500);
    SetParent(p.MainWindowHandle, panel1.Handle);
    CenterToScreen();
    psi.WindowStyle = ProcessWindowStyle.Normal;
}

The step to ProcessWindowStyle.Minimized from ProcessWindowStyle.Normal remove the annoying delay.

enter image description here

How can I find my Apple Developer Team id and Team Agent Apple ID?

There are ways you can check even if you are not a paid user. You can confirm TeamID from Xcode. [Build setting] Displayed on tooltip of development team.

How do I set the selenium webdriver get timeout?

The solution of driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS) will work on the pages with synch loading. This does not solve, however, the problem on pages loading stuff in async, then the tests will fail all the time if we set the pageLoadTimeOut.

How to replace a string in a SQL Server Table Column

you need to replace path with the help of replace function.

update table_name set column_name = replace(column_name, 'oldstring', 'newstring')

here column_name refers to that column which you want to change.

Hope it will work.

Can't push to remote branch, cannot be resolved to branch

If you are in local branch, could rename the branch "Feature/Name" to "feature/Name"

git -m feature/Name

if you have problems to make a git push make a checkout in other branch (ex develop) and return to renamed branch

git checkout feature/Name

and try again your git push

Changing an AIX password via script?

printf "oldpassword/nnewpassword/nnewpassword" | passwd user

How to create streams from string in Node.Js?

There's a module for that: https://www.npmjs.com/package/string-to-stream

var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there' 

Java - get the current class name?

Reflection APIs

There are several Reflection APIs which return classes but these may only be accessed if a Class has already been obtained either directly or indirectly.

Class.getSuperclass()
     Returns the super class for the given class.

        Class c = javax.swing.JButton.class.getSuperclass();
        The super class of javax.swing.JButton is javax.swing.AbstractButton.

        Class.getClasses()

Returns all the public classes, interfaces, and enums that are members of the class including inherited members.

        Class<?>[] c = Character.class.getClasses();

Character contains two member classes Character.Subset and
Character.UnicodeBlock.

        Class.getDeclaredClasses()
         Returns all of the classes interfaces, and enums that are explicitly declared in this class.

        Class<?>[] c = Character.class.getDeclaredClasses();
     Character contains two public member classes Character.Subset and Character.UnicodeBlock and one private class

Character.CharacterCache.

        Class.getDeclaringClass()
        java.lang.reflect.Field.getDeclaringClass()
        java.lang.reflect.Method.getDeclaringClass()
        java.lang.reflect.Constructor.getDeclaringClass()
     Returns the Class in which these members were declared. Anonymous Class Declarations will not have a declaring class but will

have an enclosing class.

        import java.lang.reflect.Field;

            Field f = System.class.getField("out");
            Class c = f.getDeclaringClass();
            The field out is declared in System.
            public class MyClass {
                static Object o = new Object() {
                    public void m() {} 
                };
                static Class<c> = o.getClass().getEnclosingClass();
            }

     The declaring class of the anonymous class defined by o is null.

    Class.getEnclosingClass()
     Returns the immediately enclosing class of the class.

    Class c = Thread.State.class().getEnclosingClass();
     The enclosing class of the enum Thread.State is Thread.

    public class MyClass {
        static Object o = new Object() { 
            public void m() {} 
        };
        static Class<c> = o.getClass().getEnclosingClass();
    }
     The anonymous class defined by o is enclosed by MyClass.

How to pass parameters in GET requests with jQuery

The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code

var id=5;
$.ajax({
    type: "get",
    url: "url of server side script",
    data:{id:id},
    success: function(res){
        console.log(res);
    },
error:function(error)
{
console.log(error);
}
});

At server side receive it using $_GET variable.

$_GET['id'];

How to vertical align an inline-block in a line of text?

_x000D_
_x000D_
code {_x000D_
    background: black;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
_x000D_
_x000D_

Tested and works in Safari 5 and IE6+.

jQuery replace one class with another

Starting with the HTML fragment:

<div class='helpTop ...

use the javaScript fragment:

$(...).toggleClass('helpTop').toggleClass('helpBottom');

Find the location of a character in string

You can make the output just 4 and 24 using unlist:

unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired"))
[1]  4 24

Android: checkbox listener

You can do this:

satView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

       @Override
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {

       }
   }
);     

MySQL DROP all tables, ignoring foreign keys

I use the following with a MSSQL server:

if (DB_NAME() = 'YOUR_DATABASE') 
begin
    while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
    begin
         declare @sql nvarchar(2000)
         SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
         FROM information_schema.table_constraints
         WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
         exec (@sql)
         PRINT @sql
    end

    while(exists(select 1 from INFORMATION_SCHEMA.TABLES))
    begin
         declare @sql2 nvarchar(2000)
         SELECT TOP 1 @sql2=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
         FROM INFORMATION_SCHEMA.TABLES
        exec (@sql2)
        PRINT @sql2
    end
end
else
    print('Only run this script on the development server!!!!')

Replace YOUR_DATABASE with the name of your database or remove the entire IF statement (I like the added safety).

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

If your VM already came with VMware Tools pre-installed, but this still isn't working for you--or if you install and still no luck--make sure you run Workstation or Player as Administrator. That fixed the issue for me.

How do I change TextView Value inside Java Code?

First, add a textView in the XML file

<TextView  
    android:id="@+id/rate_id"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/what_U_want_to_display_in_first_time"
    />

then add a button in xml file with id btn_change_textView and write this two line of code in onCreate() method of activity

Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);

then use clickListener() on button object like this

btn.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
      
        textView.setText("write here what u want to display after button click in string");
    }
});

Refresh/reload the content in Div using jquery/ajax

$(document).ready(function() {
var pageRefresh = 5000; //5 s
    setInterval(function() {
        refresh();
    }, pageRefresh);
});

// Functions

function refresh() {
    $('#div1').load(location.href + " #div1");
    $('#div2').load(location.href + " #div2");
}

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Adding label tags around the radio buttons using regular HTML will fix the 'labelfor' issue as well:

<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>

Clicking on the text now selects the appropriate radio button.

why is plotting with Matplotlib so slow?

For the first solution proposed by Joe Kington ( .copy_from_bbox & .draw_artist & canvas.blit), I had to capture the backgrounds after the fig.canvas.draw() line, otherwise the background had no effect and I got the same result as you mentioned. If you put it after the fig.show() it still does not work as proposed by Michael Browne.

So just put the background line after the canvas.draw():

[...]
fig.show()

# We need to draw the canvas before we start animating...
fig.canvas.draw()

# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]

Sublime Text 2 Code Formatting

I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.)

There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the HTMLPrettify.py file - https://github.com/victorporof/Sublime-HTMLPrettify/issues/12

Comparing two columns, and returning a specific adjacent cell in Excel

In cell D2 and copied down:

=IF(COUNTIF($A$2:$A$5,C2)=0,"",VLOOKUP(C2,$A$2:$B$5,2,FALSE))

python pandas dataframe to dictionary

See the docs for to_dict. You can use it like this:

df.set_index('id').to_dict()

And if you have only one column, to avoid the column name is also a level in the dict (actually, in this case you use the Series.to_dict()):

df.set_index('id')['value'].to_dict()

Best way to find the intersection of multiple sets?

As of 2.6, set.intersection takes arbitrarily many iterables.

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s3 = set([2, 4, 6])
>>> s1 & s2 & s3
set([2])
>>> s1.intersection(s2, s3)
set([2])
>>> sets = [s1, s2, s3]
>>> set.intersection(*sets)
set([2])

Twitter Bootstrap button click to toggle expand/collapse text section above button

Elaborating a bit more on Taylor Gautier's reply (sorry, I dont have enough reputation to add a comment), I'd reply to Dean Richardson on how to do what he wanted, without any additional JS code. Pure CSS.

You would replace his .btn with the following:

<a class="btn showdetails" data-toggle="collapse" data-target="#viewdetails"></a>

And add a small CSS for when the content is displayed:

.in.collapse+a.btn.showdetails:before { 
    content:'Hide details «';
}
.collapse+a.btn.showdetails:before { 
    content:'Show details »'; 
}

Here is his modified example

Vlookup referring to table data in a different sheet

Your formula looks fine. Maybe the value you are looking for is not in the first column of the second table?

If the second sheet is in another workbook, you need to add a Workbook reference to your formula:

=VLOOKUP(M3,[Book1]Sheet1!$A$2:$Q$47,13,FALSE)

How to make an anchor tag refer to nothing?

I know this is tagged as a jQuery question, but you can answer this with AngularJS, also.

in your element, add the ng-click directive and use the $event variable which is the click event... prevent its default behavior:

<a href="#" ng-click="$event.preventDefault()">

You can even pass the $event variable into a function:

<a href="#" ng-click="doSomething($event)">

in that function, you do whatever you want with the click event.

how to redirect to home page

document.location.href="/";

or

 window.location.href = "/";

According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location rather than document.location.

See: http://www.w3.org/TR/Window/#window-location

(Note: I copied the difference explanation above, from this question.)

Possible to extend types in Typescript?

May be below approach will be helpful for someone TS with reactjs

interface Event {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent<T> extends Event<T> {
    UserId: string;
}

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

How to use JUnit to test asynchronous processes

Avoid testing with parallel threads whenever you can (which is most of the time). This will only make your tests flaky (sometimes pass, sometimes fail).

Only when you need to call some other library / system, you might have to wait on other threads, in that case always use the Awaitility library instead of Thread.sleep().

Never just call get() or join() in your tests, else your tests might run forever on your CI server in case the future never completes. Always assert isDone() first in your tests before calling get(). For CompletionStage, that is .toCompletableFuture().isDone().

When you test a non-blocking method like this:

public static CompletionStage<String> createGreeting(CompletableFuture<String> future) {
    return future.thenApply(result -> "Hello " + result);
}

then you should not just test the result by passing a completed Future in the test, you should also make sure that your method doSomething() does not block by calling join() or get(). This is important in particular if you use a non-blocking framework.

To do that, test with a non-completed future that you set to completed manually:

@Test
public void testDoSomething() throws Exception {
    CompletableFuture<String> innerFuture = new CompletableFuture<>();
    CompletableFuture<String> futureResult = createGreeting(innerFuture).toCompletableFuture();
    assertFalse(futureResult.isDone());

    // this triggers the future to complete
    innerFuture.complete("world");
    assertTrue(futureResult.isDone());

    // futher asserts about fooResult here
    assertEquals(futureResult.get(), "Hello world");
}

That way, if you add future.join() to doSomething(), the test will fail.

If your Service uses an ExecutorService such as in thenApplyAsync(..., executorService), then in your tests inject a single-threaded ExecutorService, such as the one from guava:

ExecutorService executorService = Executors.newSingleThreadExecutor();

If your code uses the forkJoinPool such as thenApplyAsync(...), rewrite the code to use an ExecutorService (there are many good reasons), or use Awaitility.

To shorten the example, I made BarService a method argument implemented as a Java8 lambda in the test, typically it would be an injected reference that you would mock.

Convert LocalDateTime to LocalDateTime in UTC

public static String convertFromGmtToLocal(String gmtDtStr, String dtFormat, TimeZone lclTimeZone) throws Exception{
        if (gmtDtStr == null || gmtDtStr.trim().equals("")) return null;
        SimpleDateFormat format = new SimpleDateFormat(dtFormat);
        format.setTimeZone(getGMTTimeZone());
        Date dt = format.parse(gmtDtStr);
        format.setTimeZone(lclTimeZone);
        return

format.format(dt); }

How do I add a newline to command output in PowerShell?

Give this a try:

PS> $nl = [Environment]::NewLine
PS> gci hklm:\software\microsoft\windows\currentversion\uninstall | 
        ForEach { $_.GetValue("DisplayName") } | Where {$_} | Sort |
        Foreach {"$_$nl"} | Out-File addrem.txt -Enc ascii

It yields the following text in my addrem.txt file:

Adobe AIR

Adobe Flash Player 10 ActiveX

...

Note: on my system, GetValue("DisplayName") returns null for some entries, so I filter those out. BTW, you were close with this:

ForEach-Object -Process { "$_.GetValue("DisplayName") `n" }

Except that within a string, if you need to access a property of a variable, that is, "evaluate an expression", then you need to use subexpression syntax like so:

Foreach-Object -Process { "$($_.GetValue('DisplayName'))`r`n" }

Essentially within a double quoted string PowerShell will expand variables like $_, but it won't evaluate expressions unless you put the expression within a subexpression using this syntax:

$(`<Multiple statements can go in here`>).

How can I search for a multiline pattern in a file?

Why don't you go for awk:

awk '/Start pattern/,/End pattern/' filename

Convert Dictionary to JSON in Swift

Swift 4 Dictionary extension.

extension Dictionary {
    var jsonStringRepresentation: String? {
        guard let theJSONData = try? JSONSerialization.data(withJSONObject: self,
                                                            options: [.prettyPrinted]) else {
            return nil
        }

        return String(data: theJSONData, encoding: .ascii)
    }
}

Efficient SQL test query or validation query that will work across all (or most) databases

Assuming the OP wants a Java answer:

As of JDBC3 / Java 6 there's the isValid() method which should be used rather than inventing one's own method.

The implementer of the driver is required to execute some sort of query against the database when this method id called. You - as a mere JDBC user - do not have to know or understand what this query is. All you have to do is to trust that the creator of the JDBC driver has done his/her work properly.

How do I conditionally add attributes to React components?

Here is an alternative.

var condition = true;

var props = {
  value: 'foo',
  ...( condition && { disabled: true } )
};

var component = <div { ...props } />;

Or its inline version

var condition = true;

var component = (
  <div
    value="foo"
    { ...( condition && { disabled: true } ) } />
);

How can I get all sequences in an Oracle database?

select sequence_owner, sequence_name from dba_sequences;


DBA_SEQUENCES -- all sequences that exist 
ALL_SEQUENCES  -- all sequences that you have permission to see 
USER_SEQUENCES  -- all sequences that you own

Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES, there is no SEQUENCE_OWNER column in USER_SEQUENCES.

Catching errors in Angular HttpClient

For Angular 6+ , .catch doesn't work directly with Observable. You have to use

.pipe(catchError(this.errorHandler))

Below code:

import { IEmployee } from './interfaces/employee';
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  private url = '/assets/data/employee.json';

  constructor(private http: HttpClient) { }

  getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url)
                    .pipe(catchError(this.errorHandler));  // catch error
  }

  /** Error Handling method */

  errorHandler(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }
}

For more details, refer to the Angular Guide for Http

What is the basic difference between the Factory and Abstract Factory Design Patterns?

With the Factory pattern, you produce instances of implementations (Apple, Banana, Cherry, etc.) of a particular interface -- say, IFruit.

With the Abstract Factory pattern, you provide a way for anyone to provide their own factory. This allows your warehouse to be either an IFruitFactory or an IJuiceFactory, without requiring your warehouse to know anything about fruits or juices.

java: Class.isInstance vs Class.isAssignableFrom

clazz.isAssignableFrom(Foo.class) will be true whenever the class represented by the clazz object is a superclass or superinterface of Foo.

clazz.isInstance(obj) will be true whenever the object obj is an instance of the class clazz.

That is:

clazz.isAssignableFrom(obj.getClass()) == clazz.isInstance(obj)

is always true so long as clazz and obj are nonnull.

How do I return a string from a regex match in python?

Note that re.match(pattern, string, flags=0) only returns matches at the beginning of the string. If you want to locate a match anywhere in the string, use re.search(pattern, string, flags=0) instead (https://docs.python.org/3/library/re.html). This will scan the string and return the first match object. Then you can extract the matching string with match_object.group(0) as the folks suggested.

Is there an API to get bank transaction and bank balance?

Also check out the open financial exchange (ofx) http://www.ofx.net/

This is what apps like quicken, ms money etc use.

Is there a way to follow redirects with command line cURL?

Use the location header flag:

curl -L <URL>

Google Text-To-Speech API

In an update to Schahriar SaffarShargh's answer, Google has recently implemented a 'Google abuse' feature, making it impossible to send just any regular old HTTP GET to a URL such as:

http://translate.google.com/translate_tts?tl=en&q=Hello%20World

which worked just fine and dandy previously. Now, following such a link presents you with a CAPTCHA. This also affects HTTP GET requests out-of-browser (such as with cURL), because using that URL gives a redirect to the abuse protection page (the CAPTCHA).

To start, you have to add the query parameter client to the request URL:

http://translate.google.com/translate_tts?tl=en&q=Hello%20World&client=t

Google Translate sends &client=t, so you should too.

Before you make that HTTP request, make sure that you set the Referer header:

Referer: http://translate.google.com/

Evidently, the User-Agent header is also required, but interestingly enough it can be blank:

User-Agent:

Edit: NOTE - on some user-agents, such as Android 4.X, the custom User-Agent header is not sent, meaning that Google will not service the request. In order to solve that problem, I simply set the User-Agent to a valid one, such as stagefright/1.2 (Linux;Android 5.0). Use Wireshark to debug requests (as I did) if Google's servers are not responding, and ensure that these headers are being set properly in the GET! Google will respond with a 503 Service Unavailable if the request fails, followed by a redirect to the CAPTCHA page.

This solution is a bit brittle; it is entirely possible that Google will change the way they handle these requests in the future, so in the end I would suggest asking Google to make a real API endpoint (free or paid) that we can use without feeling dirty for faking HTTP headers.


Edit 2: For those interested, this cURL command should work perfectly fine to download an mp3 of Hello in English:

curl 'http://translate.google.com/translate_tts?ie=UTF-8&q=Hello&tl=en&client=t' -H 'Referer: http://translate.google.com/' -H 'User-Agent: stagefright/1.2 (Linux;Android 5.0)' > google_tts.mp3

As you may notice, I have set both the Referer and User-Agent headers in the request, as well as added the client=t parameter to the querystring. You may use https instead of http, your choice!


Edit 3: Google now requires a token for each GET request (noted by tk in the querystring). Below is the revised cURL command that will correctly download a TTS mp3:

curl 'https://translate.google.com/translate_tts?ie=UTF-8&q=hello&tl=en&tk=995126.592330&client=t' -H 'user-agent: stagefright/1.2 (Linux;Android 5.0)' -H 'referer: https://translate.google.com/' > google_tts.mp3

Notice the &tk=995126.592330 in the querystring; this is the new token. I obtained this token by pressing the speaker icon on translate.google.com and looking at the GET request. I simply added this querystring parameter to the previous cURL command, and it works.

NOTE: obviously this solution is very frail, and breaks at the whim of the architects at Google who introduce new things like tokens required for the requests. This token may not work tomorrow (though I will check and report back)... the point is, it is not wise to rely on this method; instead, one should turn to a commercial TTS solution, especially if using TTS in production.

For further explanation of the token generation and what you might be able to do about it, see Boude's answer.


If this solution breaks any time in the future, please leave a comment on this answer so that we can attempt to find a fix for it!

Google Maps API v3: Can I setZoom after fitBounds?

To chime in with another solution - I found that the "listen for bounds_changed event and then set new zoom" approach didn't work reliably for me. I think that I was sometimes calling fitBounds before the map had been fully initialized, and the initialization was causing a bounds_changed event that would use up the listener, before fitBounds changed the boundaries and zoom level. I ended up with this code, which seems to work so far:

// If there's only one marker, or if the markers are all super close together,
// `fitBounds` can zoom in too far. We want to limit the maximum zoom it can
// use.
//
// `fitBounds` is asynchronous, so we need to wait until the bounds have
// changed before we know what the new zoom is, using an event handler.
//
// Sometimes this handler gets triggered by a different event, before
// `fitBounds` takes effect; that particularly seems to happen if the map
// hasn't been fully initialized yet. So we don't immediately remove the
// listener; instead, we wait until the 'idle' event, and remove it then.
//
// But 'idle' might happen before 'bounds_changed', so we can't set up the
// removal handler immediately. Set it up in the first event handler.

var removeListener = null;
var listener = google.maps.event.addListener(map, 'bounds_changed', () => {
  console.log(map.getZoom());
  if (map.getZoom() > 15) {
    map.setZoom(15);
  }

  if (!removeListener) {
    removeListener = google.maps.event.addListenerOnce(map, 'idle', () => {
      console.log('remove');
      google.maps.event.removeListener(listener);
    });
  }
});

Accessing dictionary value by index in python

Let us take an example of dictionary:

numbers = {'first':0, 'second':1, 'third':3}

When I did

numbers.values()[index]

I got an error:'dict_values' object does not support indexing

When I did

numbers.itervalues()

to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'

Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.

tuple(numbers.items())[key_index][value_index]

for example:

tuple(numbers.items())[0][0] gives 'first'

if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use

list(list(numbers.items())[index])

java.lang.OutOfMemoryError: GC overhead limit exceeded

For my case increasing the memory using -Xmx option was the solution.

I had a 10g file read in java and each time I got the same error. This happened when the value in the RES column in top command reached to the value set in -Xmx option. Then by increasing the memory using -Xmx option everything went fine.

There was another point as well. When I set JAVA_OPTS or CATALINA_OPTS in my user account and increased the amount of memory again I got the same error. Then, I printed the value of those environment variables in my code which gave me different values than what I set. The reason was that Tomcat was the root for that process and then as I was not a su-doer I asked the admin to increase the memory in catalina.sh in Tomcat.

What is the best way to filter a Java Collection?

Since the early release of Java 8, you could try something like:

Collection<T> collection = ...;
Stream<T> stream = collection.stream().filter(...);

For example, if you had a list of integers and you wanted to filter the numbers that are > 10 and then print out those numbers to the console, you could do something like:

List<Integer> numbers = Arrays.asList(12, 74, 5, 8, 16);
numbers.stream().filter(n -> n > 10).forEach(System.out::println);

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

The redirect function probably works by using the 'refresh' http header (and maybe using a 30X code as well). Once the headers have been sent to the client, there is not way for the server to append that redirect command, its too late.

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

Google Play on Android 4.0 emulator

You could download it from a Android 4.0 phone and then mount the system image rw and copy it over.

Didnt tried it before but it should work.

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

Create a .reg file containing your proxy settings for your users. Create a batch file setting it to setting it to run the .reg file with the extension /s

On a server using a logon script, tell the logon to run the batch file. Jason

Disable dragging an image from an HTML page

This code does exactly what you want. It prevents the image from dragging while allowing any other actions that depend on the event.

$("img").mousedown(function(e){
    e.preventDefault()
});

Move the most recent commit(s) to a new branch with Git

Most of the solutions here count the amount of commits you'd like to go back. I think this is an error prone methodology. Counting would require recounting.

You can simply pass the commit hash of the commit you want to be at HEAD or in other words, the commit you'd like to be the last commit via:

(Notice see commit hash)

To avoid this:

1) git checkout master

2) git branch <feature branch> master

3) git reset --hard <commit hash>

4) git push -f origin master

Is an empty href valid?

Whilst W3's validator may not complain about an empty href attribute, the current HTML5 Working Draft specifies:

The href attribute on a and area elements must have a value that is a valid URL potentially surrounded by spaces.

A valid URL is a URL which complies with the URL Standard. Now the URL Standard is a bit confusing to get your head around, however nowhere does it state that a URL can be an empty string.

...which means that an empty string is not a valid URL.

The HTML5 Working Draft goes on, however, to state:

Note: The href attribute on a and area elements is not required; when those elements do not have href attributes they do not create hyperlinks.

This means we can simply omit the href attribute altogether:

<a class="arrow"></a>

If your intention is that these href-less a elements should still require keyboard interraction, you'll have to go down the normal route of assigning a role and tabindex alongside your usual click/keydown handlers:

<a class="arrow" role="button" tab-index="0"></a>

Convert integer to string Jinja

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

Styling twitter bootstrap buttons

I found the simplest way is to put this in your overrides. Sorry for my unimaginative color choice

Bootstrap 4-Alpha SASS

.my-btn {
  //@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  @include button-variant(red, white, blue);
}

Bootstrap 4 Alpha SASS Example

Bootstrap 3 LESS

.my-btn {
  //.button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border);
  .button-variant(red; white; blue);
}

Bootstrap 3 LESS Example

Bootstrap 3 SASS

.my-btn {
  //@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  @include button-variant(red, white, blue);
}

Bootstrap 3 SASS Example

Bootstrap 2.3 LESS

.btn-primary {
  //.buttonBackground(@btnBackground, @btnBackgroundHighlight, @grayDark, 0 1px 1px rgba(255,255,255,.75));
  .buttonBackground(red, white);
}

Bootstrap 2.3 LESS Example

Bootstrap 2.3 SASS

.btn-primary {
  //@include buttonBackground($btnPrimaryBackground, $btnPrimaryBackgroundHighlight); 
  @include buttonBackground(red, white); 
}

It will take care of the hover/actives for you

From the comments, if you want to lighten the button instead of darken when using black (or just want to inverse) you need to extend the class a bit further like so:

Bootstrap 3 SASS Ligthen

.my-btn {
  // @include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
  $color: #fff;
  $background: #000;
  $border: #333;
  @include button-variant($color, $background, $border);
  // override the default darkening with lightening
  &:hover,
  &:focus,
  &.focus,
  &:active,
  &.active,
  .open > &.dropdown-toggle {
    color: $color;
    background-color: lighten($background, 20%); //10% default
    border-color: lighten($border, 22%); // 12% default
  }
}

Bootstrap 3 SASS Lighten Example

How do I disable "missing docstring" warnings at a file-level in Pylint?

  1. Ctrl + Shift + P

  2. Then type and click on > preferences:configure language specific settings

  3. and then type "python" after that. Paste the code

     {
         "python.linting.pylintArgs": [
             "--load-plugins=pylint_django", "--errors-only"
         ],
     }
    

JavaScript: Global variables after Ajax requests

What you expect is the synchronous (blocking) type request.

var it_works = false;

jQuery.ajax({
  type: "POST",
  url: 'some_file.php',
  success: function (data) {
    it_works = true;
  }, 
  async: false // <- this turns it into synchronous
});?

// Execution is BLOCKED until request finishes.

// it_works is available
alert(it_works);

Requests are asynchronous (non-blocking) by default which means that the browser won't wait for them to be completed in order to continue its work. That's why your alert got wrong result.

Now, with jQuery.ajax you can optionally set the request to be synchronous, which means that the script will only continue to run after the request is finished.


The RECOMMENDED way, however, is to refactor your code so that the data would be passed to a callback function as soon as the request is finished. This is preferred because blocking execution means blocking the UI which is unacceptable. Do it this way:

$.post("some_file.php", '', function(data) {
    iDependOnMyParameter(data);
});

function iDependOnMyParameter(param) {
    // You should do your work here that depends on the result of the request!
    alert(param)
}

// All code here should be INDEPENDENT of the result of your AJAX request
// ...

Asynchronous programming is slightly more complicated because the consequence of making a request is encapsulated in a function instead of following the request statement. But the realtime behavior that the user experiences can be significantly better because they will not see a sluggish server or sluggish network cause the browser to act as though it had crashed. Synchronous programming is disrespectful and should not be employed in applications which are used by people.

Douglas Crockford (YUI Blog)

How to embed a .mov file in HTML?

Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag

Example:

<video controls="controls" width="800" height="600" 
       name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>

This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)

Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)

C# Equivalent of SQL Server DataTypes

SQL Server and the .NET Framework are based on different type systems. For example, the .NET Framework Decimal structure has a maximum scale of 28, whereas the SQL Server decimal and numeric data types have a maximum scale of 38. Click Here's a link! for detail

https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Make sure you have a start page specified, as well. Right click on the .aspx page you want to use as your start page and choose "Set as start page"

Can I give a default value to parameters or optional parameters in C# functions?

Yes, but you'll need to be using .NET 3.5 and C# 4.0 to get this functionality.

This MSDN page has more information.

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Hardware

If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).

Software

threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).

Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).

Now a simple case: processing a 512x512 image

Suppose we want one thread to process one pixel (i,j).

We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)

It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.

dim3 threadsPerBlock(8, 8);  // 64 threads

and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.

dim3 numBlocks(imageWidth/threadsPerBlock.x,  /* for instance 512/8 = 64*/
              imageHeight/threadsPerBlock.y); 

The kernel is launched like this:

myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );       

Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.

In the kernel the pixel (i,j) to be processed by a thread is calculated this way:

uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;

Cookies on localhost with explicit domain

Results I had varied by browser.

Chrome- 127.0.0.1 worked but localhost .localhost and "" did not. Firefox- .localhost worked but localhost, 127.0.0.1, and "" did not.

Have not tested in Opera, IE, or Safari

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

For me it only worked when the certificate and both keys were in the Login keychain. I had created a Development keychain before, but the Xcode Organizer wouldn't find the keys in there. So I moved them back to Login, quit the keychain tool - and voila, the error in Xcode Organizer went away! This was on Snow Leopard 10.6.2 with the 3.1.3 SDK.

CSS full screen div with text in the middle

The accepted answer works, but if:

  • you don't know the content's dimensions
  • the content is dynamic
  • you want to be future proof

use this:

.centered {
  position: fixed; /* or absolute */
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

More information about centering content in this excellent CSS-Tricks article.


Also, if you don't need to support old browsers: a flex-box makes this a piece of cake:

.center{
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

Another great guide about flexboxs from CSS Tricks; http://css-tricks.com/snippets/css/a-guide-to-flexbox/

Execute external program

This is not right. Here's how you should use Runtime.exec(). You might also try its more modern cousin, ProcessBuilder:

Java Runtime.getRuntime().exec() alternatives

How to center cards in bootstrap 4?

You can also use Bootstrap 4 flex classes

Like: .align-item-center and .justify-content-center

We can use these classes identically for all device view.

Like: .align-item-sm-center, .align-item-md-center, .justify-content-xl-center, .justify-content-lg-center, .justify-content-xs-center

.text-center class is used to align text in center.

How to show soft-keyboard when edittext is focused

In your onResume() section of the Activity you can do call the method bringKeyboard();

 onResume() {
     EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
     bringKeyboard(yourEditText);
 }


  protected boolean bringKeyboard(EditText view) {
    if (view == null) {
        return false;
    }
    try {
      // Depending if edittext has some pre-filled values you can decide whether to bring up soft keyboard or not
        String value = view.getText().toString();
        if (value == null) {
            InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            return true;
        }
    } catch (Exception e) {
        Log.e(TAG, "decideFocus. Exception", e);
    }
    return false;
  }

Installing a plain plugin jar in Eclipse 3.5

Since the advent of p2, you should be using the dropins directory instead.

To be completely clear create "plugins" under "/dropins" and make sure to restart eclipse with the "-clean" option.

jQuery onclick event for <li> tags

Typing in $(this) will return the jQuery element instead of the HTML Element. Then it just depends on what you want to do in the click event.

alert($(this));

Is having an 'OR' in an INNER JOIN condition a bad idea?

This kind of JOIN is not optimizable to a HASH JOIN or a MERGE JOIN.

It can be expressed as a concatenation of two resultsets:

SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

, each of them being an equijoin, however, SQL Server's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).

How to return rows from left table not found in right table?

This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.

As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.

Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

You're looking for a query such as:

DECLARE @table1 TABLE (test int)
DECLARE @table2 TABLE (test int)

INSERT INTO @table1
(
    test
)
SELECT 1
UNION ALL SELECT 2

INSERT INTO @table2
(
    test
)
SELECT 1
UNION ALL SELECT 3

-- Here's the important part
SELECT  a.*
FROM    @table1 a
LEFT    join @table2 b on a.test = b.test -- this will return all rows from a
WHERE   b.test IS null -- this then excludes that which exist in both a and b

-- Returned results:

2

DISABLE the Horizontal Scroll

So to fix this properly, I did what others here did and used css to get hide the horizontal toolbar:

.name {
  max-width: 100%;
  overflow-x: hidden;
}

Then in js, I created an event listener to look for scrolling, and counteracted the users attempted horizontal scroll.

var scrollEventHandler = function()
{
  window.scroll(0, window.pageYOffset)
}

window.addEventListener("scroll", scrollEventHandler, false);

I saw somebody do something similar, but apparently that didn't work. This however is working perfectly fine for me.

Looking for a short & simple example of getters/setters in C#

well here is common usage of getter setter in actual use case,

public class OrderItem 
{
public int Id {get;set;}
public int quantity {get;set;}
public int Price {get;set;}
public int TotalAmount {get {return this.quantity *this.Price;}set;}
}

How can I give eclipse more memory than 512M?

I've had a lot of problems trying to get Eclipse to accept as much memory as I'd like it to be able to use (between 2 and 4 gigs for example).

Open eclipse.ini in the Eclipse installation directory. You should be able to change the memory sizes after -vmargs up to 1024 without a problem up to some maximum value that's dependent on your system. Here's that section on my Linux box:

-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=512m
-Xms512m
-Xmx1024m

And here's that section on my Windows box:

-vmargs
-Xms256m
-Xmx1024m

But, I've failed at setting it higher than 1024 megs. If anybody knows how to make that work, I'd love to know.

EDIT: 32bit version of juno seems to not accept more than Xmx1024m where the 64 bit version accept 2048.

EDIT: Nick's post contains some great links that explain two different things:

  • The problem is largely dependent on your system and the amount of contiguous free memory available, and
  • By using javaw.exe (on Windows), you may be able to get a larger allocated block of memory.

I have 8 gigs of Ram and can't set -Xmx to more than 1024 megs of ram, even when a minimal amount of programs are loaded and both windows/linux report between 4 and 5 gigs of free ram.

how to zip a folder itself using java

Java 6 +

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Zip {

    private static final FileFilter FOLDER_FILTER = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    };

    private static final FileFilter FILE_FILTER = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isFile();
        }
    };


    private static void compress(File file, ZipOutputStream outputStream, String path) throws IOException {

        if (file.isDirectory()) {
            File[] subFiles = file.listFiles(FILE_FILTER);
            if (subFiles != null) {
                for (File subFile : subFiles) {
                    compress(subFile, outputStream, new File(path, subFile.getName()).getAbsolutePath());
                }
            }
            File[] subDirs = file.listFiles(FOLDER_FILTER);
            if (subDirs != null) {
                for (File subDir : subDirs) {
                    compress(subDir, outputStream, new File(path, subDir.getName()).getAbsolutePath());
                }
            }
        } else if (file.exists()) {
            outputStream.putNextEntry(new ZipEntry(path));
            FileInputStream inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) >= 0) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.closeEntry();
        }
    }

    public static void compress(String dirPath, String zipFilePath) throws IOException {
        File file = new File(dirPath);
        final ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(zipFilePath));
        compress(file, outputStream, "/");
        outputStream.close();
    }

}

How to check if a std::string is set or not?

Use empty():

std::string s;

if (s.empty())
    // nothing in s

Creating a static class with no instances

The Pythonic way to create a static class is simply to declare those methods outside of a class (Java uses classes both for objects and for grouping related functions, but Python modules are sufficient for grouping related functions that do not require any object instance). However, if you insist on making a method at the class level that doesn't require an instance (rather than simply making it a free-standing function in your module), you can do so by using the "@staticmethod" decorator.

That is, the Pythonic way would be:

# My module
elements = []

def add_element(x):
  elements.append(x)

But if you want to mirror the structure of Java, you can do:

# My module
class World(object):
  elements = []

  @staticmethod
  def add_element(x):
    World.elements.append(x)

You can also do this with @classmethod if you care to know the specific class (which can be handy if you want to allow the static method to be inherited by a class inheriting from this class):

# My module
class World(object):
  elements = []

  @classmethod
  def add_element(cls, x):
    cls.elements.append(x)

Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

This is actually a better solution I've found. Uses jQuery however it works perfectly. Also it refreshes automatically similar to the way SO and Facebook does so you don't have to refresh the page to see the updates.

This plugin will read your datetime attr in the <time> tag and fill it in for you.

e.g. "4 minutes ago" or "about 1 day ago

http://timeago.yarp.com/

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

What are ABAP and SAP?

SAP is a company and offers a full Enterprise Resource Planning (ERP) system, business platform, and the associated modules (financials, general ledger, &c).

ABAP is the primary programming language used to write SAP software and customizations. It would do it injustice to think of it as COBOL and SQL on steroids, but that gives you an idea. ABAP runs within the SAP system.

SAP and ABAP abstract the DB and run atop various underlying DBMSs.

SAP produces other things as well and even publicly says they dabble in Java and even produce a J2EE container, but tried-and-true SAP is ABAP through-and-through.

What's the best way to set a single pixel in an HTML5 canvas?

Since different browsers seems to prefer different methods, maybe it would make sense to do a smaller test with all three methods as a part of the loading process to find out which is best to use and then use that throughout the application?

Calling onclick on a radiobutton list using javascript

I agree with @annakata that this question needs some more clarification, but here is a very, very basic example of how to setup an onclick event handler for the radio buttons:

<html>
 <head>
  <script type="text/javascript">
    window.onload = function() {

        var ex1 = document.getElementById('example1');
        var ex2 = document.getElementById('example2');
        var ex3 = document.getElementById('example3');

        ex1.onclick = handler;
        ex2.onclick = handler;
        ex3.onclick = handler;

    }

    function handler() {
        alert('clicked');
    }
  </script>
 </head>
 <body>
  <input type="radio" name="example1" id="example1" value="Example 1" />
  <label for="example1">Example 1</label>
  <input type="radio" name="example2" id="example2" value="Example 2" />
  <label for="example1">Example 2</label>
  <input type="radio" name="example3" id="example3" value="Example 3" />
  <label for="example1">Example 3</label>
 </body>
</html>

How to extract one column of a csv file

Been using this code for a while, it is not "quick" unless you count "cutting and pasting from stackoverflow".

It uses ${##} and ${%%} operators in a loop instead of IFS. It calls 'err' and 'die', and supports only comma, dash, and pipe as SEP chars (that's all I needed).

err()  { echo "${0##*/}: Error:" "$@" >&2; }
die()  { err "$@"; exit 1; }

# Return Nth field in a csv string, fields numbered starting with 1
csv_fldN() { fldN , "$1" "$2"; }

# Return Nth field in string of fields separated
# by SEP, fields numbered starting with 1
fldN() {
        local me="fldN: "
        local sep="$1"
        local fldnum="$2"
        local vals="$3"
        case "$sep" in
                -|,|\|) ;;
                *) die "$me: arg1 sep: unsupported separator '$sep'" ;;
        esac
        case "$fldnum" in
                [0-9]*) [ "$fldnum" -gt 0 ] || { err "$me: arg2 fldnum=$fldnum must be number greater or equal to 0."; return 1; } ;;
                *) { err "$me: arg2 fldnum=$fldnum must be number"; return 1;} ;;
        esac
        [ -z "$vals" ] && err "$me: missing arg2 vals: list of '$sep' separated values" && return 1
        fldnum=$(($fldnum - 1))
        while [ $fldnum -gt 0 ] ; do
                vals="${vals#*$sep}"
                fldnum=$(($fldnum - 1))
        done
        echo ${vals%%$sep*}
}

Example:

$ CSVLINE="example,fields with whitespace,field3"
$ $ for fno in $(seq 3); do echo field$fno: $(csv_fldN $fno "$CSVLINE");  done
field1: example
field2: fields with whitespace
field3: field3

@Cacheable key on multiple method arguments

You can use a Spring-EL expression, for eg on JDK 1.7:

@Cacheable(value="bookCache", key="T(java.util.Objects).hash(#p0,#p1, #p2)")

Remove characters from a String in Java

String id = id.substring(0,id.length()-4)

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

How to: Install Plugin in Android Studio

2019: With Android Studio 3.4.2 started:

  1. Click on File -> Settings
  2. Find "Plugins" in the left pane of the popup window and click on it
  3. Click on the Gear in the upper right
  4. Click on "Install Plugin from Disk"
  5. Find your plugin from the file browser or drag and drop it from another window to go to it in the browse window, then click on it then click "OK"
  6. The browse window will close
  7. Click "OK" on the setting window
  8. Click "Restart" on the popup

Convert a date format in epoch

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:

String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454

Date.getTime() returns the epoch time in milliseconds.

How do you convert a JavaScript date to UTC?

You can use the following method to convert any js date to UTC:

let date = new Date(YOUR_DATE).toISOString()

// It would give the date in format "2020-06-16T12:30:00.000Z" where Part before T is date in YYYY-MM-DD format, part after T is time in format HH:MM:SS  and Z stands for UTC - Zero hour offset

DELETE ... FROM ... WHERE ... IN

The canonical T-SQL (SqlServer) answer is to use a DELETE with JOIN as such

DELETE o
FROM Orders o
INNER JOIN Customers c
    ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'

This will delete all orders which have a customer with first name Sklivvz.

Get GPS location from the web browser

Use this, and you will find all informations at http://www.w3schools.com/html/html5_geolocation.asp

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
}
</script>

How do you change the width and height of Twitter Bootstrap's tooltips?

Another solution; create a new class (e.g. tooltip-wide) in CSS:

.tooltip-wide + .tooltip > .tooltip-inner {
     max-width: 100%;
}

Use this class on elements where you want wide tooltips:

<div class="tooltip-wide" data-toggle="tooltip" title="I am a long tooltip">Long tooltip</div>

Bootstrap tooltip generates markup below the element containing the tooltip, so the HTML actually looks something like this after the markup is generated:

<div class="tooltip-wide" data-toggle="tooltip" title="I am a long tooltip">Long tooltip</div>
<div class="tooltip" role="tooltip">
    <div class="tooltip-arrow"></div>
    <div class="tooltip-inner">I am a long tooltip</div>
</div>

The CSS uses this to access the adjacent element (+) to .tooltip-wide, and from there navigates to .tooltip-inner, before applying the max-width attribute. This will only affect elements using the .tooltip-wide class, all other tooltips will remain unaltered.

Docker command can't connect to Docker daemon

After installing docker on Ubuntu, I ran the following command:

sudo service docker start

Have you tried it?

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

Curly braces. Passing keyword arguments into dict(), though it works beautifully in a lot of scenarios, can only initialize a map if the keys are valid Python identifiers.

This works:

a = {'import': 'trade', 1: 7.8}
a = dict({'import': 'trade', 1: 7.8})

This won't work:

a = dict(import='trade', 1=7.8)

It will result in the following error:

    a = dict(import='trade', 1=7.8)
             ^
SyntaxError: invalid syntax

Regular expression for exact match of a string

A more straight forward way is to check for equality

if string1 == string2
  puts "match"
else
  puts "not match"
end

however, if you really want to stick to regular expression,

string1 =~ /^123456$/

'gulp' is not recognized as an internal or external command

I had the same problem on windows 7. You must edit your path system variable manually.

Go to START -> edit the system environment variables -> Environment variables -> in system part find variables "Path" -> edit -> add new path after ";" to your file gulp.cmd directory some like ';C:\Users\YOURUSERNAME\AppData\Roaming\npm' -> click ok and close these windows -> restart your CLI -> enjoy

Is a Java hashmap search really O(1)?

You seem to mix up worst-case behaviour with average-case (expected) runtime. The former is indeed O(n) for hash tables in general (i.e. not using a perfect hashing) but this is rarely relevant in practice.

Any dependable hash table implementation, coupled with a half decent hash, has a retrieval performance of O(1) with a very small factor (2, in fact) in the expected case, within a very narrow margin of variance.

How can I express that two values are not equal to eachother?

If the class implements comparable, you could also do

int compRes = a.compareTo(b);
if(compRes < 0 || compRes > 0)
    System.out.println("not equal");
else
    System.out.println("equal);

doesn't use a !, though not particularly useful, or readable....

What is the difference between Task.Run() and Task.Factory.StartNew()

People already mentioned that

Task.Run(A);

Is equivalent to

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

But no one mentioned that

Task.Factory.StartNew(A);

Is equivalent to:

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current);

As you can see two parameters are different for Task.Run and Task.Factory.StartNew:

  1. TaskCreationOptions - Task.Run uses TaskCreationOptions.DenyChildAttach which means that children tasks can not be attached to the parent, consider this:

    var parentTask = Task.Run(() =>
    {
        var childTask = new Task(() =>
        {
            Thread.Sleep(10000);
            Console.WriteLine("Child task finished.");
        }, TaskCreationOptions.AttachedToParent);
        childTask.Start();
    
        Console.WriteLine("Parent task finished.");
    });
    
    parentTask.Wait();
    Console.WriteLine("Main thread finished.");
    

    When we invoke parentTask.Wait(), childTask will not be awaited, even though we specified TaskCreationOptions.AttachedToParent for it, this is because TaskCreationOptions.DenyChildAttach forbids children to attach to it. If you run the same code with Task.Factory.StartNew instead of Task.Run, parentTask.Wait() will wait for childTask because Task.Factory.StartNew uses TaskCreationOptions.None

  2. TaskScheduler - Task.Run uses TaskScheduler.Default which means that the default task scheduler (the one that runs tasks on Thread Pool) will always be used to run tasks. Task.Factory.StartNew on the other hand uses TaskScheduler.Current which means scheduler of the current thread, it might be TaskScheduler.Default but not always. In fact when developing Winforms or WPF applications it is required to update UI from the current thread, to do this people use TaskScheduler.FromCurrentSynchronizationContext() task scheduler, if you unintentionally create another long running task inside task that used TaskScheduler.FromCurrentSynchronizationContext() scheduler the UI will be frozen. A more detailed explanation of this can be found here

So generally if you are not using nested children task and always want your tasks to be executed on Thread Pool it is better to use Task.Run, unless you have some more complex scenarios.

How to calculate the angle between a line and the horizontal axis?

import math
from collections import namedtuple


Point = namedtuple("Point", ["x", "y"])


def get_angle(p1: Point, p2: Point) -> float:
    """Get the angle of this line with the horizontal axis."""
    dx = p2.x - p1.x
    dy = p2.y - p1.y
    theta = math.atan2(dy, dx)
    angle = math.degrees(theta)  # angle is in (-180, 180]
    if angle < 0:
        angle = 360 + angle
    return angle

Testing

For testing I let hypothesis generate test cases.

enter image description here

import hypothesis.strategies as s
from hypothesis import given


@given(s.floats(min_value=0.0, max_value=360.0))
def test_angle(angle: float):
    epsilon = 0.0001
    x = math.cos(math.radians(angle))
    y = math.sin(math.radians(angle))
    p1 = Point(0, 0)
    p2 = Point(x, y)
    assert abs(get_angle(p1, p2) - angle) < epsilon

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

I'd say it depends on what you need it for:

  1. If you need it just to get 3 columns layout, I'd suggest to do it with float.

  2. If you need it for menu, you can use inline-block. For the whitespace problem, you can use few tricks as described by Chris Coyier here http://css-tricks.com/fighting-the-space-between-inline-block-elements/.

  3. If you need to make a multiple choice option, which the width needs to spread evenly inside a specified box, then I'd prefer display: table. This will not work correctly in some browsers, so it depends on your browser support.

Lastly, what might be the best method is using flexbox. The spec for this has changed few times, so it's not stable just yet. But once it has been finalized, this will be the best method I reckon.

Close a MessageBox after several seconds

There is an codeproject project avaliable HERE that provides this functuanility.

Following many threads here on SO and other boards this cant be done with the normal MessageBox.

Edit:

I have an idea that is a bit ehmmm yeah..

Use a timer and start in when the MessageBox appears. If your MessageBox only listens to the OK Button (only 1 possibility) then use the OnTick-Event to emulate an ESC-Press with SendKeys.Send("{ESC}"); and then stop the timer.

How can I parse a YAML file in Python

Read & Write YAML files with Python 2+3 (and unicode)

# -*- coding: utf-8 -*-
import yaml
import io

# Define data
data = {
    'a list': [
        1, 
        42, 
        3.141, 
        1337, 
        'help', 
        u'€'
    ],
    'a string': 'bla',
    'another dict': {
        'foo': 'bar',
        'key': 'value',
        'the answer': 42
    }
}

# Write YAML file
with io.open('data.yaml', 'w', encoding='utf8') as outfile:
    yaml.dump(data, outfile, default_flow_style=False, allow_unicode=True)

# Read YAML file
with open("data.yaml", 'r') as stream:
    data_loaded = yaml.safe_load(stream)

print(data == data_loaded)

Created YAML file

a list:
- 1
- 42
- 3.141
- 1337
- help
- €
a string: bla
another dict:
  foo: bar
  key: value
  the answer: 42

Common file endings

.yml and .yaml

Alternatives

For your application, the following might be important:

  • Support by other programming languages
  • Reading / writing performance
  • Compactness (file size)

See also: Comparison of data serialization formats

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

Using async/await with a forEach loop

In addition to @Bergi’s answer, I’d like to offer a third alternative. It's very similar to @Bergi’s 2nd example, but instead of awaiting each readFile individually, you create an array of promises, each which you await at the end.

import fs from 'fs-promise';
async function printFiles () {
  const files = await getFilePaths();

  const promises = files.map((file) => fs.readFile(file, 'utf8'))

  const contents = await Promise.all(promises)

  contents.forEach(console.log);
}

Note that the function passed to .map() does not need to be async, since fs.readFile returns a Promise object anyway. Therefore promises is an array of Promise objects, which can be sent to Promise.all().

In @Bergi’s answer, the console may log file contents in the order they’re read. For example if a really small file finishes reading before a really large file, it will be logged first, even if the small file comes after the large file in the files array. However, in my method above, you are guaranteed the console will log the files in the same order as the provided array.

Permutations in JavaScript?

If you notice, the code actually splits the chars into an array prior to do any permutation, so you simply remove the join and split operation

_x000D_
_x000D_
var permArr = [],_x000D_
  usedChars = [];_x000D_
_x000D_
function permute(input) {_x000D_
  var i, ch;_x000D_
  for (i = 0; i < input.length; i++) {_x000D_
    ch = input.splice(i, 1)[0];_x000D_
    usedChars.push(ch);_x000D_
    if (input.length == 0) {_x000D_
      permArr.push(usedChars.slice());_x000D_
    }_x000D_
    permute(input);_x000D_
    input.splice(i, 0, ch);_x000D_
    usedChars.pop();_x000D_
  }_x000D_
  return permArr_x000D_
};_x000D_
_x000D_
_x000D_
document.write(JSON.stringify(permute([5, 3, 7, 1])));
_x000D_
_x000D_
_x000D_

How to cast List<Object> to List<MyClass>

You can use a double cast.

return (List<Customer>) (List) getList();

HTML <sup /> tag affecting line height, how to make it consistent?

I had the same problem and non of the given answers worked. But I found a git commit with a fix that did work for me:

sup {
  font-size: 0.8em;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
  top: -0.5em;
}

Pip install Matplotlib error with virtualenv

If on MacOSx try

xcode-select --install

This complies subprocess 32, the reason for the failure.

Android Studio Gradle Already disposed Module

Sometimes gradlew clean or Invalidate Cache and Restart does not help, because these methods do not clean Android Studio specific files by themselves.

In this case, close AS and remove .idea directory and .iml file in a root project where settings.gradle file exists. This will make AS rebuild from the fresh ground.

How/When does Execute Shell mark a build as failure in Jenkins?

In Jenkins ver. 1.635, it is impossible to show a native environment variable like this:

$BUILD_NUMBER or ${BUILD_NUMBER}

In this case, you have to set it in an other variable.

set BUILDNO = $BUILD_NUMBER
$BUILDNO

Asyncio.gather vs asyncio.wait

I also noticed that you can provide a group of coroutines in wait() by simply specifying the list:

result=loop.run_until_complete(asyncio.wait([
        say('first hello', 2),
        say('second hello', 1),
        say('third hello', 4)
    ]))

Whereas grouping in gather() is done by just specifying multiple coroutines:

result=loop.run_until_complete(asyncio.gather(
        say('first hello', 2),
        say('second hello', 1),
        say('third hello', 4)
    ))

Grep and Python

The natural question is why not just use grep?! But assuming you can't...

import re
import sys

file = open(sys.argv[2], "r")

for line in file:
     if re.search(sys.argv[1], line):
         print line,

Things to note:

  • search instead of match to find anywhere in string
  • comma (,) after print removes carriage return (line will have one)
  • argv includes python file name, so variables need to start at 1

This doesn't handle multiple arguments (like grep does) or expand wildcards (like the Unix shell would). If you wanted this functionality you could get it using the following:

import re
import sys
import glob

for arg in sys.argv[2:]:
    for file in glob.iglob(arg):
        for line in open(file, 'r'):
            if re.search(sys.argv[1], line):
                print line,

What is *.o file?

A file ending in .o is an object file. The compiler creates an object file for each source file, before linking them together, into the final executable.

PHP PDO returning single row

Thanks to Steven's suggestion to use fetchColumn, here's my recommendation to cut short one line from your code.

$DBH = new PDO( "connection string goes here" );
$STH = $DBH->query( "select figure from table1" );
$result = $STH->fetchColumn();
echo $result;
$DBH = null;

Disable button in angular with two conditions?

Using the ternary operator is possible like following.[disabled] internally required true or false for its operation.

<button type="button" 
  [disabled]="(testVariable1 != 0 || testVariable2!=0)? true:false"
  mat-button>Button</button>

jQuery: how to get which button was clicked upon form submission?

You want to use window.event.srcElement.id like this:

function clickTheButton() {

var Sender = window.event.srcElement;
alert("the item clicked was " + Sender.id)

}

for a button that looks like:

<input type="button" id="myButton" onclick="clickTheButton();" value="Click Me"/>

you will get an alert that reads: "the item clicked was myButton.

In your improved example you can add window.event.srcElement to process_form_submission and you will have a reference to whichever element invoked the process.

How do I make a textbox that only accepts numbers?

I have made something for this on CodePlex.

It works by intercepting the TextChanged event. If the result is a good number it will be stored. If it is something wrong, the last good value will be restored. The source is a bit too large to publish here, but here is a link to the class that handles the core of this logic.

Properly Handling Errors in VBA (Excel)

This is what I'm teaching my students tomorrow. After years of looking at this stuff... ie all of the documentation above http://www.cpearson.com/excel/errorhandling.htm comes to mind as an excellent one...

I hope this summarizes it for others. There is an Err object and an active (or inactive) ErrorHandler. Both need to be handled and reset for new errors.

Paste this into a workbook and step through it with F8.

Sub ErrorHandlingDemonstration()

    On Error GoTo ErrorHandler

    'this will error
    Debug.Print (1 / 0)

    'this will also error
    dummy = Application.WorksheetFunction.VLookup("not gonna find me", Range("A1:B2"), 2, True)

    'silly error
    Dummy2 = "string" * 50

    Exit Sub

zeroDivisionErrorBlock:
    maybeWe = "did some cleanup on variables that shouldnt have been divided!"
    ' moves the code execution to the line AFTER the one that errored
    Resume Next

vlookupFailedErrorBlock:
    maybeThisTime = "we made sure the value we were looking for was in the range!"
    ' moves the code execution to the line AFTER the one that errored
    Resume Next

catchAllUnhandledErrors:
    MsgBox(thisErrorsDescription)
    Exit Sub

ErrorHandler:
    thisErrorsNumberBeforeReset = Err.Number
    thisErrorsDescription = Err.Description
    'this will reset the error object and error handling
    On Error GoTo 0
    'this will tell vba where to go for new errors, ie the new ErrorHandler that was previous just reset!
    On Error GoTo ErrorHandler

    ' 11 is the err.number for division by 0
    If thisErrorsNumberBeforeReset = 11 Then
        GoTo zeroDivisionErrorBlock
    ' 1004 is the err.number for vlookup failing
    ElseIf thisErrorsNumberBeforeReset = 1004 Then
        GoTo vlookupFailedErrorBlock
    Else
        GoTo catchAllUnhandledErrors
    End If

End Sub

Interfaces vs. abstract classes

Another thing to consider is that, since there is no multiple inheritance, if you want a class to be able to implement/inherit from your interface/abstract class, but inherit from another base class, use an interface.

What does android:layout_weight mean?

Please look at the weightSum of LinearLayout and the layout_weight of each View. android:weightSum="4" android:layout_weight="2" android:layout_weight="2" Their layout_height are both 0px, but I am not sure it is relevan

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="4">

<fragment android:name="com.example.SettingFragment"
    android:id="@+id/settingFragment"
    android:layout_width="match_parent"
    android:layout_height="0px"
    android:layout_weight="2"
    />

<Button
    android:id="@+id/dummy_button"
    android:layout_width="match_parent"
    android:layout_height="0px"
    android:layout_weight="2"
    android:text="DUMMY"
    />
</LinearLayout>

How can I override inline styles with external CSS?

inline-styles in a document have the highest priority, so for example say if you want to change the color of a div element to blue, but you've an inline style with a color property set to red

<div style="font-size: 18px; color: red;">
   Hello World, How Can I Change The Color To Blue?
</div>
div {
   color: blue; 
   /* This Won't Work, As Inline Styles Have Color Red And As 
      Inline Styles Have Highest Priority, We Cannot Over Ride 
      The Color Using An Element Selector */
}

So, Should I Use jQuery/Javascript? - Answer Is NO

We can use element-attr CSS Selector with !important, note, !important is important here, else it won't over ride the inline styles..

<div style="font-size: 30px; color: red;">
    This is a test to see whether the inline styles can be over ridden with CSS?
</div>
div[style] {
   font-size: 12px !important;
   color: blue !important;
}

Demo

Note: Using !important ONLY will work here, but I've used div[style] selector to specifically select div having style attribute

How to connect to SQL Server from another computer?

Disclamer

This is just some additional information that might help anyone. I want to make it abundantly clear that what I am describing here is possibly:

  • A. not 100% correct and
  • B. not safe in terms of network security.

I am not a DBA, but every time I find myself setting up a SQL Server (Express or Full) for testing or what not I run into the connectivity issue. The solution I am describing is more for the person who is just trying to get their job done - consult someone who is knowledgeable in this field when setting up a production server.

For SQL Server 2008 R2 this is what I end up doing:

  1. Make sure everything is squared away like in this tutorial which is the same tutorial posted above as a solution by "Dani" as the selected answer to this question.
  2. Check and/or set, your firewall settings for the computer that is hosting the SQL Server. If you are using a Windows Server 2008 R2 then use the Server Manager, go to Configuration and then look at "Windows Firewall with Advanced Security". If you are using Windows 7 then go to Control Panel and search for "Firewall" click on "Allow a program through Windows Firewall".
    • Create an inbound rule for port TCP 1433 - allow the connection
    • Create an outbound rule for port TCP 1433 - allow the connection
  3. When you are finished with the firewall settings you are going to want to check one more thing. Open up the "SQL Server Configuration Manager" locate: SQL Server Network Configuration - Protocols for SQLEXPRESS (or equivalent) - TCP/IP
    • Double click on TCP/IP
    • Click on the IP Addresses tab
    • Under IP1 set the TCP Port to 1433 if it hasn't been already
    • Under IP All set the TCP Port to 1433 if it hasn't been already
  4. Restart SQL Server and SQL Browser (do both just to be on the safe side)

Usually after I do what I mentioned above I don't have a problem anymore. Here is a screenshot of what to look for - for that last step:

Port 1433 is the default port used by SQL Server but for some reason doesn't show up in the configuration by default.

Again, if someone with more information about this topic sees a red flag please correct me.

How to convert Base64 String to javascript file object like as from file input form?

const url = 'data:image/png;base6....';
fetch(url)
  .then(res => res.blob())
  .then(blob => {
    const file = new File([blob], "File name",{ type: "image/png" })
  })

Base64 String -> Blob -> File.

How to add an item to an ArrayList in Kotlin?

If you want to specifically use java ArrayList then you can do something like this:

fun initList(){
    val list: ArrayList<String> = ArrayList()
    list.add("text")
    println(list)
}

Otherwise @guenhter answer is the one you are looking for.

Where should my npm modules be installed on Mac OS X?

Second Thomas David Kehoe, with the following caveat --

If you are using node version manager (nvm), your global node modules will be stored under whatever version of node you are using at the time you saved the module.

So ~/.nvm/versions/node/{version}/lib/node_modules/.

Java keytool easy way to add server cert from url/port

I use openssl, but if you prefer not to, or are on a system (particularly Windows) that doesn't have it, since java 7 in 2011 keytool can do the whole job:

 keytool -printcert -sslserver host[:port] -rfc >tempfile
 keytool -import [-noprompt] -alias nm -keystore file [-storepass pw] [-storetype ty] <tempfile 
 # or with noprompt and storepass (so nothing on stdin besides the cert) piping works:
 keytool -printcert -sslserver host[:port] -rfc | keytool -import -noprompt -alias nm -keystore file -storepass pw [-storetype ty]

Conversely, for java 9 up always, and for earlier versions in many cases, Java can use a PKCS12 file for a keystore instead of the traditional JKS file, and OpenSSL can create a PKCS12 without any assistance from keytool:

openssl s_client -connect host:port </dev/null | openssl pkcs12 -export -nokeys [-name nm] [-passout option] -out p12file
# <NUL on Windows
# default is to prompt for password, but -passout supports several options 
# including actual value, envvar, or file; see the openssl(1ssl) man page 

Rails migration for change column

I think this should work.

change_column :table_name, :column_name, :date

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

I was able to figure it out. In case someone wants to know below the code that worked for me:

ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);

Let me know if there is a simpler way o doing it.

Changing the image source using jQuery

I have the same wonder today, I did on this way :

//<img src="actual.png" alt="myImage" class=myClass>
$('.myClass').attr('src','').promise().done(function() {
$(this).attr('src','img/new.png');  
});

Make the current Git branch a master branch

The following steps are performed in the Git browser powered by Atlassian (Bitbucket server)

Making {current-branch} as master

  1. Make a branch out of master and name it “master-duplicate”.
  2. Make a branch out of {current-branch} and name it “{current-branch}-copy”.
  3. In repository setting (Bitbucket) change “Default Branch” to point at “master-duplicate” (without this step, you will not be able to delete master - “In the Next step”).
  4. Delete “master” branch - I did this step from source tree (you can do it from the CLI or Git browser)
  5. Rename “{current-branch}” to “master” and push to repository (this will create a new “master” branch still “{current-branch}” will exist).
  6. In repository settings, change “Default Branch” to point at “master”.

How to convert datatype:object to float64 in python?

Or you can use regular expression to handle multiple items as the general case of this issue,

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(r'[,.%]','')) 
df['CTR'] = pd.to_numeric(df['CTR'].str.replace(r'[^\d%]',''))

Linux Script to check if process is running and act on the result

If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:

#! /bin/bash

logfile="/var/oscamlog/oscam1check.log"

case "$(pidof oscam1 | wc -w)" in

0)  echo "oscam1 not running, restarting oscam1:     $(date)" >> $logfile
    /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
    ;;
2)  echo "oscam1 running, all OK:     $(date)" >> $logfile
    ;;
*)  echo "multiple instances of oscam1 running. Stopping & restarting oscam1:     $(date)" >> $logfile
    kill $(pidof oscam1 | awk '{ $1=""; print $0}')
    ;;
esac

It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like

root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript

Just an FYI

Difference between npx and npm?

NPX:

From https://www.futurehosting.com/blog/npx-makes-life-easier-for-node-developers-plus-node-vulnerability-news/:

Web developers can have dozens of projects on their development machines, and each project has its own particular set of npm-installed dependencies. A few years back, the usual advice for dealing with CLI applications like Grunt or Gulp was to install them locally in each project and also globally so they could easily be run from the command line.

But installing globally caused as many problems as it solved. Projects may depend on different versions of command line tools, and polluting the operating system with lots of development-specific CLI tools isn’t great either. Today, most developers prefer to install tools locally and leave it at that.

Local versions of tools allow developers to pull projects from GitHub without worrying about incompatibilities with globally installed versions of tools. NPM can just install local versions and you’re good to go. But project specific installations aren’t without their problems: how do you run the right version of the tool without specifying its exact location in the project or playing around with aliases?

That’s the problem npx solves. A new tool included in NPM 5.2, npx is a small utility that’s smart enough to run the right application when it’s called from within a project.

If you wanted to run the project-local version of mocha, for example, you can run npx mocha inside the project and it will do what you expect.

A useful side benefit of npx is that it will automatically install npm packages that aren’t already installed. So, as the tool’s creator Kat Marchán points out, you can run npx benny-hill without having to deal with Benny Hill polluting the global environment.

If you want to take npx for a spin, update to the most recent version of npm.

I want to execute shell commands from Maven's pom.xml

Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install

<groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>pip</executable>
              <arguments><argument>install</argument></arguments>                            
             <workingDirectory>${project.build.directory}/Demo</workingDirectory>
            </configuration>

Comparing arrays for equality in C++

Since nobody mentioned it yet, you can compare arrays with the std::equal algorithm:

int iar1[] = {1,2,3,4,5};
int iar2[] = {1,2,3,4,5};

if (std::equal(std::begin(iar1), std::end(iar1), std::begin(iar2)))
    cout << "Arrays are equal.";
else
    cout << "Arrays are not equal.";

You need to include <algorithm> and <iterator>. If you don't use C++11 yet, you can write:

if (std::equal(iar1, iar1 + sizeof iar1 / sizeof *iar1, iar2))

how to check for null with a ng-if values in a view with angularjs?

You can also use ng-template, I think that would be more efficient while run time :)

<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
    <div>2</div>
</ng-template>

Cheers

Android : Capturing HTTP Requests with non-rooted android device

There is many ways to do that but one of them is fiddler

Fiddler Configuration

  1. Go to options
  2. In HTTPS tab, enable Capture HTTPS Connects and Decrypt HTTPS traffic
  3. In Connections tab, enable Allow remote computers to connect
  4. Restart fiddler

Android Configuration

  1. Connect to same network
  2. Modify network settings
  3. Add proxy for connection with your PC's IP address ( or hostname ) and default fiddler's port ( 8888 / you can change that in settings )

Now you can see full log from your device in fiddler

Also you can find a full instruction here

How to set a Postgresql default value datestamp like 'YYYYMM'?

Just in case Milen A. Radev doesn't get around to posting his solution, this is it:

CREATE TABLE foo (
    key     int PRIMARY KEY,
    foo     text NOT NULL DEFAULT TO_CHAR(CURRENT_TIMESTAMP,'YYYYMM')
);

is there a require for json in node.js

You can import json files by using the node.js v14 experimental json modules flag. More details here

file.js

import data from './folder/file.json'

export default {
  foo () {
    console.log(data)
  }
}

And you call it with node --experimental-json-modules file.js

Sort ObservableCollection<string> through C#

This is an ObservableCollection<T>, that automatically sorts itself upon a change, triggers a sort only when necessary, and only triggers a single move collection change action.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;

namespace ConsoleApp4
{
  using static Console;

  public class SortableObservableCollection<T> : ObservableCollection<T>
  {
    public Func<T, object> SortingSelector { get; set; }
    public bool Descending { get; set; }
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
      base.OnCollectionChanged(e);
      if (SortingSelector == null 
          || e.Action == NotifyCollectionChangedAction.Remove
          || e.Action == NotifyCollectionChangedAction.Reset)
        return;

      var query = this
        .Select((item, index) => (Item: item, Index: index));
      query = Descending
        ? query.OrderBy(tuple => SortingSelector(tuple.Item))
        : query.OrderByDescending(tuple => SortingSelector(tuple.Item));

      var map = query.Select((tuple, index) => (OldIndex:tuple.Index, NewIndex:index))
       .Where(o => o.OldIndex != o.NewIndex);

      using (var enumerator = map.GetEnumerator())
       if (enumerator.MoveNext())
          Move(enumerator.Current.OldIndex, enumerator.Current.NewIndex);


    }
  }


  //USAGE
  class Program
  {
    static void Main(string[] args)
    {
      var xx = new SortableObservableCollection<int>() { SortingSelector = i => i };
      xx.CollectionChanged += (sender, e) =>
       WriteLine($"action: {e.Action}, oldIndex:{e.OldStartingIndex},"
         + " newIndex:{e.NewStartingIndex}, newValue: {xx[e.NewStartingIndex]}");

      xx.Add(10);
      xx.Add(8);
      xx.Add(45);
      xx.Add(0);
      xx.Add(100);
      xx.Add(-800);
      xx.Add(4857);
      xx.Add(-1);

      foreach (var item in xx)
        Write($"{item}, ");
    }
  }
}

Output:

action: Add, oldIndex:-1, newIndex:0, newValue: 10
action: Add, oldIndex:-1, newIndex:1, newValue: 8
action: Move, oldIndex:1, newIndex:0, newValue: 8
action: Add, oldIndex:-1, newIndex:2, newValue: 45
action: Add, oldIndex:-1, newIndex:3, newValue: 0
action: Move, oldIndex:3, newIndex:0, newValue: 0
action: Add, oldIndex:-1, newIndex:4, newValue: 100
action: Add, oldIndex:-1, newIndex:5, newValue: -800
action: Move, oldIndex:5, newIndex:0, newValue: -800
action: Add, oldIndex:-1, newIndex:6, newValue: 4857
action: Add, oldIndex:-1, newIndex:7, newValue: -1
action: Move, oldIndex:7, newIndex:1, newValue: -1
-800, -1, 0, 8, 10, 45, 100, 4857,

Jenkins: Failed to connect to repository

In our case git had to be installed on the Jenkins server.

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

Use of var keyword in C#

Amazed this hasn't been noted so far, but it is common sense to use var for foreach loop variables.

If you specify a specific type instead, you risk having a runtime cast silently inserted into your program by the compiler!

foreach (Derived d in listOfBase)
{

The above will compile. But the compiler inserts a downcast from Base to Derived. So if anything on the list is not a Derived at runtime, there is an invalid cast exception. Type safety is compromised. Invisible casts are horrible.

The only way to rule this out is to use var, so the compiler determines the type of the loop variable from the static type of the list.

Unresolved Import Issues with PyDev and Eclipse

In the properties for your pydev project, there's a pane called "PyDev - PYTHONPATH", with a sub-pane called "External Libraries". You can add source folders (any folder that has an __init__.py) to the path using that pane. Your project code will then be able to import modules from those source folders.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

I had missing application context in the Tomcat Run\Debug configuration:enter image description here

Adding it, solved the problem and I got the right response instead of "The origin server did not find..."

Number of lines in a file in Java

This is the fastest version I have found so far, about 6 times faster than readLines. On a 150MB log file this takes 0.35 seconds, versus 2.40 seconds when using readLines(). Just for fun, linux' wc -l command takes 0.15 seconds.

public static int countLinesOld(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}

EDIT, 9 1/2 years later: I have practically no java experience, but anyways I have tried to benchmark this code against the LineNumberReader solution below since it bothered me that nobody did it. It seems that especially for large files my solution is faster. Although it seems to take a few runs until the optimizer does a decent job. I've played a bit with the code, and have produced a new version that is consistently fastest:

public static int countLinesNew(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];

        int readChars = is.read(c);
        if (readChars == -1) {
            // bail out if nothing to read
            return 0;
        }

        // make it easy for the optimizer to tune this loop
        int count = 0;
        while (readChars == 1024) {
            for (int i=0; i<1024;) {
                if (c[i++] == '\n') {
                    ++count;
                }
            }
            readChars = is.read(c);
        }

        // count remaining characters
        while (readChars != -1) {
            System.out.println(readChars);
            for (int i=0; i<readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
            readChars = is.read(c);
        }

        return count == 0 ? 1 : count;
    } finally {
        is.close();
    }
}

Benchmark resuls for a 1.3GB text file, y axis in seconds. I've performed 100 runs with the same file, and measured each run with System.nanoTime(). You can see that countLinesOld has a few outliers, and countLinesNew has none and while it's only a bit faster, the difference is statistically significant. LineNumberReader is clearly slower.

Benchmark Plot

How to remove all listeners in an element?

Here's a function that is also based on cloneNode, but with an option to clone only the parent node and move all the children (to preserve their event listeners):

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners on one element:

recreateNode(document.getElementById("btn"));

Remove event listeners on an element and all of its children:

recreateNode(document.getElementById("list"), true);

If you need to keep the object itself and therefore can't use cloneNode, then you have to wrap the addEventListener function and track the listener list by yourself, like in this answer.

Export DataTable to Excel File

Try this to export the data to Excel file same as in DataTable and could customize also.

dtDataTable1 = ds.Tables[0];
    try
    {
        Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
        Workbook xlWorkBook = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);

        for (int i = 1; i > 0; i--)
        {
            Sheets xlSheets = null;
            Worksheet xlWorksheet = null;
            //Create Excel sheet
            xlSheets = ExcelApp.Sheets;
            xlWorksheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
            xlWorksheet.Name = "MY FIRST EXCEL FILE";
            for (int j = 1; j < dtDataTable1.Columns.Count + 1; j++)
            {
                ExcelApp.Cells[i, j] = dtDataTable1.Columns[j - 1].ColumnName;
                ExcelApp.Cells[1, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
                ExcelApp.Cells[i, j].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.WhiteSmoke);
            }
            // for the data of the excel
            for (int k = 0; k < dtDataTable1.Rows.Count; k++)
            {
                for (int l = 0; l < dtDataTable1.Columns.Count; l++)
                {
                    ExcelApp.Cells[k + 2, l + 1] = dtDataTable1.Rows[k].ItemArray[l].ToString();
                }
            }
            ExcelApp.Columns.AutoFit();
        }
        ((Worksheet)ExcelApp.ActiveWorkbook.Sheets[ExcelApp.ActiveWorkbook.Sheets.Count]).Delete();
        ExcelApp.Visible = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

In Typescript, How to check if a string is Numeric

You can use the Number.isFinite() function:

Number.isFinite(Infinity);  // false
Number.isFinite(NaN);       // false
Number.isFinite(-Infinity); // false
Number.isFinite('0');       // false
Number.isFinite(null);      // false

Number.isFinite(0);         // true
Number.isFinite(2e64);      // true

Note: there's a significant difference between the global function isFinite() and the latter Number.isFinite(). In the case of the former, string coercion is performed - so isFinite('0') === true whilst Number.isFinite('0') === false.

Also, note that this is not available in IE!

How to enable C++11 in Qt Creator?

The only place I have successfully make it work is by searching in:

...\Qt\{5.9; or your version}\mingw{53_32; or your version}\mkspecs\win32-g++\qmake.conf:

Then at the line:

QMAKE_CFLAGS           += -fno-keep-inline-dllexport

Edit :

QMAKE_CFLAGS           += -fno-keep-inline-dllexport -std=c++11

How can I sort a List alphabetically?

By using Collections.sort(), we can sort a list.

public class EmployeeList {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

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

        empNames.add("sudheer");
        empNames.add("kumar");
        empNames.add("surendra");
        empNames.add("kb");

        if(!empNames.isEmpty()){

            for(String emp:empNames){

                System.out.println(emp);
            }

            Collections.sort(empNames);

            System.out.println(empNames);
        }
    }
}

output:

sudheer
kumar
surendra
kb
[kb, kumar, sudheer, surendra]

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Define static method in source-file with declaration in header-file in C++

Keywords static and virtual should not be repeated in the definition. They should only be used in the class declaration.

Passing an array as a function parameter in JavaScript

While using spread operator we must note that it must be the last or only parameter passed. Else it will fail.

function callMe(...arr){ //valid arguments
    alert(arr);
}

function callMe(name, ...arr){ //valid arguments
    alert(arr);
}

function callMe(...arr, name){ //invalid arguments
    alert(arr);
}

If you need to pass an array as the starting argument you can do:

function callMe(arr, name){
    let newArr = [...arr];
    alert(newArr);
}

Lombok annotations do not compile under Intellij idea

If you're using Eclipse compiler with lombok, this setup finally worked for me:

  • IDEA 14.1
  • Lombok plugin
  • ... / Compiler / Java Compiler > Use Compiler: Eclipse
  • ... / Compiler / Annotation Processors > Enable annotation processing: checked (default configuration)
  • ... / Compiler > Additional build process VM options:(Shared build process VM options) -javaagent:lombok.jar

The most important part is the last one, mine looks like following: enter image description here

Plugin is needed for IntelliJ editor to recognize getters and setters, javaagent is needed for eclipse compiler to compile with lombok.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

In my maven project this error occurs, after i closed my projects and reopens them. The dependencys wasn´t build correctly at that time. So for me the solution was just to update the Maven Dependencies of the projects!

Convert char array to single int?

Long story short you have to use atoi()

ed:

If you are interested in doing this the right way :

char szNos[] = "12345";
char *pNext;
long output;
output = strtol (szNos, &pNext, 10); // input, ptr to next char in szNos (null here), base 

Remove substring from the string

If you are using rails or at less activesupport you got String#remove and String#remove! method

def remove!(*patterns)
  patterns.each do |pattern|
    gsub! pattern, ""
  end

  self
end

source: http://api.rubyonrails.org/classes/String.html#method-i-remove

jQuery Refresh/Reload Page if Ajax Success after time

Lots of good answers here, just out of curiosity after looking into this today, is it not best to use setInterval rather than the setTimeout?

setInterval(function() {
location.reload();
}, 30000);

let me know you thoughts.

Vendor code 17002 to connect to SQLDeveloper

Listed are the steps that could rectify the error:

  1. Press Windows+R
  2. Type services.msc and strike Enter
  3. Find all services
  4. Starting with ora start these services and wait!!
  5. When your server specific service is initialized (in my case it was orcl)
  6. Now run mysql or whatever you are using and start coding.P

Is there a constraint that restricts my generic method to numeric types?

There is no way to restrict templates to types, but you can define different actions based on the type. As part of a generic numeric package, I needed a generic class to add two values.

    class Something<TCell>
    {
        internal static TCell Sum(TCell first, TCell second)
        {
            if (typeof(TCell) == typeof(int))
                return (TCell)((object)(((int)((object)first)) + ((int)((object)second))));

            if (typeof(TCell) == typeof(double))
                return (TCell)((object)(((double)((object)first)) + ((double)((object)second))));

            return second;
        }
    }

Note that the typeofs are evaluated at compile time, so the if statements would be removed by the compiler. The compiler also removes spurious casts. So Something would resolve in the compiler to

        internal static int Sum(int first, int second)
        {
            return first + second;
        }

Delete a row in DataGridView Control in VB.NET

For Each row As DataGridViewRow In yourDGV.SelectedRows
    yourDGV.Rows.Remove(row)
Next

This will delete all rows that had been selected.

How to display scroll bar onto a html table

I resolved this problem by separating my content into two tables.

One table is the header row.

The seconds is also <table> tag, but wrapped by <div> with static height and overflow scroll.

How to find first element of array matching a boolean condition in JavaScript?

There is no built-in function in Javascript to perform this search.

If you are using jQuery you could do a jQuery.inArray(element,array).

Make the size of a heatmap bigger with seaborn

add plt.figure(figsize=(16,5)) before the sns.heatmap and play around with the figsize numbers till you get the desired size

...

plt.figure(figsize = (16,5))

ax = sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5)

How to truncate milliseconds off of a .NET DateTime

Here is an extension method based on a previous answer that will let you truncate to any resolution...

Usage:

DateTime myDateSansMilliseconds = myDate.Truncate(TimeSpan.TicksPerSecond);
DateTime myDateSansSeconds = myDate.Truncate(TimeSpan.TicksPerMinute)

Class:

public static class DateTimeUtils
{
    /// <summary>
    /// <para>Truncates a DateTime to a specified resolution.</para>
    /// <para>A convenient source for resolution is TimeSpan.TicksPerXXXX constants.</para>
    /// </summary>
    /// <param name="date">The DateTime object to truncate</param>
    /// <param name="resolution">e.g. to round to nearest second, TimeSpan.TicksPerSecond</param>
    /// <returns>Truncated DateTime</returns>
    public static DateTime Truncate(this DateTime date, long resolution)
    {
        return new DateTime(date.Ticks - (date.Ticks % resolution), date.Kind);
    }
}

How do you reset the stored credentials in 'git credential-osxkeychain'?

Try running /Applications/Utilities/Keychain Access.

Easy way to print Perl array? (with a little formatting)

Map can also be used, but sometimes hard to read when you have lots of things going on.

map{ print "element $_\n" }   @array; 

jquery mobile background image

Override ui-page class in your css:

.ui-page {
    background: url("image.gif");
    background-repeat: repeat;
}

How can change width of dropdown list?

This worked for me:

ul.dropdown-menu > li {
    max-width: 144px;
}

in Chromium and Firefox.

How to save local data in a Swift app?

For Swift 3

UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")

Check array position for null/empty

If your array is not initialized then it contains randoms values and cannot be checked !

To initialize your array with 0 values:

int array[5] = {0};

Then you can check if the value is 0:

array[4] == 0;

When you compare to NULL, it compares to 0 as the NULL is defined as integer value 0 or 0L.

If you have an array of pointers, better use the nullptr value to check:

char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr

if (array[4] == nullptr)
    // do something

Is there any boolean type in Oracle databases?

As per Ammoq and kupa's answers, We use number(1) with default of 0 and don't allow nulls.

here's an add column to demonstrate:

ALTER TABLE YourSchema.YourTable ADD (ColumnName NUMBER(1) DEFAULT 0 NOT NULL);

Hope this helps someone.

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to change the type of a field?

To convert a field of string type to date field, you would need to iterate the cursor returned by the find() method using the forEach() method, within the loop convert the field to a Date object and then update the field using the $set operator.

Take advantage of using the Bulk API for bulk updates which offer better performance as you will be sending the operations to the server in batches of say 1000 which gives you a better performance as you are not sending every request to the server, just once in every 1000 requests.

The following demonstrates this approach, the first example uses the Bulk API available in MongoDB versions >= 2.6 and < 3.2. It updates all the documents in the collection by changing all the created_at fields to date fields:

var bulk = db.collection.initializeUnorderedBulkOp(),
    counter = 0;

db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
    var newDate = new Date(doc.created_at);
    bulk.find({ "_id": doc._id }).updateOne({ 
        "$set": { "created_at": newDate}
    });

    counter++;
    if (counter % 1000 == 0) {
        bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
        bulk = db.collection.initializeUnorderedBulkOp();
    }
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }

The next example applies to the new MongoDB version 3.2 which has since deprecated the Bulk API and provided a newer set of apis using bulkWrite():

var bulkOps = [];

db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) { 
    var newDate = new Date(doc.created_at);
    bulkOps.push(         
        { 
            "updateOne": { 
                "filter": { "_id": doc._id } ,              
                "update": { "$set": { "created_at": newDate } } 
            }         
        }           
    );     
})

db.collection.bulkWrite(bulkOps, { "ordered": true });

setTimeout / clearTimeout problems

A way to use this in react:

class Timeout extends Component {
  constructor(props){
    super(props)

    this.state = {
      timeout: null
    }

  }

  userTimeout(){
    const { timeout } = this.state;
    clearTimeout(timeout);
    this.setState({
      timeout: setTimeout(() => {this.callAPI()}, 250)
    })

  }
}

Helpful if you'd like to only call an API after the user has stopped typing for instance. The userTimeout function could be bound via onKeyUp to an input.

MVC 3 file upload and model binding

If you won't always have images posting to your action, you can do something like this:

[HttpPost]
public ActionResult Uploadfile(Container container, HttpPostedFileBase file) 
{
    //do container stuff

    if (Request.Files != null)
    {
        foreach (string requestFile in Request.Files)
        {
            HttpPostedFileBase file = Request.Files[requestFile]; 
            if (file.ContentLength > 0)
            {
                string fileName = Path.GetFileName(file.FileName);
                string directory = Server.MapPath("~/App_Data/uploads/");
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                string path = Path.Combine(directory, fileName);
                file.SaveAs(path);
            }
        }
    }

} 

How to know a Pod's own IP address from inside a container in the Pod?

POD_HOST=$(kubectl get pod $POD_NAME --template={{.status.podIP}})

This command will return you an IP

python, sort descending dataframe with pandas

from pandas import DataFrame
import pandas as pd

d = {'one':[2,3,1,4,5],
 'two':[5,4,3,2,1],
 'letter':['a','a','b','b','c']}

df = DataFrame(d)

test = df.sort_values(['one'], ascending=False)
test

Rename MySQL database

First backup the old database called HRMS and edit the script file with replace the word HRMS to SUNHRM. After this step import the database file to the mysql

MyISAM versus InnoDB

I'm not a database expert, and I do not speak from experience. However:

MyISAM tables use table-level locking. Based on your traffic estimates, you have close to 200 writes per second. With MyISAM, only one of these could be in progress at any time. You have to make sure that your hardware can keep up with these transaction to avoid being overrun, i.e., a single query can take no more than 5ms.

That suggests to me you would need a storage engine which supports row-level locking, i.e., InnoDB.

On the other hand, it should be fairly trivial to write a few simple scripts to simulate the load with each storage engine, then compare the results.

how can I connect to a remote mongo server from Mac OS terminal

You are probably connecting fine but don't have sufficient privileges to run show dbs.

You don't need to run the db.auth if you pass the auth in the command line:

mongo somewhere.mongolayer.com:10011/my_database -u username -p password

Once you connect are you able to see collections?

> show collections

If so all is well and you just don't have admin privileges to the database and can't run the show dbs

Python JSON dump / append to .txt with each variable on new line

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

How to check if text fields are empty on form submit using jQuery?

You can use 'required' http://jsbin.com/atefuq/1/edit

<form action="login.php" method="post">
    <label>Login Name:</label>
    <input required type="text" name="email" id="log" />
    <label>Password:</label>
    <input required type="password" name="password" id="pwd" />
    <input  required type="submit" name="submit" value="Login" />
</form>

numbers not allowed (0-9) - Regex Expression in javascript

\D is a non-digit, and so then \D* is any number of non-digits in a row. So your whole string should match ^\D*$.

Check on http://rubular.com/r/AoWBmrbUkN it works perfectly.

You can also try on http://regexpal.com/ OR http://www.regextester.com/

jQuery AJAX form data serialize using PHP

try it , but first be sure what is you response console.log(response) on ajax success from server

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm");
$("#smt").click(function(){
$.ajax({
        type:"POST",
        url:form.attr("action"),
        data:form.serialize(),

        success: function(response){
        if(response === 1){
            //load chech.php file  
        }  else {
            //show error
        }
        }
    });
});
});

How to run a Command Prompt command with Visual Basic code?

Yes. You can use Process.Start to launch an executable, including a console application.

If you need to read the output from the application, you may need to read from it's StandardOutput stream in order to get anything printed from the application you launch.

Filter Excel pivot table using VBA

Field.CurrentPage only works for Filter fields (also called page fields).
If you want to filter a row/column field, you have to cycle through the individual items, like so:

Sub FilterPivotField(Field As PivotField, Value)
    Application.ScreenUpdating = False
    With Field
        If .Orientation = xlPageField Then
            .CurrentPage = Value
        ElseIf .Orientation = xlRowField Or .Orientation = xlColumnField Then
            Dim i As Long
            On Error Resume Next ' Needed to avoid getting errors when manipulating PivotItems that were deleted from the data source.
            ' Set first item to Visible to avoid getting no visible items while working
            .PivotItems(1).Visible = True
            For i = 2 To Field.PivotItems.Count
                If .PivotItems(i).Name = Value Then _
                    .PivotItems(i).Visible = True Else _
                    .PivotItems(i).Visible = False
            Next i
            If .PivotItems(1).Name = Value Then _
                .PivotItems(1).Visible = True Else _
                .PivotItems(1).Visible = False
        End If
    End With
    Application.ScreenUpdating = True
End Sub

Then, you would just call:

FilterPivotField ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode"), "K123223"

Naturally, this gets slower the more there are individual different items in the field. You can also use SourceName instead of Name if that suits your needs better.

Setting the selected attribute on a select list using jQuery

If you are using JQuery, since the 1.6 you have to use the .prop() method :

$('select option:nth(1)').prop("selected","selected");