Programs & Examples On #Havok

Havok Game Dynamics SDK is a physics engine (dynamic simulation) used in videogames and recreates interactions between objects and characters of the game. It detects collisions, gravity, mass and speed in real-time.

Why is @font-face throwing a 404 error on woff files?

This might be obvious, but it has tripped me up with 404s a number of times... Make sure the fonts folder permissions are set correctly.

Basic http file downloading and saving to disk in python?

A clean way to download a file is:

import urllib

testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")

This downloads a file from a website and names it file.gz. This is one of my favorite solutions, from Downloading a picture via urllib and python.

This example uses the urllib library, and it will directly retrieve the file form a source.

Spring @Transactional - isolation, propagation

Good question, although not a trivial one to answer.

Propagation

Defines how transactions relate to each other. Common options:

  • REQUIRED: Code will always run in a transaction. Creates a new transaction or reuses one if available.
  • REQUIRES_NEW: Code will always run in a new transaction. Suspends the current transaction if one exists.

Isolation

Defines the data contract between transactions.

  • ISOLATION_READ_UNCOMMITTED: Allows dirty reads.
  • ISOLATION_READ_COMMITTED: Does not allow dirty reads.
  • ISOLATION_REPEATABLE_READ: If a row is read twice in the same transaction, the result will always be the same.
  • ISOLATION_SERIALIZABLE: Performs all transactions in a sequence.

The different levels have different performance characteristics in a multi-threaded application. I think if you understand the dirty reads concept you will be able to select a good option.


Example of when a dirty read can occur:

  thread 1   thread 2      
      |         |
    write(x)    |
      |         |
      |        read(x)
      |         |
    rollback    |
      v         v 
           value (x) is now dirty (incorrect)

So a sane default (if such can be claimed) could be ISOLATION_READ_COMMITTED, which only lets you read values which have already been committed by other running transactions, in combination with a propagation level of REQUIRED. Then you can work from there if your application has other needs.


A practical example of where a new transaction will always be created when entering the provideService routine and completed when leaving:

public class FooService {
    private Repository repo1;
    private Repository repo2;

    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public void provideService() {
        repo1.retrieveFoo();
        repo2.retrieveFoo();
    }
}

Had we instead used REQUIRED, the transaction would remain open if the transaction was already open when entering the routine. Note also that the result of a rollback could be different as several executions could take part in the same transaction.


We can easily verify the behaviour with a test and see how results differ with propagation levels:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:/fooService.xml")
public class FooServiceTests {

    private @Autowired TransactionManager transactionManager;
    private @Autowired FooService fooService;

    @Test
    public void testProvideService() {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        fooService.provideService();
        transactionManager.rollback(status);
        // assert repository values are unchanged ... 
}

With a propagation level of

  • REQUIRES_NEW: we would expect fooService.provideService() was NOT rolled back since it created it's own sub-transaction.

  • REQUIRED: we would expect everything was rolled back and the backing store was unchanged.

Remove background drawable programmatically in Android

setBackgroundResource(0) is the best option. From the documentation:

Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.

It works everywhere, because it's since API 1.

setBackground was added much later, in API 16, so it will not work if your minSdkVersion is lower than 16.

Session state can only be used when enableSessionState is set to true either in a configuration

Did you enable the session state in the section as well?

 <system.web>
      <pages enableSessionState="true" /> 
 </system.web>

Or did you add this to the page?

 <%@Page enableSessionState="true"> 

And did you verify that the ASP.NET Session State Manager Service service is running? In your screenshot it isn't. It's set to start-up mode Manual which requires you to start it every time you want to make use of it. To start it, highlight the service and click the green play button on the toolbar. To start it automatically, edit the properties and adjust the Start-up type.

Or set the SessionState's mode property to InProc, so that the state service is not required.

 <system.web>
      <sessionState mode="InProc" />
 </system.web>

Check MSDN for all the options available to you with regards to storing data in the ASP.NET session state.


Note: It's better to have your Controller fetch the value from the session and have it add the value to the Model for your page/control (or to the ViewBag), that way the View doesn't depend on the HttpSession and you can choose a different source for this item later with minimal code changes. Or even better, not use the session state at all. It can kill you performance when you're using a lot of async javascript calls.

Return content with IHttpActionResult for non-OK response

@mayabelle you can create IHttpActionResult concrete and wrapped those code like this:

public class NotFoundPlainTextActionResult : IHttpActionResult
{
    public NotFoundPlainTextActionResult(HttpRequestMessage request, string message)
    {
        Request = request;
        Message = message;
    }

    public string Message { get; private set; }
    public HttpRequestMessage Request { get; private set; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(ExecuteResult());
    }

    public HttpResponseMessage ExecuteResult()
    {
        var response = new HttpResponseMessage();

        if (!string.IsNullOrWhiteSpace(Message))
            //response.Content = new StringContent(Message);
            response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception(Message));

        response.RequestMessage = Request;
        return response;
    }
}

What does -> mean in Python function definitions?

As other answers have stated, the -> symbol is used as part of function annotations. In more recent versions of Python >= 3.5, though, it has a defined meaning.

PEP 3107 -- Function Annotations described the specification, defining the grammar changes, the existence of func.__annotations__ in which they are stored and, the fact that it's use case is still open.

In Python 3.5 though, PEP 484 -- Type Hints attaches a single meaning to this: -> is used to indicate the type that the function returns. It also seems like this will be enforced in future versions as described in What about existing uses of annotations:

The fastest conceivable scheme would introduce silent deprecation of non-type-hint annotations in 3.6, full deprecation in 3.7, and declare type hints as the only allowed use of annotations in Python 3.8.

(Emphasis mine)

This hasn't been actually implemented as of 3.6 as far as I can tell so it might get bumped to future versions.

According to this, the example you've supplied:

def f(x) -> 123:
    return x

will be forbidden in the future (and in current versions will be confusing), it would need to be changed to:

def f(x) -> int:
    return x

for it to effectively describe that function f returns an object of type int.

The annotations are not used in any way by Python itself, it pretty much populates and ignores them. It's up to 3rd party libraries to work with them.

How to keep :active css style after clicking an element

The :target-pseudo selector is made for these type of situations: http://reference.sitepoint.com/css/pseudoclass-target

It is supported by all modern browsers. To get some IE versions to understand it you can use something like Selectivizr

Here is a tab example with :target-pseudo selector.

Laravel 5 PDOException Could Not Find Driver

sudo apt-get update

For Mysql Database

sudo apt-get install php-mysql

For PostgreSQL Database

sudo apt-get install php-pgsql

Than

php artisan migrate

Get current working directory in a Qt application

I'm running Qt 5.5 under Windows and the default constructor of QDir appears to pick up the current working directory, not the application directory.

I'm not sure if the getenv PWD will work cross-platform and I think it is set to the current working directory when the shell launched the application and doesn't include any working directory changes done by the app itself (which might be why the OP is seeing this behavior).

So I thought I'd add some other ways that should give you the current working directory (not the application's binary location):

// using where a relative filename will end up
QFileInfo fi("temp");
cout << fi.absolutePath() << endl;

// explicitly using the relative name of the current working directory
QDir dir(".");
cout << dir.absolutePath() << endl;

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    }
    componentDidMount() {
        fetch(url)
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    }
    render() {
        const {users} = this.state;
        if (users) {
            return (
                <ul>
                    {users.map(user => <li>{user.name}</li>)}
                </ul>
            )
        } else {
            return (<h1>Loading ...</h1>)
        }
    }
}

export default MyComponent;

Free ASP.Net and/or CSS Themes

Microsoft hired one fo the kids from A List Apart to whip some out. The .Net projects are free of charge for download.

http://msdn.microsoft.com/en-us/asp.net/aa336613.aspx

Is there a simple way to remove multiple spaces in a string?

I have tried the following method and it even works with the extreme case like:

str1='          I   live    on    earth           '

' '.join(str1.split())

But if you prefer a regular expression it can be done as:

re.sub('\s+', ' ', str1)

Although some preprocessing has to be done in order to remove the trailing and ending space.

How to protect Excel workbook using VBA?

I agree with @Richard Morgan ... what you are doing should be working, so more information may be needed.

Microsoft has some suggestions on options to protect your Excel 2003 worksheets.

Here is a little more info ...

From help files (Protect Method):

expression.Protect(Password, Structure, Windows)

expression Required. An expression that returns a Workbook object.

Password Optional Variant. A string that specifies a case-sensitive password for the worksheet or workbook. If this argument is omitted, you can unprotect the worksheet or workbook without using a password. Otherwise, you must specify the password to unprotect the worksheet or workbook. If you forget the password, you cannot unprotect the worksheet or workbook. It's a good idea to keep a list of your passwords and their corresponding document names in a safe place.

Structure Optional Variant. True to protect the structure of the workbook (the relative position of the sheets). The default value is False.

Windows Optional Variant. True to protect the workbook windows. If this argument is omitted, the windows aren’t protected.

ActiveWorkbook.Protect Password:="password", Structure:=True, Windows:=True

If you want to work at the worksheet level, I used something similar years ago when I needed to protect/unprotect:

Sub ProtectSheet()
    ActiveSheet.Protect "password", True, True
End Sub

Sub UnProtectSheet()
    ActiveSheet.Unprotect "password"
End Sub

Sub protectAll()
    Dim myCount
    Dim i
    myCount = Application.Sheets.Count
    Sheets(1).Select
    For i = 1 To myCount
        ActiveSheet.Protect "password", true, true
        If i = myCount Then
            End
        End If
        ActiveSheet.Next.Select
    Next i
End Sub

How can change width of dropdown list?

If you want to control the width of the list that drops down, you can do it as follows.

CSS

#wgtmsr option {
    width: 50px;
}

How do I check if an element is hidden in jQuery?

Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length).

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

You can get this if the client specifies "https" but the server is only running "http". So, the server isn't expecting to make a secure connection.

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I was getting an "out of space" error, which left me scratching my head as I had plenty of disk space, until I realized that it ran out of space on /tmp, which on Arch Linux is mounted on a tmpfs with a size limit.

Need to get a string after a "word" in a string in c#

use indexOf() function

string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
  //DO YOUR LOGIC
  string errorCode = s.Substring(index+4);
}

Select All distinct values in a column using LINQ

I have to find distinct rows with the following details class : Scountry
columns: countryID, countryName,isactive
There is no primary key in this. I have succeeded with the followin queries

public DbSet<SCountry> country { get; set; }
    public List<SCountry> DoDistinct()
    {
        var query = (from m in country group m by new { m.CountryID, m.CountryName, m.isactive } into mygroup select mygroup.FirstOrDefault()).Distinct();
        var Countries = query.ToList().Select(m => new SCountry { CountryID = m.CountryID, CountryName = m.CountryName, isactive = m.isactive }).ToList();
        return Countries;
    }

How to check if BigDecimal variable == 0 in java?

There is a static constant that represents 0:

BigDecimal.ZERO.equals(selectPrice)

You should do this instead of:

selectPrice.equals(BigDecimal.ZERO)

in order to avoid the case where selectPrice is null.

Python: access class property from string

  • getattr(x, 'y') is equivalent to x.y
  • setattr(x, 'y', v) is equivalent to x.y = v
  • delattr(x, 'y') is equivalent to del x.y

Update multiple values in a single statement

Have you tried with a sub-query for every field:

UPDATE
    MasterTbl
SET
    TotalX = (SELECT SUM(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalY = (SELECT SUM(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
    TotalZ = (SELECT SUM(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
WHERE
    ....

Arduino Tools > Serial Port greyed out

In my case this turned out to be a bad USB hub.

The 'lsusb' command can be used to display all recognized devices. If the unit is not plugged in the option to set the speed will be disabled.

The lsusb command should output something like the string 'Future Technology Devices International, Ltd Bridge(I2C/SPI/UART/FIFO)' if your device is recognized. Mine was an RFDuino

How to make an alert dialog fill 90% of screen size?

My answer is based on the koma's but it doesn't require to override onStart but only onCreateView which is almost always overridden by default when you create new fragments.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.your_fragment_layout, container);

    Rect displayRectangle = new Rect();
    Window window = getDialog().getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

    v.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
    v.setMinimumHeight((int)(displayRectangle.height() * 0.9f));

    return v;
}

I've tested it on Android 5.0.1.

How to POST raw whole JSON in the body of a Retrofit request?

In Retrofit2, When you want to send your parameters in raw you must use Scalars.

first add this in your gradle:

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

Your Interface

public interface ApiInterface {

    String URL_BASE = "http://10.157.102.22/rest/";

    @Headers("Content-Type: application/json")
    @POST("login")
    Call<User> getUser(@Body String body);

}

Activity

   public class SampleActivity extends AppCompatActivity implements Callback<User> {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.URL_BASE)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiInterface apiInterface = retrofit.create(ApiInterface.class);


        // prepare call in Retrofit 2.0
        try {
            JSONObject paramObject = new JSONObject();
            paramObject.put("email", "[email protected]");
            paramObject.put("pass", "4384984938943");

            Call<User> userCall = apiInterface.getUser(paramObject.toString());
            userCall.enqueue(this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResponse(Call<User> call, Response<User> response) {
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
    }
}

How to mount host volumes into docker containers in Dockerfile during build

There is a way to mount a volume during a build, but it doesn't involve Dockerfiles.

The technique would be to create a container from whatever base you wanted to use (mounting your volume(s) in the container with the -v option), run a shell script to do your image building work, then commit the container as an image when done.

Not only will this leave out the excess files you don't want (this is good for secure files as well, like SSH files), it also creates a single image. It has downsides: the commit command doesn't support all of the Dockerfile instructions, and it doesn't let you pick up when you left off if you need to edit your build script.

UPDATE:

For example,

CONTAINER_ID=$(docker run -dit ubuntu:16.04)
docker cp build.sh $CONTAINER_ID:/build.sh
docker exec -t $CONTAINER_ID /bin/sh -c '/bin/sh /build.sh'
docker commit $CONTAINER_ID $REPO:$TAG
docker stop $CONTAINER_ID

PHP Get Highest Value from Array

Don't sort the array to get the largest value.

Get the max value:

$value = max($array);

Get the corresponding key:

$key = array_search($value, $array);

Laravel Migration table already exists, but I want to add new not the older

You need to run

php artisan migrate:rollback

if that also fails just go in and drop all the tables which you may have to do as it seems your migration table is messed up or your user table when you ran a previous rollback did not drop the table.

EDIT:

The reason this happens is that you ran a rollback previously and it had some error in the code or did not drop the table. This still however messes up the laravel migration table and as far as it's concerned you now have no record of pushing the user table up. The user table does already exist however and this error is throw.

How to set tbody height with overflow scroll

HTML:

<table id="uniquetable">
    <thead>
      <tr>
        <th> {{ field[0].key }} </th>
        <th> {{ field[1].key }} </th>
        <th> {{ field[2].key }} </th>
        <th> {{ field[3].key }} </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="obj in objects" v-bind:key="obj.id">
        <td> {{ obj.id }} </td>
        <td> {{ obj.name }} </td>
        <td> {{ obj.age }} </td>
        <td> {{ obj.gender }} </td>
      </tr>
    </tbody>
</table>

CSS:

#uniquetable thead{
    display:block;
    width: 100%;
}
#uniquetable tbody{
    display:block;
    width: 100%;
    height: 100px;
    overflow-y:overlay;
    overflow-x:hidden;
}
#uniquetable tbody tr,#uniquetable thead tr{
    width: 100%;
    display:table;
}
#uniquetable tbody tr td, #uniquetable thead tr th{
   display:table-cell;
   width:20% !important;
   overflow:hidden;
}

this will work as well:

#uniquetable tbody {
    width:inherit !important;
    display:block;
    max-height: 400px;
    overflow-y:overlay;
  }
  #uniquetable thead {
    width:inherit !important;
    display:block;
  }
  #uniquetable tbody tr, #uniquetable thead tr {
    display:inline-flex;
    width:100%;
  }
  #uniquetable tbody tr td,  #uniquetable thead tr th {
    display:block;
    width:20%;
    border-top:none;
    text-overflow: ellipsis;
    overflow: hidden;
    max-height:400px;
  }

How to remove focus from single editText

If I understand your question correctly, this should help you:

TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1 .setFocusable(false);

How do I center text vertically and horizontally in Flutter?

                       child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'Text here',
                            textAlign: TextAlign.center,                          
                          ),
                        ),

This produced the best result for me.

Guzzle 6: no more json() method for responses

$response is instance of PSR-7 ResponseInterface. For more details see https://www.php-fig.org/psr/psr-7/#3-interfaces

getBody() returns StreamInterface:

/**
 * Gets the body of the message.
 *
 * @return StreamInterface Returns the body as a stream.
 */
public function getBody();

StreamInterface implements __toString() which does

Reads all data from the stream into a string, from the beginning to end.

Therefore, to read body as string, you have to cast it to string:

$stringBody = (string) $response->getBody()


Gotchas

  1. json_decode($response->getBody() is not the best solution as it magically casts stream into string for you. json_decode() requires string as 1st argument.
  2. Don't use $response->getBody()->getContents() unless you know what you're doing. If you read documentation for getContents(), it says: Returns the remaining contents in a string. Therefore, calling getContents() reads the rest of the stream and calling it again returns nothing because stream is already at the end. You'd have to rewind the stream between those calls.

When should you use 'friend' in C++?

We had an interesting issue come up at a company I previously worked at where we used friend to decent affect. I worked in our framework department we created a basic engine level system over our custom OS. Internally we had a class structure:

         Game
        /    \
 TwoPlayer  SinglePlayer

All of these classes were part of the framework and maintained by our team. The games produced by the company were built on top of this framework deriving from one of Games children. The issue was that Game had interfaces to various things that SinglePlayer and TwoPlayer needed access to but that we did not want expose outside of the framework classes. The solution was to make those interfaces private and allow TwoPlayer and SinglePlayer access to them via friendship.

Truthfully this whole issue could have been resolved by a better implementation of our system but we were locked into what we had.

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

How to convert String to long in Java?

It's quite simple, use Long.valueOf(String s);

For example:

String s;
long l;

Scanner sc=new Scanner(System.in);
s=sc.next();
l=Long.valueOf(s);
System.out.print(l);

You're done!!!

Hexadecimal To Decimal in Shell Script

Various tools are available to you from within a shell. Sputnick has given you an excellent overview of your options, based on your initial question. He definitely deserves votes for the time he spent giving you multiple correct answers.

One more that's not on his list:

[ghoti@pc ~]$ dc -e '16i BFCA3000 p'
3217698816

But if all you want to do is subtract, why bother changing the input to base 10?

[ghoti@pc ~]$ dc -e '16i BFCA3000 17FF - p 10o p'
3217692673
BFCA1801
[ghoti@pc ~]$ 

The dc command is "desk calc". It will also take input from stdin, like bc, but instead of using "order of operations", it uses stacking ("reverse Polish") notation. You give it inputs which it adds to a stack, then give it operators that pop items off the stack, and push back on the results.

In the commands above we've got the following:

  • 16i -- tells dc to accept input in base 16 (hexadecimal). Doesn't change output base.
  • BFCA3000 -- your initial number
  • 17FF -- a random hex number I picked to subtract from your initial number
  • - -- take the two numbers we've pushed, and subtract the later one from the earlier one, then push the result back onto the stack
  • p -- print the last item on the stack. This doesn't change the stack, so...
  • 10o -- tells dc to print its output in base "10", but remember that our input numbering scheme is currently hexadecimal, so "10" means "16".
  • p -- print the last item on the stack again ... this time in hex.

You can construct fabulously complex math solutions with dc. It's a good thing to have in your toolbox for shell scripts.

macOS on VMware doesn't recognize iOS device

I have 2 computers with VMWare Workstation and Mac OS Sierra installed as the guest OS. First machine could recognize my iOS device whereas my second machine could not recognize it. The second machine was exhibiting the same behavior as others reported where it would reconnect and disconnect with the iPhone endlessly.

Thankfully, my second machine had network connectivity problems with my VM. So I stumbled upon the solution when I reset my network settings for the VM.

You can try the following steps and see if it works for you. It worked for me.

  1. Go to Start Menu.
  2. Open VMWare folder.
  3. Start VMWare Network Editor.
  4. Click Change Settings button to assign Administrator privileges.
  5. Click Restore Defaults button.
  6. Open Virtual Machine.
  7. Verify internet connectivity on Mac OS.
  8. Connect iOS device. If iTunes launches on Mac, this means that the Mac has correctly identified your iOS device.

Convert from List into IEnumerable format

Why not use a Single liner ...

IEnumerable<Book> _Book_IE= _Book_List as IEnumerable<Book>;

Print all but the first three columns

Pretty much all the answers currently add either leading spaces, trailing spaces or some other separator issue. To select from the fourth field where the separator is whitespace and the output separator is a single space using awk would be:

awk '{for(i=4;i<=NF;i++)printf "%s",$i (i==NF?ORS:OFS)}' file

To parametrize the starting field you could do:

awk '{for(i=n;i<=NF;i++)printf "%s",$i (i==NF?ORS:OFS)}' n=4 file

And also the ending field:

awk '{for(i=n;i<=m=(m>NF?NF:m);i++)printf "%s",$i (i==m?ORS:OFS)}' n=4 m=10 file

Execute combine multiple Linux commands in one line

What is the utility of an only one Ampersand? This morning, I made a launcher in the XFCE panel (in Manjaro+XFCE) to launch 2 passwords managers simultaneously:

sh -c "keepassx && password-gorilla"
or
sh -c "keepassx; password-gorilla"

But it does not work as I want. I.E., the first app starts but the second starts only when the previous is closed

However, I found that (with only one ampersand):

sh -c "keepassx & password-gorilla"

and it works as I want now...

Java array reflection: isArray vs. instanceof

Java array reflection is for cases where you don't have an instance of the Class available to do "instanceof" on. For example, if you're writing some sort of injection framework, that injects values into a new instance of a class, such as JPA does, then you need to use the isArray() functionality.

I blogged about this earlier in December. http://blog.adamsbros.org/2010/12/08/java-array-reflection/

Perform Segue programmatically and pass parameters to the destination view

In case if you use new swift version.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ChannelMoreSegue" {

        }
}

How to access parent Iframe from JavaScript

Maybe just use

window.parent

into your iframe to get the calling frame / windows. If you had multiple calling frame, you can use

window.top

How to validate Google reCAPTCHA v3 on server side?

Source Tutorial Link

V2 of Google reCAPTCHA.

Step 1 - Go to Google reCAPTCHA

Login then get Site Key and Secret Key

Step 2 - Download PHP code here and upload src folder on your server.

Step 3 - Use below code in your form.php

        <head>
            <title>FreakyJolly.com Google reCAPTCHA EXAMPLE form</title>
            <script src='https://www.google.com/recaptcha/api.js'></script>
        </head>

        <body>
            <?php

            require('src/autoload.php');

            $siteKey = '6LegPmIUAAAAADLwDmXXXXXXXyZAJVJXXXjN';
            $secret = '6LegPmIUAAAAAO3ZTXXXXXXXXJwQ66ngJ7AlP';

            $recaptcha = new \ReCaptcha\ReCaptcha($secret);

            $gRecaptchaResponse = $_POST['g-recaptcha-response']; //google captcha post data
            $remoteIp = $_SERVER['REMOTE_ADDR']; //to get user's ip

            $recaptchaErrors = ''; // blank varible to store error

            $resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp); //method to verify captcha
            if ($resp->isSuccess()) {

               /******** 

                Add code to create User here when form submission is successful

               *****/

            } else {

                /****

                // This variable will have error when reCAPTCHA is not entered correctly.

                ****/

               $recaptchaErrors = $resp->getErrorCodes(); 
            }


            ?>
                <form autcomplete="off" class="form-createuser" name="create_user_form" action="" method="post">
                    <div class="panel periodic-login">
                        <div class="panel-body text-center">
                            <div class="form-group form-animate-text" style="margin-top:40px !important;">
                                <input type="text" autcomplete="off" class="form-text" name="new_user_name" required="">
                                <span class="bar"></span>
                                <label>Username</label>
                            </div>
                            <div class="form-group form-animate-text" style="margin-top:40px !important;">
                                <input type="text" autcomplete="off" class="form-text" name="new_phone_number" required="">
                                <span class="bar"></span>
                                <label>Phone</label>
                            </div>
                            <div class="form-group form-animate-text" style="margin-top:40px !important;">
                                <input type="password" autcomplete="off" class="form-text" name="new_user_password" required="">
                                <span class="bar"></span>
                                <label>Password</label>
                            </div>
                            <?php 
                                    if(isset($recaptchaErrors[0])){
                                        print('Error in Submitting Form. Please Enter reCAPTCHA AGAIN');
                                    }
                              ?>
                            <div class="g-recaptcha" data-sitekey="6LegPmIUAAAAADLwDmmVmXXXXXXXXXXXXXXjN"></div>
                            <input type="submit" class="btn col-md-12" value="Create User">
                        </div>
                    </div>
                </form>
        </body>

        </html>

Printing Python version in output

Try

python --version 

or

python -V

This will return a current python version in terminal.

Check for special characters in string

_x000D_
_x000D_
var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";_x000D_
var checkForSpecialChar = function(string){_x000D_
 for(i = 0; i < specialChars.length;i++){_x000D_
   if(string.indexOf(specialChars[i]) > -1){_x000D_
       return true_x000D_
    }_x000D_
 }_x000D_
 return false;_x000D_
}_x000D_
_x000D_
var str = "YourText";_x000D_
if(checkForSpecialChar(str)){_x000D_
  alert("Not Valid");_x000D_
} else {_x000D_
    alert("Valid");_x000D_
}
_x000D_
_x000D_
_x000D_

Android view pager with page indicator

I know this has already been answered, but for anybody looking for a simple, no-frills implementation of a ViewPager indicator, I've implemented one that I've open sourced. For anyone finding Jake Wharton's version a bit complex for their needs, have a look at https://github.com/jarrodrobins/SimpleViewPagerIndicator.

How do I restart nginx only after the configuration test was successful on Ubuntu?

You can use signals to control nginx.

According to documentation, you need to send HUP signal to nginx master process.

HUP - changing configuration, keeping up with a changed time zone (only for FreeBSD and Linux), starting new worker processes with a new configuration, graceful shutdown of old worker processes

Check the documentation here: http://nginx.org/en/docs/control.html

You can send the HUP signal to nginx master process PID like this:

kill -HUP $( cat /var/run/nginx.pid )

The command above reads the nginx PID from /var/run/nginx.pid. By default nginx pid is written to /usr/local/nginx/logs/nginx.pid but that can be overridden in config. Check your nginx.config to see where it saves the PID.

How to animate the change of image in an UIImageView?

[UIView transitionWithView:textFieldimageView
                  duration:0.2f
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
                    imageView.image = newImage;
                } completion:nil];

is another possibility

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)

How to send string from one activity to another?

TWO CASES

There are two situations possible when we talk about passing data between activities.

Let's say there are two activities A and B and there is a String X. and you are in Activity A.

Now let's see the two cases

  1. A-------->B
  2. A<--------B

CASE 1:
String X is in A and you want to get it in Activity B.

It is very straightforward.

In Activity A.

1) Create Intent
2) Put Extra value
3) startActivity

Intent i = new Intent(A.this, B.class);
i.putExtra("Your_KEY",X);
startActivity(i)

In Activity B

Inside onCreate() method retrieve string X using the key which you used while storing X (Your_KEY).

Intent i = getIntent();
String s = i.getStringExtra("Your_KEY");

Case 2:
This case is little tricky if u are new to Android development Because you are in Activity A, you move to Activity B, collect the string, move back to Activity A and retrieve the collected String or data. Let's see how to deal with this situation.

In Activity A
1) Create Intent
2) start an activity with a request code.

Intent i = new Intent(A.this, B.class);
startActivityForResult(i,your_req_code);

In Activity B
1) Put string X in intent
2) Set result
3) Finish activity

Intent returnIntent = new Intent();
returnIntent .putString("KEY",X);
setResult(resCode,returnIntent);   // for the first argument, you could set Activity.RESULT_OK or your custom rescode too
finish();

Again in Activity A
1) Override onActivityResult method

onActivityResult(int req_code, int res_code, Intent data)
{
       if(req_code==your_req_code)
       {
          String X = data.getStringExtra("KEY")
       }
}

Further understanding of Case 2

You might wonder what is the reqCode, resCode in the onActivityResult(int reqCode, resCode, Intent data)

reqCode is useful when you have to identify from which activity you are getting the result from.

Let's say you have two buttons, one button starts Camera (you click a photo and get the bitmap of that image in your Activity as a result), another button starts GoogleMap( you get back the current coordinates of your location as a result). So to distinguish between the results of both activities you start CameraActivty and MapActivity with different request codes.

resCode: is useful when you have to distinguish between how results are coming back to requesting activity.

For eg: You start Camera Activity. When the camera activity starts, you could either take a photo or just move back to requesting activity without taking a photo with the back button press. So in these two situations, your camera activity sends result with different resCode ACTIVITY.RESULT_OK and ACTIVITY.RESULT_CANCEL respectively.

Relevant Links

Read more on Getting result

What is the difference between call and apply?

Let me add a little detail to this.

these two calls are almost equivalent:

func.call(context, ...args); // pass an array as list with spread operator

func.apply(context, args);   // is same as using apply

There’s only a minor difference:

  • The spread operator ... allows passing iterable args as the list to call.
  • The apply accepts only array-like args.

So, these calls complement each other. Where we expect an iterable, call works, where we expect an array-like, apply works.

And for objects that are both iterable and array-like, like a real array, we technically could use any of them, but apply will probably be faster because most JavaScript engines internally optimize it better.

Download a specific tag with Git

Checking out Tags

If you want to view the versions of files a tag is pointing to, you can do a git checkout, though this puts your repository in “detached HEAD” state, which has some ill side effects:

$ git checkout 2.0.0
Note: checking out '2.0.0'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b <new-branch-name>

HEAD is now at 99ada87... Merge pull request #89 from schacon/appendix-final

$ git checkout 2.0-beta-0.1
Previous HEAD position was 99ada87... Merge pull request #89 from schacon/appendix-final
HEAD is now at df3f601... add atlas.json and cover image

In “detached HEAD” state, if you make changes and then create a commit, the tag will stay the same, but your new commit won’t belong to any branch and will be unreachable, except for by the exact commit hash. Thus, if you need to make changes—say you’re fixing a bug on an older version, for instance—you will generally want to create a branch:

$ git checkout -b version2 v2.0.0
Switched to a new branch 'version2'

If you do this and make a commit, your version2 branch will be slightly different than your v2.0.0 tag since it will move forward with your new changes, so do be careful.

exporting multiple modules in react.js

You can have only one default export which you declare like:

export default App; or export default class App extends React.Component {...

and later do import App from './App'

If you want to export something more you can use named exports which you declare without default keyword like:

export {
  About,
  Contact,
}

or:

export About;
export Contact;

or:

export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);

and later you import them like:

import App, { About, Contact } from './App';

EDIT:

There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js file. Other than that why export anything if it is no used outside the file?. Correct main.js :

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute  } from 'react-router'

class App extends React.Component {
...
}

class Home extends React.Component {
...
}


class About extends React.Component {
...
}


class Contact extends React.Component {
...
}


ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>

), document.getElementById('app'))

EDIT2:

another thing is that this tutorial is based on react-router-V3 which has different api than v4.

Why do python lists have pop() but not push()

Ok, personal opinion here, but Append and Prepend imply precise positions in a set.

Push and Pop are really concepts that can be applied to either end of a set... Just as long as you're consistent... For some reason, to me, Push() seems like it should apply to the front of a set...

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot http://i.imgur.com/gzGYVTZ.png) It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

How to handle errors with boto3?

Use the response contained within the exception. Here is an example:

import boto3
from botocore.exceptions import ClientError

try:
    iam = boto3.client('iam')
    user = iam.create_user(UserName='fred')
    print("Created user: %s" % user)
except ClientError as e:
    if e.response['Error']['Code'] == 'EntityAlreadyExists':
        print("User already exists")
    else:
        print("Unexpected error: %s" % e)

The response dict in the exception will contain the following:

  • ['Error']['Code'] e.g. 'EntityAlreadyExists' or 'ValidationError'
  • ['ResponseMetadata']['HTTPStatusCode'] e.g. 400
  • ['ResponseMetadata']['RequestId'] e.g. 'd2b06652-88d7-11e5-99d0-812348583a35'
  • ['Error']['Message'] e.g. "An error occurred (EntityAlreadyExists) ..."
  • ['Error']['Type'] e.g. 'Sender'

For more information see:

[Updated: 2018-03-07]

The AWS Python SDK has begun to expose service exceptions on clients (though not on resources) that you can explicitly catch, so it is now possible to write that code like this:

import botocore
import boto3

try:
    iam = boto3.client('iam')
    user = iam.create_user(UserName='fred')
    print("Created user: %s" % user)
except iam.exceptions.EntityAlreadyExistsException:
    print("User already exists")
except botocore.exceptions.ParamValidationError as e:
    print("Parameter validation error: %s" % e)
except botocore.exceptions.ClientError as e:
    print("Unexpected error: %s" % e)

Unfortunately, there is currently no documentation for these exceptions but you can get a list of them as follows:

import botocore
import boto3
dir(botocore.exceptions)

Note that you must import both botocore and boto3. If you only import botocore then you will find that botocore has no attribute named exceptions. This is because the exceptions are dynamically populated into botocore by boto3.

Is there a Pattern Matching Utility like GREP in Windows?

May be Everything? It supports regexps and has a console util too.

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I noticed following line from error.

exact fetch returns more than requested number of rows

That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.

Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.

So, I truncated dual table and inserted only row which X value. And, everything working fine.

Can't import Numpy in Python

Your sys.path is kind of unusual, as each entry is prefixed with /usr/intel. I guess numpy is installed in the usual non-prefixed place, e.g. it. /usr/share/pyshared/numpy on my Ubuntu system.

Try find / -iname '*numpy*'

How to make a phone call using intent in Android?

More elegant option:

String phone = "+34666777888";
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null));
startActivity(intent);

ERROR 1049 (42000): Unknown database 'mydatabasename'

I found these lines in one of the .sql files

"To connect with a manager that does not use port 3306, you must specify the port number:

$mysqli = new mysqli('127.0.0.0.1','user','password','database','3307');

or, in procedural terms:

$mysqli = mysqli_connect('127.0.0.0.1','user','password','database','3307');"

It resolved the error for me . So i will suggest must use port number while making connection to server to resolve the error 1049(unknown database).

Delete item from array and shrink array

Since an array has a fixed size that is allocated when created, your only option is to create a new array without the element you want to remove.

If the element you want to remove is the last array item, this becomes easy to implement using Arrays.copy:

int a[] = { 1, 2, 3};
a = Arrays.copyOf(a, 2);

After running the above code, a will now point to a new array containing only 1, 2.

Otherwise if the element you want to delete is not the last one, you need to create a new array at size-1 and copy all the items to it except the one you want to delete.

The approach above is not efficient. If you need to manage a mutable list of items in memory, better use a List. Specifically LinkedList will remove an item from the list in O(1) (fastest theoretically possible).

How to compare two files in Notepad++ v6.6.8

Update:

  • for Notepad++ 7.5 and above use Compare v2.0.0
  • for Notepad++ 7.7 and above use Compare v2.0.0 for Notepad++ 7.7, if you need to install manually follow the description below, otherwise use "Plugin Admin".

I use Compare plugin 2 for notepad++ 7.5 and newer versions. Notepad++ 7.5 and newer versions does not have plugin manager. You have to download and install plugins manually. And YES it matters if you use 64bit or 32bit (86x).

So Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin, and the same valid for 32bit.

I wrote a guideline how to install it:

  1. Start your Notepad++ as administrator mode.
  2. Press F1 to find out if your Notepad++ is 64bit or 32bit (86x), hence you need to download the correct plugin version. Download Compare-plugin 2.
  3. Unzip Compare-plugin in temporary folder.
  4. Import plugin from the temporary folder.
  5. The plugin should appear under Plugins menu.

Note:
It is also possible to drag and drop the plugin .dll file directly in plugin folder.
64bit: %programfiles%\Notepad++\plugins
32bit: %programfiles(x86)%\Notepad++\plugins

Update Thanks to @TylerH with this update: Notepad++ Now has "Plugin Admin" as a replacement for the old Plugin Manager. But this method (answer) is still valid for adding plugins manually for almost any Notepad++ plugins.

Disclaimer: the link of this guideline refer to my personal web site.

How to adjust gutter in Bootstrap 3 grid system?

(Posted on behalf of the OP).

I believe I figured it out.

In my case, I added [class*="col-"] {padding: 0 7.5px;};.

Then added .row {margin: 0 -7.5px;}.

This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;} to .row {margin: 0 -8.5px;}, then it works perfectly.

I have no idea why there is a 1px margin. Maybe someone can explain it?

See the sample I created:

Demo
Code

How to disable Google Chrome auto update?

In addition to the most upvoted answer, it might be good to remove these as well for the sake of cleanness.

enter image description here

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

I wrote a package (https://github.com/alexsanjoseph/compareDF) since I had the same issue.

  > df1 <- data.frame(a = 1:5, b=letters[1:5], row = 1:5)
  > df2 <- data.frame(a = 1:3, b=letters[1:3], row = 1:3)
  > df_compare = compare_df(df1, df2, "row")

  > df_compare$comparison_df
    row chng_type a b
  1   4         + 4 d
  2   5         + 5 e

A more complicated example:

library(compareDF)
df1 = data.frame(id1 = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710",
                         "Hornet 4 Drive", "Duster 360", "Merc 240D"),
                 id2 = c("Maz", "Maz", "Dat", "Hor", "Dus", "Mer"),
                 hp = c(110, 110, 181, 110, 245, 62),
                 cyl = c(6, 6, 4, 6, 8, 4),
                 qsec = c(16.46, 17.02, 33.00, 19.44, 15.84, 20.00))

df2 = data.frame(id1 = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710",
                         "Hornet 4 Drive", " Hornet Sportabout", "Valiant"),
                 id2 = c("Maz", "Maz", "Dat", "Hor", "Dus", "Val"),
                 hp = c(110, 110, 93, 110, 175, 105),
                 cyl = c(6, 6, 4, 6, 8, 6),
                 qsec = c(16.46, 17.02, 18.61, 19.44, 17.02, 20.22))

> df_compare$comparison_df
    grp chng_type                id1 id2  hp cyl  qsec
  1   1         -  Hornet Sportabout Dus 175   8 17.02
  2   2         +         Datsun 710 Dat 181   4 33.00
  3   2         -         Datsun 710 Dat  93   4 18.61
  4   3         +         Duster 360 Dus 245   8 15.84
  5   7         +          Merc 240D Mer  62   4 20.00
  6   8         -            Valiant Val 105   6 20.22

The package also has an html_output command for quick checking

df_compare$html_output enter image description here

Can I apply multiple background colors with CSS3?

You can only use one color but as many images as you want, here is the format:

background: [ <bg-layer> , ]* <final-bg-layer>

<bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2}

<final-bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2} || <background-color>

or background: url(image1.png) center bottom no-repeat, url(image2.png) left top no-repeat;

If you need more colors, make an image of a solid color and use it. I know it’s not what you want to hear, but I hope it helps.

The format is from http://www.css3.info/preview/multiple-backgrounds/

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

If you are using .net core, then during development you can bypass certificate validation by using compiler directives. This way will only validate certificate for release and not for debug:

#if (DEBUG)
        client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
                new X509ServiceCertificateAuthentication()
                {
                    CertificateValidationMode = X509CertificateValidationMode.None,
                    RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck
                };   #endif

Clean out Eclipse workspace metadata

One of the things that you might want to try out is starting eclipse with the -clean option. If you have chosen to have eclipse use the same workspace every time then there is nothing else you need to do after that. With that option in place the workspace should be cleaned out.

However, if you don't have a default workspace chosen, when opening up eclipse you will be prompted to choose the workspace. At this point, choose the workspace you want cleaned up.

See "How to run eclipse in clean mode" and "Keeping Eclipse running clean" for more details.

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

I did this, also with jQuery:

$('input[type=search]').on('focus', function(){
  // replace CSS font-size with 16px to disable auto zoom on iOS
  $(this).data('fontSize', $(this).css('font-size')).css('font-size', '16px');
}).on('blur', function(){
  // put back the CSS font-size
  $(this).css('font-size', $(this).data('fontSize'));
});

Of course, some other elements in the interface may have to be adapted if this 16px font-size breaks the design.

Android: How do I prevent the soft keyboard from pushing my view up?

Just a single line to be added...

Add android:windowSoftInputMode="stateHidden|adjustPan" in required activity of your manifest file.

I just got solved :) :)

Why is the Android emulator so slow? How can we speed up the Android emulator?

Add some more RAM and use SSD drive. Android Studio is best run on 8 to 12 GB of RAM using SSD drives based on my experience.

OSError: [WinError 193] %1 is not a valid Win32 application

The file hello.py is not an executable file. You need to specify a file like python.exe

try following:

import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])

Convert file path to a file URI?

UrlCreateFromPath to the rescue! Well, not entirely, as it doesn't support extended and UNC path formats, but that's not so hard to overcome:

public static Uri FileUrlFromPath(string path)
{
    const string prefix = @"\\";
    const string extended = @"\\?\";
    const string extendedUnc = @"\\?\UNC\";
    const string device = @"\\.\";
    const StringComparison comp = StringComparison.Ordinal;

    if(path.StartsWith(extendedUnc, comp))
    {
        path = prefix+path.Substring(extendedUnc.Length);
    }else if(path.StartsWith(extended, comp))
    {
        path = prefix+path.Substring(extended.Length);
    }else if(path.StartsWith(device, comp))
    {
        path = prefix+path.Substring(device.Length);
    }

    int len = 1;
    var buffer = new StringBuilder(len);
    int result = UrlCreateFromPath(path, buffer, ref len, 0);
    if(len == 1) Marshal.ThrowExceptionForHR(result);

    buffer.EnsureCapacity(len);
    result = UrlCreateFromPath(path, buffer, ref len, 0);
    if(result == 1) throw new ArgumentException("Argument is not a valid path.", "path");
    Marshal.ThrowExceptionForHR(result);
    return new Uri(buffer.ToString());
}

[DllImport("shlwapi.dll", CharSet=CharSet.Auto, SetLastError=true)]
static extern int UrlCreateFromPath(string path, StringBuilder url, ref int urlLength, int reserved);

In case the path starts with with a special prefix, it gets removed. Although the documentation doesn't mention it, the function outputs the length of the URL even if the buffer is smaller, so I first obtain the length and then allocate the buffer.

Some very interesting observation I had is that while "\\device\path" is correctly transformed to "file://device/path", specifically "\\localhost\path" is transformed to just "file:///path".

The WinApi function managed to encode special characters, but leaves Unicode-specific characters unencoded, unlike the Uri construtor. In that case, AbsoluteUri contains the properly encoded URL, while OriginalString can be used to retain the Unicode characters.

Does Java support structs?

Along with Java 14, it starts supporting Record. You may want to check that https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Record.html

public record Person (String name, String address) {}

Person person = new Person("Esteban", "Stormhaven, Tamriel");

And there are Sealed Classes after Java 15. https://openjdk.java.net/jeps/360

sealed interface Shape permits Circle, Rectangle {

  record Circle(Point center, int radius) implements Shape { }

  record Rectangle(Point lowerLeft, Point upperRight) implements Shape { } 
}

How to know whether refresh button or browser back button is clicked in Firefox

For Back Button in jquery // http://code.jquery.com/jquery-latest.js

 jQuery(window).bind("unload", function() { //

and in html5 there is an event The event is called 'popstate'

window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

and for refresh please check Check if page gets reloaded or refreshed in Javascript

In Mozilla Client-x and client-y is inside document area https://developer.mozilla.org/en-US/docs/Web/API/event.clientX

Shell Script: Execute a python program from within a shell script

Save the following program as print.py:

#!/usr/bin/python3
print('Hello World')

Then in the terminal type:

chmod +x print.py
./print.py

Verify External Script Is Loaded

@jasper's answer is totally correct but with modern browsers, a standard Javascript solution could be:

function isScriptLoaded(src)
{
    return document.querySelector('script[src="' + src + '"]') ? true : false;
}

Print to the same line and not a new line?

for object "pega" that provides StartRunning(), StopRunning(), boolean getIsRunning() and integer getProgress100() returning value in range of 0 to 100, this provides text progress bar while running...

now = time.time()
timeout = now + 30.0
last_progress = -1

pega.StartRunning()

while now < timeout and pega.getIsRunning():
    time.sleep(0.5)
    now = time.time()

    progress = pega.getTubProgress100()
    if progress != last_progress:
        print('\r'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", end='', flush=True)
        last_progress = progress

pega.StopRunning()

progress = pega.getTubProgress100()
print('\r'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", flush=True)

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

Select a random sample of results from a query result

Sample function is used for sample data in ORACLE. So you can try like this:-

SELECT * FROM TABLE_NAME SAMPLE(50);

Here 50 is the percentage of data contained by the table. So if you want 1000 rows from 100000. You can execute a query like:

SELECT * FROM TABLE_NAME SAMPLE(1);

Hope this can help you.

Max size of an iOS application

50 Meg is the max for Cell data download.

But you might be able to keep it under that in the app store and then have the app download other content after the user install and runs the app, so the app can be bigger. But not sure what the apple rules are for this.

I know that all in-app purchases need to be approved, but not sure if this kind of content needs to be approved.

Download old version of package with NuGet

In NuGet 3.0 the Get-Package command is deprecated and replaced with Find-Package command.

Find-Package Common.Logging -AllVersions

See the NuGet command reference docs for details.

This is the message shown if you try to use Get-Package in Visual Studio 2015.

This Command/Parameter combination has been deprecated and will be removed
in the next release. Please consider using the new command that replaces it: 
'Find-Package [-Id] -AllVersions'

Or as @Yishai said, you can use the version number dropdown in the NuGet screen in Visual Studio.

WordPress: get author info from post id

If you want it outside of loop then use the below code.

<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id ); 
echo $display_name;
?>

PHP foreach change original array values

Try this

function checkForm($fields){
        foreach($fields as $field){
            if($field['required'] && strlen($_POST[$field['name']]) <= 0){
                $field['value'] = "Some error";
            }
        }
        return $field;
    }

jQuery access input hidden value

To get value, use:

$.each($('input'),function(i,val){
    if($(this).attr("type")=="hidden"){
        var valueOfHidFiled=$(this).val();
        alert(valueOfHidFiled);
    }
});

or:

var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);

To set value, use:

$('input[type=hidden]').attr('value',newValue);

java.time.format.DateTimeParseException: Text could not be parsed at index 21

The default parser can parse your input. So you don't need a custom formatter and

String dateTime = "2012-02-22T02:06:58.147Z";
ZonedDateTime d = ZonedDateTime.parse(dateTime);

works as expected.

Quickest way to compare two generic lists for differences

Maybe it's funny, but this works for me:

string.Join("",List1) != string.Join("", List2)

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1.

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

How do I change the ID of a HTML element with JavaScript?

You can modify the id without having to use getElementById

Example:

<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>

You can see it here: http://jsbin.com/elikaj/1/

Tested with Mozilla Firefox 22 and Google Chrome 60.0

Change key pair for ec2 instance

Instruction from AWS EC2 support:

  1. Change pem login
  2. go to your EC2 Console
  3. Under NETWORK & SECURITY, click on Key Pair Click on Create Key Pair
  4. Give your new key pair a name, save the .pem file. The name of the key pair will be used to connect to your instance
  5. Create SSH connection to your instance and keep it open
  6. in PuttyGen, click "Load" to load your .pem file
  7. Keep the SSH-2 RSA radio button checked. Click on "Save private key" You'll get pop-up window warning, click "Yes”
  8. click on "Save public key" as well, so to generate the public key. This is the public key that we're going to copy across to your current instance
  9. Save the public key with the new key pair name and with the extension .pub
  10. Open the public key content in a notepad
  11. copy the content below "Comment: "imported-openssh-key" and before "---- END SSH2 PUBLIC KEY ----
    Note - you need to copy the content as one line - delete all new lines
  12. on your connected instance, open your authorized_keys file using the tool vi. Run the following command: vi .ssh/authorized_keys you should see the original public key in the file also
  13. move your cursor on the file to the end of your first public key content :type "i" for insert
  14. on the new line, type "ssh-rsa" and add a space before you paste the content of the public key , space, and the name of the .pem file (without the .pem) Note - you should get a line with the same format as the previous line
  15. press the Esc key, and then type :wq!

this will save the updated authorized_keys file

now try open a new SSH session to your instance using your new key pai

When you've confirmed you're able to SSH into the instance using the new key pair, u can vi .ssh/authorized_key and delete the old key.

Answer to Shaggie remark:

If you are unable to connect to the instance (e.g. key is corrupted) than use the AWS console to detach the volume (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) and reattach it to working instance, than change the key on the volume and reattach it back to the previous instance.

How do I format a number with commas in T-SQL?

In SQL Server 2012 and higher, this will format a number with commas:

select format([Number], 'N0')

You can also change 0 to the number of decimal places you want.

Listing information about all database files in SQL Server

Using this script you can show all the databases name and files used (with exception of system dbs).

select name,physical_name from sys.master_files where database_id > 4

Learning Ruby on Rails

Once you get your environment up and running, this is helpful in giving you a basic app that users can log into.

Restful Authentication with all the bells and whistles: http://railsforum.com/viewtopic.php?id=14216&p=1

Select Tag Helper in ASP.NET Core MVC

Using the Select Tag helpers to render a SELECT element

In your GET action, create an object of your view model, load the EmployeeList collection property and send that to the view.

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.EmployeesList = new List<Employee>
    {
        new Employee { Id = 1, FullName = "Shyju" },
        new Employee { Id = 2, FullName = "Bryan" }
    };
    return View(vm);
}

And in your create view, create a new SelectList object from the EmployeeList property and pass that as value for the asp-items property.

@model MyViewModel
<form asp-controller="Home" asp-action="Create">

    <select asp-for="EmployeeId" 
            asp-items="@(new SelectList(Model.EmployeesList,"Id","FullName"))">
        <option>Please select one</option>
    </select>

    <input type="submit"/>

</form>

And your HttpPost action method to accept the submitted form data.

[HttpPost]
public IActionResult Create(MyViewModel model)
{
   //  check model.EmployeeId 
   //  to do : Save and redirect
}

Or

If your view model has a List<SelectListItem> as the property for your dropdown items.

public class MyViewModel
{
    public int EmployeeId { get; set; }
    public string Comments { get; set; }
    public List<SelectListItem> Employees { set; get; }
}

And in your get action,

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.Employees = new List<SelectListItem>
    {
        new SelectListItem {Text = "Shyju", Value = "1"},
        new SelectListItem {Text = "Sean", Value = "2"}
    };
    return View(vm);
}

And in the view, you can directly use the Employees property for the asp-items.

@model MyViewModel
<form asp-controller="Home" asp-action="Create">

    <label>Comments</label>
    <input type="text" asp-for="Comments"/>

    <label>Lucky Employee</label>
    <select asp-for="EmployeeId" asp-items="@Model.Employees" >
        <option>Please select one</option>
    </select>

    <input type="submit"/>

</form>

The class SelectListItem belongs to Microsoft.AspNet.Mvc.Rendering namespace.

Make sure you are using an explicit closing tag for the select element. If you use the self closing tag approach, the tag helper will render an empty SELECT element!

The below approach will not work

<select asp-for="EmployeeId" asp-items="@Model.Employees" />

But this will work.

<select asp-for="EmployeeId" asp-items="@Model.Employees"></select>

Getting data from your database table using entity framework

The above examples are using hard coded items for the options. So i thought i will add some sample code to get data using Entity framework as a lot of people use that.

Let's assume your DbContext object has a property called Employees, which is of type DbSet<Employee> where the Employee entity class has an Id and Name property like this

public class Employee
{
   public int Id { set; get; }
   public string Name { set; get; }
}

You can use a LINQ query to get the employees and use the Select method in your LINQ expression to create a list of SelectListItem objects for each employee.

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.Employees = context.Employees
                          .Select(a => new SelectListItem() {  
                              Value = a.Id.ToString(),
                              Text = a.Name
                          })
                          .ToList();
    return View(vm);
}

Assuming context is your db context object. The view code is same as above.

Using SelectList

Some people prefer to use SelectList class to hold the items needed to render the options.

public class MyViewModel
{
    public int EmployeeId { get; set; }
    public SelectList Employees { set; get; }
}

Now in your GET action, you can use the SelectList constructor to populate the Employees property of the view model. Make sure you are specifying the dataValueField and dataTextField parameters.

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.Employees = new SelectList(GetEmployees(),"Id","FirstName");
    return View(vm);
}
public IEnumerable<Employee> GetEmployees()
{
    // hard coded list for demo. 
    // You may replace with real data from database to create Employee objects
    return new List<Employee>
    {
        new Employee { Id = 1, FirstName = "Shyju" },
        new Employee { Id = 2, FirstName = "Bryan" }
    };
}

Here I am calling the GetEmployees method to get a list of Employee objects, each with an Id and FirstName property and I use those properties as DataValueField and DataTextField of the SelectList object we created. You can change the hardcoded list to a code which reads data from a database table.

The view code will be same.

<select asp-for="EmployeeId" asp-items="@Model.Employees" >
    <option>Please select one</option>
</select>

Render a SELECT element from a list of strings.

Sometimes you might want to render a select element from a list of strings. In that case, you can use the SelectList constructor which only takes IEnumerable<T>

var vm = new MyViewModel();
var items = new List<string> {"Monday", "Tuesday", "Wednesday"};
vm.Employees = new SelectList(items);
return View(vm);

The view code will be same.

Setting selected options

Some times,you might want to set one option as the default option in the SELECT element (For example, in an edit screen, you want to load the previously saved option value). To do that, you may simply set the EmployeeId property value to the value of the option you want to be selected.

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.Employees = new List<SelectListItem>
    {
        new SelectListItem {Text = "Shyju", Value = "11"},
        new SelectListItem {Text = "Tom", Value = "12"},
        new SelectListItem {Text = "Jerry", Value = "13"}
    };
    vm.EmployeeId = 12;  // Here you set the value
    return View(vm);
}

This will select the option Tom in the select element when the page is rendered.

Multi select dropdown

If you want to render a multi select dropdown, you can simply change your view model property which you use for asp-for attribute in your view to an array type.

public class MyViewModel
{
    public int[] EmployeeIds { get; set; }
    public List<SelectListItem> Employees { set; get; }
}

This will render the HTML markup for the select element with the multiple attribute which will allow the user to select multiple options.

@model MyViewModel
<select id="EmployeeIds" multiple="multiple" name="EmployeeIds">
    <option>Please select one</option>
    <option value="1">Shyju</option>
    <option value="2">Sean</option>
</select>

Setting selected options in multi select

Similar to single select, set the EmployeeIds property value to the an array of values you want.

public IActionResult Create()
{
    var vm = new MyViewModel();
    vm.Employees = new List<SelectListItem>
    {
        new SelectListItem {Text = "Shyju", Value = "11"},
        new SelectListItem {Text = "Tom", Value = "12"},
        new SelectListItem {Text = "Jerry", Value = "13"}
    };
    vm.EmployeeIds= new int[] { 12,13} ;  
    return View(vm);
}

This will select the option Tom and Jerry in the multi select element when the page is rendered.

Using ViewBag to transfer the list of items

If you do not prefer to keep a collection type property to pass the list of options to the view, you can use the dynamic ViewBag to do so.(This is not my personally recommended approach as viewbag is dynamic and your code is prone to uncatched typo errors)

public IActionResult Create()
{       
    ViewBag.Employees = new List<SelectListItem>
    {
        new SelectListItem {Text = "Shyju", Value = "1"},
        new SelectListItem {Text = "Sean", Value = "2"}
    };
    return View(new MyViewModel());
}

and in the view

<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
    <option>Please select one</option>
</select>

Using ViewBag to transfer the list of items and setting selected option

It is same as above. All you have to do is, set the property (for which you are binding the dropdown for) value to the value of the option you want to be selected.

public IActionResult Create()
{       
    ViewBag.Employees = new List<SelectListItem>
    {
        new SelectListItem {Text = "Shyju", Value = "1"},
        new SelectListItem {Text = "Bryan", Value = "2"},
        new SelectListItem {Text = "Sean", Value = "3"}
    };

    vm.EmployeeId = 2;  // This will set Bryan as selected

    return View(new MyViewModel());
}

and in the view

<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
    <option>Please select one</option>
</select>

Grouping items

The select tag helper method supports grouping options in a dropdown. All you have to do is, specify the Group property value of each SelectListItem in your action method.

public IActionResult Create()
{
    var vm = new MyViewModel();

    var group1 = new SelectListGroup { Name = "Dev Team" };
    var group2 = new SelectListGroup { Name = "QA Team" };

    var employeeList = new List<SelectListItem>()
    {
        new SelectListItem() { Value = "1", Text = "Shyju", Group = group1 },
        new SelectListItem() { Value = "2", Text = "Bryan", Group = group1 },
        new SelectListItem() { Value = "3", Text = "Kevin", Group = group2 },
        new SelectListItem() { Value = "4", Text = "Alex", Group = group2 }
    };
    vm.Employees = employeeList;
    return View(vm);
}

There is no change in the view code. the select tag helper will now render the options inside 2 optgroup items.

Extension methods must be defined in a non-generic static class

Add keyword static to class declaration:

// this is a non-generic static class
public static class LinqHelper
{
}

Best TCP port number range for internal applications

I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!

If they're not, then they haven't been done very well. Go back and do them properly :-)

In other words, run the server at IP address X and port Y then configure clients with that information. Then, if you find you must run a different server on X that conflicts with your Y, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.

I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).

Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:

telnet big_honking_mainframe_box.com 1023

If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.

How to get SLF4J "Hello World" working with log4j?

Following is an example. You can see the details http://jkssweetlife.com/configure-slf4j-working-various-logging-frameworks/ and download the full codes here.

  • Add following dependency to your pom if you are using maven, otherwise, just download the jar files and put on your classpath

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.7</version>
    </dependency>
    
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
    
  • Configure log4j.properties

    log4j.rootLogger=TRACE, stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSS} %-5p [%c] - %m%n
    
  • Java example

    public class Slf4jExample {
        public static void main(String[] args) {
    
            Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
    
            final String message = "Hello logging!";
            logger.trace(message);
            logger.debug(message);
            logger.info(message);
            logger.warn(message);
            logger.error(message);
        }
    }
    

How to make a section of an image a clickable link

The easiest way is to make the "button image" as a separate image. Then place it over the main image (using "style="position: absolute;". Assign the URL link to "button image". and smile :)

What happens if you mount to a non-empty mount point with fuse?

Just add -o nonempty in command line, like this:

s3fs -o nonempty  <bucket-name> </mount/point/>

How can I suppress the newline after a print statement?

The question asks: "How can it be done in Python 3?"

Use this construct with Python 3.x:

for item in [1,2,3,4]:
    print(item, " ", end="")

This will generate:

1  2  3  4

See this Python doc for more information:

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

--

Aside:

in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,

In [21]: print('this','is', 'a', 'test')  # default single space between items
this is a test

In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest

In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test

MySQL match() against() - order by relevance and column?

Just adding for who might need.. Don't forget to alter the table!

ALTER TABLE table_name ADD FULLTEXT(column_name);

To delay JavaScript function call using jQuery

Since you declare sample inside the anonymous function you pass to ready, it is scoped to that function.

You then pass a string to setTimeout which is evaled after 2 seconds. This takes place outside the current scope, so it can't find the function.

Only pass functions to setTimeout, using eval is inefficient and hard to debug.

setTimeout(sample,2000)

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

Maven: Failed to retrieve plugin descriptor error

I wouldn't advise you to do this but on my personal computer I disabled the firewall so that maven could get the required plugins.

How Connect to remote host from Aptana Studio 3

Window -> Show View -> Other -> Studio/Remote

(Drag this tabbed window wherever)

Click the add FTP button (see below); #profit

Add New FTP Site...

SVN: Folder already under version control but not comitting?

Have you tried performing an svn cleanup?

How to position background image in bottom right corner? (CSS)

This should do it:

<style>
body {
    background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>

http://www.w3schools.com/cssref/pr_background-position.asp

In c# what does 'where T : class' mean?

It is a generic type constraint. In this case it means that the generic type T has to be a reference type (class, interface, delegate, or array type).

How to select all the columns of a table except one column?

  1. Generate your select query with any good autocomplete editor of your database.
  2. copy and paste your select query in a reserved method (function) and return its ResultSet to your main program or do your stuff in the same method.
  3. call this method each time whenever you require

Remove from the beginning of std::vector

Two suggestions:

  1. Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
  2. Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;

How can I replace a newline (\n) using sed?

This is really simple... I really get irritated when I found the solution. There was just one more back slash missing. This is it:

sed -i "s/\\\\\n//g" filename

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

If you add a $scope.$apply(); right after $scope.pluginsDisplayed.splice(index,1); then it works.

I am not sure why this is happening, but basically when AngularJS doesn't know that the $scope has changed, it requires to call $apply manually. I am also new to AngularJS so cannot explain this better. I need too look more into it.

I found this awesome article that explains it quite properly. Note: I think it might be better to use ng-click (docs) rather than binding to "mousedown". I wrote a simple app here (http://avinash.me/losh, source http://github.com/hardfire/losh) based on AngularJS. It is not very clean, but it might be of help.

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

It's as simple as that:

function isMacintosh() {
  return navigator.platform.indexOf('Mac') > -1
}

function isWindows() {
  return navigator.platform.indexOf('Win') > -1
}

You can do funny things then like:

var isMac = isMacintosh();
var isPC = !isMacintosh();

TSQL - Cast string to integer or return default value

If you are on SQL Server 2012 (or newer):

Use the TRY_CONVERT function.

If you are on SQL Server 2005, 2008, or 2008 R2:

Create a user defined function. This will avoid the issues that Fedor Hajdu mentioned with regards to currency, fractional numbers, etc:

CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS int
AS
BEGIN
    SET @Value = REPLACE(@Value, ',', '')
    IF ISNUMERIC(@Value + 'e0') = 0 RETURN NULL
    IF ( CHARINDEX('.', @Value) > 0 AND CONVERT(bigint, PARSENAME(@Value, 1)) <> 0 ) RETURN NULL
    DECLARE @I bigint =
        CASE
        WHEN CHARINDEX('.', @Value) > 0 THEN CONVERT(bigint, PARSENAME(@Value, 2))
        ELSE CONVERT(bigint, @Value)
        END
    IF ABS(@I) > 2147483647 RETURN NULL
    RETURN @I
END
GO

-- Testing
DECLARE @Test TABLE(Value nvarchar(50))    -- Result
INSERT INTO @Test SELECT '1234'            -- 1234
INSERT INTO @Test SELECT '1,234'           -- 1234
INSERT INTO @Test SELECT '1234.0'          -- 1234
INSERT INTO @Test SELECT '-1234'           -- -1234
INSERT INTO @Test SELECT '$1234'           -- NULL
INSERT INTO @Test SELECT '1234e10'         -- NULL
INSERT INTO @Test SELECT '1234 5678'       -- NULL
INSERT INTO @Test SELECT '123-456'         -- NULL
INSERT INTO @Test SELECT '1234.5'          -- NULL
INSERT INTO @Test SELECT '123456789000000' -- NULL
INSERT INTO @Test SELECT 'N/A'             -- NULL
SELECT Value, dbo.TryConvertInt(Value) FROM @Test

Reference: I used this page extensively when creating my solution.

Standard way to embed version into python package?

There doesn't seem to be a standard way to embed a version string in a python package. Most packages I've seen use some variant of your solution, i.e. eitner

  1. Embed the version in setup.py and have setup.py generate a module (e.g. version.py) containing only version info, that's imported by your package, or

  2. The reverse: put the version info in your package itself, and import that to set the version in setup.py

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file = input.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {
            console.log(line);
        });
    };

    reader.onerror = (event) => {
        alert(event.target.error.name);
    };

    reader.readAsText(file);
}

is there a css hack for safari only NOT chrome?

For those who want to implement a hack for Safari 7.0 and below, but not 7.1 and above -- use:

.myclass { (;property: value;); }
.myclass { [;property: value;]; }

Config Error: This configuration section cannot be used at this path

On Windows Server 2012 with IIS 8 I have solved this by enabling ASP.NET 4.5 feature:

enter image description here

and then following ken's answer.

MessageBox with YesNoCancel - No & Cancel triggers same event

The way I use a yes/no prompt is:

If MsgBox("Are you sure?", MsgBoxStyle.YesNo) <> MsgBoxResults.Yes Then
    Exit Sub
End If

How to filter input type="file" dialog by specific file type?

See http://www.w3schools.com/tags/att_input_accept.asp:

The accept attribute is supported in all major browsers, except Internet Explorer and Safari. Definition and Usage

The accept attribute specifies the types of files that the server accepts (that can be submitted through a file upload).

Note: The accept attribute can only be used with <input type="file">.

Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.

Syntax <input accept="audio/*|video/*|image/*|MIME_type" />

Tip: To specify more than one value, separate the values with a comma (e.g. <input accept="audio/*,video/*,image/*" />.

How to store custom objects in NSUserDefaults

Swift 3

class MyObject: NSObject, NSCoding  {
    let name : String
    let url : String
    let desc : String

    init(tuple : (String,String,String)){
        self.name = tuple.0
        self.url = tuple.1
        self.desc = tuple.2
    }
    func getName() -> String {
        return name
    }
    func getURL() -> String{
        return url
    }
    func getDescription() -> String {
        return desc
    }
    func getTuple() -> (String, String, String) {
        return (self.name,self.url,self.desc)
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
        self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
        self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.name, forKey: "name")
        aCoder.encode(self.url, forKey: "url")
        aCoder.encode(self.desc, forKey: "desc")
    }
    }

to store and retrieve:

func save() {
            let data  = NSKeyedArchiver.archivedData(withRootObject: object)
            UserDefaults.standard.set(data, forKey:"customData" )
        }
        func get() -> MyObject? {
            guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
            return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
        }

Is there a way to SELECT and UPDATE rows at the same time?

It'd be easier to do your UPDATE first and then run 'SELECT ID FROM INSERTED'.

Take a look at SQL Tips for more info and examples.

JOIN queries vs multiple queries

Construct both separate queries and joins, then time each of them -- nothing helps more than real-world numbers.

Then even better -- add "EXPLAIN" to the beginning of each query. This will tell you how many subqueries MySQL is using to answer your request for data, and how many rows scanned for each query.

Difference between Running and Starting a Docker container

Explanation with an example:

Consider you have a game (iso) image in your computer.

When you run (mount your image as a virtual drive), a virtual drive is created with all the game contents in the virtual drive and the game installation file is automatically launched. [Running your docker image - creating a container and then starting it.]

But when you stop (similar to docker stop) it, the virtual drive still exists but stopping all the processes. [As the container exists till it is not deleted]

And when you do start (similar to docker start), from the virtual drive the games files start its execution. [starting the existing container]

In this example - The game image is your Docker image and virtual drive is your container.

Get safe area inset top and bottom heights

I'm working with CocoaPods frameworks and in case UIApplication.shared is unavailable then I use safeAreaInsets in view's window:

if #available(iOS 11.0, *) {
    let insets = view.window?.safeAreaInsets
    let top = insets.top
    let bottom = insets.bottom
}

Function ereg_replace() is deprecated - How to clear this bug?

print $input."<hr>".ereg_replace('/&/', ':::', $input);

becomes

print $input."<hr>".preg_replace('/&/', ':::', $input);

More example :

$mytext = ereg_replace('[^A-Za-z0-9_]', '', $mytext );

is changed to

$mytext = preg_replace('/[^A-Za-z0-9_]/', '', $mytext );

How do you refresh the MySQL configuration file without restarting?

Try:

sudo /etc/init.d/mysql reload

or

sudo /etc/init.d/mysql force-reload

That should initiate a reload of the configuration. Make sureyour init.d script supports it though, I don't know what version of MySQL/OS you are using?

My MySQL script contains the following:

'reload'|'force-reload')
        log_daemon_msg "Reloading MySQL database server" "mysqld"
        $MYADMIN reload
        log_end_msg 0
        ;;

Sql Server return the value of identity column after insert statement

You can explicitly get back Identity columns using SqlServer's OUTPUT clause: Assuming you have an identity/auto-increment column called ID:

$sql='INSERT INTO [xyz].[myTable] (Field1, Field2, Field3) OUTPUT Inserted.ID VALUES  (1, 2, '3')';

Note that in Perl DBI you would then execute the INSERT statement, just like it was a SELECT. And capture the output like it was a SELECT

$sth->execute($sql);
@row=$sth->fetchrow_array; #Only 1 val in 1 row returned
print "Inserted ID: ", $row[0], "\n";

Presumably this is preferable because it doesn't require another request.

using extern template (C++11)

Wikipedia has the best description

In C++03, the compiler must instantiate a template whenever a fully specified template is encountered in a translation unit. If the template is instantiated with the same types in many translation units, this can dramatically increase compile times. There is no way to prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern data declarations.

C++03 has this syntax to oblige the compiler to instantiate a template:

  template class std::vector<MyClass>;

C++11 now provides this syntax:

  extern template class std::vector<MyClass>;

which tells the compiler not to instantiate the template in this translation unit.

The warning: nonstandard extension used...

Microsoft VC++ used to have a non-standard version of this feature for some years already (in C++03). The compiler warns about that to prevent portability issues with code that needed to compile on different compilers as well.

Look at the sample in the linked page to see that it works roughly the same way. You can expect the message to go away with future versions of MSVC, except of course when using other non-standard compiler extensions at the same time.

Fix footer to bottom of page

The Footer be positioned at the bottom of the page, but not fixed.

CSS

html {
  height: 100%;
}

body {
  position: relative;
  margin: 0;
  min-height: 100%;  
  padding: 0;
}
#header {
  background: #595959;
  height: 90px;
}
#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 90px;
  background-color: #595959;
}

HTML

<html>
   <head></head>
   <body>        
      <div id="header"></div>
      <div id="content"></div>
      <div id="footer"></div>     
   </body>
</html>  

How can I select all children of an element except the last child?

You can use the negation pseudo-class :not() against the :last-child pseudo-class. Being introduced CSS Selectors Level 3, it doesn't work in IE8 or below:

:not(:last-child) { /* styles */ }

Remove new lines from string and replace with one empty space

this below code work all text please use it:

$des = str_replace('\n',' ',$des);
$des = str_replace('\r',' ',$des);

Can PHP cURL retrieve response headers AND body in a single request?

My way is

$response = curl_exec($ch);
$x = explode("\r\n\r\n", $v, 3);
$header=http_parse_headers($x[0]);
if ($header=['Response Code']==100){ //use the other "header"
    $header=http_parse_headers($x[1]);
    $body=$x[2];
}else{
    $body=$x[1];
}

If needed apply a for loop and remove the explode limit.

Something like 'contains any' for Java set?

There's a bit rough method to do that. If and only if the A set contains some B's element than the call

A.removeAll(B)

will modify the A set. In this situation removeAll will return true (As stated at removeAll docs). But probably you don't want to modify the A set so you may think to act on a copy, like this way:

new HashSet(A).removeAll(B)

and the returning value will be true if the sets are not distinct, that is they have non-empty intersection.

Also see Apache Commons Collections

Is it possible to implement a Python for range loop without an iterator variable?

We have had some fun with the following, interesting to share so:

class RepeatFunction:
    def __init__(self,n=1): self.n = n
    def __call__(self,Func):
        for i in xrange(self.n):
            Func()
        return Func


#----usage
k = 0

@RepeatFunction(7)                       #decorator for repeating function
def Job():
    global k
    print k
    k += 1

print '---------'
Job()

Results:

0
1
2
3
4
5
6
---------
7

How to put a UserControl into Visual Studio toolBox

Basic qustion if you are using generics in your base control. If yes:

lets say we have control:

public class MyComboDropDown : ComboDropDownComon<MyType>
{
    public MyComboDropDown() { }
}

MyComboDropDown will not allow to open designer on it and will be not shown in Toolbox. Why? Because base control is not already compiled - when MyComboDropDown is complied. You can modify to this:

public class MyComboDropDown : MyComboDropDownBase
{
    public MyComboDropDown() { }
}

public class MyComboDropDownBase : ComboDropDownComon<MyType>
{

}

Than after rebuild, and reset toolbox it should be able to see MyComboDropDown in designer and also in Toolbox

Push eclipse project to GitHub with EGit

I have the same issue and solved it by reading this post, while solving it, I hitted a problem: auth failed.

And I finally solved it by using a ssh key way to authorize myself. I found the EGit offical guide very useful and I configured the ssh way successfully by refer to the Eclipse SSH Configuration section in the link provided.

Hope it helps.

Setting up maven dependency for SQL Server

Even after installing the sqlserver jar, my maven was trying to fetch the dependecy from maven repository. I then, provided my pom the repository of my local machine and it works fine after that...might be of help for someone.

    <repository>
        <id>local</id>
        <name>local</name>
        <url>file://C:/Users/mywindows/.m2/repository</url>
    </repository>

AngularJS routing without the hash '#'

The following information is from:
https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag

It is very easy to get clean URLs and remove the hashtag from the URL in Angular.
By default, AngularJS will route URLs with a hashtag For Example:

There are 2 things that need to be done.

  • Configuring $locationProvider

  • Setting our base for relative links

  • $location Service

In Angular, the $location service parses the URL in the address bar and makes changes to your application and vice versa.

I would highly recommend reading through the official Angular $location docs to get a feel for the location service and what it provides.

https://docs.angularjs.org/api/ng/service/$location

$locationProvider and html5Mode

  • We will use the $locationProvider module and set html5Mode to true.
  • We will do this when defining your Angular application and configuring your routes.

    angular.module('noHash', [])
    
    .config(function($routeProvider, $locationProvider) {
    
       $routeProvider
           .when('/', {
               templateUrl : 'partials/home.html',
               controller : mainController
           })
           .when('/about', {
               templateUrl : 'partials/about.html',
               controller : mainController
           })
           .when('/contact', {
               templateUrl : 'partials/contact.html',
               controller : mainController
           });
    
       // use the HTML5 History API
       $locationProvider.html5Mode(true); });
    

What is the HTML5 History API? It is a standardized way to manipulate the browser history using a script. This lets Angular change the routing and URLs of our pages without refreshing the page. For more information on this, here is a good HTML5 History API Article:

http://diveintohtml5.info/history.html

Setting For Relative Links

  • To link around your application using relative links, you will need to set the <base> in the <head> of your document. This may be in the root index.html file of your Angular app. Find the <base> tag, and set it to the root URL you'd like for your app.

For example: <base href="/">

  • There are plenty of other ways to configure this, and the HTML5 mode set to true should automatically resolve relative links. If your root of your application is different than the url (for instance /my-base, then use that as your base.

Fallback for Older Browsers

  • The $location service will automatically fallback to the hashbang method for browsers that do not support the HTML5 History API.
  • This happens transparently to you and you won’t have to configure anything for it to work. From the Angular $location docs, you can see the fallback method and how it works.

In Conclusion

  • This is a simple way to get pretty URLs and remove the hashtag in your Angular application. Have fun making those super clean and super fast Angular apps!

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

If you have an AMD Ryzen processor in your computer you need the following setup requirements to be in place:

  1. AMD Processor - Recommended: AMD® Ryzen™ processors
  2. Android Studio 3.2 Beta or higher - download via Android Studio Preview page
  3. Android Emulator v27.3.8+ - download via Android Studio SDK Manager
  4. x86 Android Virtual Device (AVD) - Create AVD
  5. Windows 10 with April 2018 Update
  6. Enable via Windows Features: "Windows Hypervisor Platform"

Note:There is Hyper-V features... You should enable Windows Hypervisor Platform not Hyper-V. Windows Hypervisor Platform is at the bottom

After conditions done avd x86 work without haxm install

Reference

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

Not the answer for this question

I got this exception when trying to delete a folder where i deleted the file inside.

Example:

createFolder("folder");  
createFile("folder/file");  
deleteFile("folder/file");  
deleteFolder("folder"); // error here

While deleteFile("folder/file"); returned that it was deleted, the folder will only be considered empty after the program restart.

On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#delete-java.nio.file.Path-

Explanation from dhke

Controller not a function, got undefined, while defining controllers globally

I was getting this error because I was using an older version of angular that wasn't compatible with my code.

Passing null arguments to C# methods

Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?

e.g.

private void Example(int? arg1, int? arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}

JavaScript: location.href to open in new window/tab?

You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.

Java - No enclosing instance of type Foo is accessible

You've declared the class Thing as a non-static inner class. That means it must be associated with an instance of the Hello class.

In your code, you're trying to create an instance of Thing from a static context. That is what the compiler is complaining about.

There are a few possible solutions. Which solution to use depends on what you want to achieve.

  • Move Thing out of the Hello class.

  • Change Thing to be a static nested class.

    static class Thing
    
  • Create an instance of Hello before creating an instance of Thing.

    public static void main(String[] args)
    {
        Hello h = new Hello();
        Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
    }
    

The last solution (a non-static nested class) would be mandatory if any instance of Thing depended on an instance of Hello to be meaningful. For example, if we had:

public class Hello {
    public int enormous;

    public Hello(int n) {
        enormous = n;
    }

    public class Thing {
        public int size;

        public Thing(int m) {
            if (m > enormous)
                size = enormous;
            else
                size = m;
        }
    }
    ...
}

any raw attempt to create an object of class Thing, as in:

Thing t = new Thing(31);

would be problematic, since there wouldn't be an obvious enormous value to test 31 against it. An instance h of the Hello outer class is necessary to provide this h.enormous value:

...
Hello h = new Hello(30);
...
Thing t = h.new Thing(31);
...

Because it doesn't mean a Thing if it doesn't have a Hello.

For more information on nested/inner classes: Nested Classes (The Java Tutorials)

Invoke-customs are only supported starting with android 0 --min-api 26

If you have Java 7 so include the below following snippet within your app-level build.gradle :

compileOptions {

    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7

}

Print directly from browser without print popup window

this.print(false);

I tried this in Chrome, Firefox and IE. It works only in Firefox and IE, it uses the default printer (with default print settings) and only works when I render a PDF (I use Foxit Reader with Safe Reading Mode disabled). Chrome shows the print dialog, also the other browsers when I render an HTML page.

How to move a marker in Google Maps API

use panTo(x,y).This will help u

How to use JavaScript source maps (.map files)?

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.

So, to answer you questions in order:

  • What is it for? To de-reference uglified code
  • How can a developer use it? You use it for debugging a production app. In development mode you can use the full version of Angular. In production, you would use the minified version.
  • Should I care about creating a js.map file? If you care about being able to debug production code easier, then yes, you should do it.
  • How does it get created? It is created at build time. There are build tools that can build your .map file for you as it does other files. https://github.com/gruntjs/grunt-contrib-uglify/issues/71

I hope this makes sense.

How to run a hello.js file in Node.js on windows?

Go to cmd and type: node "C:\Path\To\File\Sample.js"

Can I force a page break in HTML printing?

Just wanted to put an update. page-break-after is a legacy property now.

Official page states

This property has been replaced by the break-after property.

Is there a Python equivalent of the C# null-coalescing operator?

other = s or "some default value"

Ok, it must be clarified how the or operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.

Note that the or operator does not return only True or False. Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.

In this case, the expression x or y returns x if it is True or evaluates to true when converted to boolean. Otherwise, it returns y. For most cases, this will serve for the very same purpose of C?'s null-coalescing operator, but keep in mind:

42    or "something"    # returns 42
0     or "something"    # returns "something"
None  or "something"    # returns "something"
False or "something"    # returns "something"
""    or "something"    # returns "something"

If you use your variable s to hold something that is either a reference to the instance of a class or None (as long as your class does not define members __nonzero__() and __len__()), it is secure to use the same semantics as the null-coalescing operator.

In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using None specifically (an error object, for example).

In some languages this behavior is referred to as the Elvis operator.

Android, How to read QR code in my application?

Use a QR library like ZXing... I had very good experience with it, QrDroid is much buggier. If you must rely on an external reader, rely on a standard one like Google Goggles!

Merge (Concat) Multiple JSONObjects in Java

Merging typed data structure trees is not trivial, you need to define the precedence, handle incompatible types, define how they will be casted and merged...

So in my opinion, you won't avoid

... pulling them all apart and individually adding in by puts`.

If your question is: Has someone done it for me yet? Then I think you can have a look at this YAML merging library/tool I revived. (YAML is a superset of JSON), and the principles are applicable to both.
(However, this particular code returns YAML objects, not JSON. Feel free to extend the project and send a PR.)

Implement division with bit-wise operator

All these solutions are too long. The base idea is to write the quotient (for example, 5=101) as 100 + 00 + 1 = 101.

public static Point divide(int a, int b) {

    if (a < b)
        return new Point(0,a);
    if (a == b)
        return new Point(1,0);
    int q = b;
    int c = 1;
    while (q<<1 < a) {
        q <<= 1;
        c <<= 1;
    }
    Point r = divide(a-q, b);
    return new Point(c + r.x, r.y);
}


public static class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int compare(Point b) {
        if (b.x - x != 0) {
            return x - b.x;
        } else {
            return y - b.y;
        }
    }

    @Override
    public String toString() {
        return " (" + x + " " + y + ") ";
    }
}

How do I generate a random int number?

I will assume that you want a uniformly distributed random number generator like below. Random number in most of programming language including C# and C++ is not properly shuffled before using them. This means that you will get the same number over and over, which isn't really random. To avoid to draw the same number over and over, you need a seed. Typically, ticks in time is ok for this task. Remember that you will get the same number over and over if you are using the same seed every time. So try to use varying seed always. Time is a good source for seed because they chage always.

int GetRandomNumber(int min, int max)
{
    Random rand = new Random((int)DateTime.Now.Ticks);
    return rand.Next(min, max);
}

if you are looking for random number generator for normal distribution, you might use a Box-Muller transformation. Check the answer by yoyoyoyosef in Random Gaussian Variable Question. Since you want integer, you have to cast double value to integer at the end.

Random rand = new Random(); //reuse this if you are generating many
double u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles
double u2 = 1.0-rand.NextDouble();
double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
         Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)
double randNormal =
         mean + stdDev * randStdNormal; //random normal(mean,stdDev^2)

Random Gaussian Variables

Why do some functions have underscores "__" before and after the function name?

From the Python PEP 8 -- Style Guide for Python Code:

Descriptive: Naming Styles

The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):

  • _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

  • __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below).

  • __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".

What is a "web service" in plain English?

A simple definition would be an HTTP request that acts like a normal method call; i.e., it accepts parameters and returns a structured result, usually XML, that can be deserialized into an object(s).

String comparison using '==' vs. 'strcmp()'

strcmp will return different values based on the environment it is running(Linux/Windows)!

The reason is the that it has a bug as the bug report says https://bugs.php.net/bug.php?id=53999

Please handle with care!!Thank you.

What is the difference between Builder Design pattern and Factory Design pattern?

Both patterns come for the same necessity: Hide from some client code the construction logic of a complex object. But what makes "complex" (or, sometimes, complicate) an object? Mainly, it's due to dependencies, or rather the state of an object composed by more partial states. You can inject dependencies by constructor to set the initial object state, but an object may require a lot of them, some will be in a default initial state (just because we should have learned that set a default dependency to null is not the cleanest way) and some other set to a state driven by some condition. Moreover, there are object properties that are some kind of "oblivious dependencies" but also they can assume optional states.

there are two well known ways to dominate that complexity:

  • Composition/aggregation: Construct an object, construct its dependent objects, then wire together. Here, a builder can make transparent and flexible the process that determines the rules that lead the construction of component.

  • Polymorphism: Construction rules are declared directly into subtype definition, so you have a set of rules for each subtype and some condition decides which one among these set of rules apply to construct the object. A factory fits perfectly in this scenario.

Nothing prevents to mix these two approaches. A family of product could abstract object creation done with a builder, a builder could use factories to determine which component object instantiate.

Convert string to variable name in JavaScript

Javascript has an eval() function for such occasions:

function (varString) {
  var myVar = eval(varString);
  // .....
}

Edit: Sorry, I think I skimmed the question too quickly. This will only get you the variable, to set it you need

function SetTo5(varString) {
  var newValue = 5;
  eval(varString + " = " + newValue);
}

or if using a string:

function SetToString(varString) {
  var newValue = "string";
  eval(varString + " = " + "'" + newValue + "'");
}

But I imagine there is a more appropriate way to accomplish what you're looking for? I don't think eval() is something you really want to use unless there's a great reason for it. eval()

How to implement an android:background that doesn't stretch?

Use draw9patch... included within Android Studio's SDK tools. You can define the stretchable areas of your image. Important parts are constrained and the image doesn't look all warped. A good demo on dra9patch is HERE

Use draw9patch to change your existing splash.png into new_splash.9.png, drag new_splash.9.png into the drawable-hdpi project folder ensure the AndroidManifest and styles.xml are proper as below:

AndroidManifest.xml:

<application
...
        android:theme="@style/splashScreenStyle"
>

styles.xml:

<style name="splashScreenStyle" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowBackground">@drawable/new_splash</item>
</style>

How to add a single item to a Pandas Series

As far as @joaqin's solution is deprecated, because set_value method will be removed in a future pandas release, I would mention the other option to add a single item to pandas series, using .at[] accessor.

>>> import pandas as pd
>>> x = pd.Series()
>>> N = 4
>>> for i in range(N):
...     x.at[i] = i**2

It produces the same output.

>>> print(x)
0    0
1    1
2    4
3    9

How to do a for loop in windows command line?

This may help you find what you're looking for... Batch script loop

My answer is as follows:

@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start

:end
echo var has reached %var%.
pause
exit

The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.

Pass a JavaScript function as parameter

You can also use eval() to do the same thing.

//A function to call
function needToBeCalled(p1, p2)
{
    alert(p1+"="+p2);
}

//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
    eval(aFunction + "("+params+")");
}

//A function Call
callAnotherFunction("needToBeCalled", "10,20");

That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.

Error Code: 2013. Lost connection to MySQL server during query

Go to Workbench Edit ? Preferences ? SQL Editor ? DBMS connections read time out : Up to 3000. The error no longer occurred.

How to get div height to auto-adjust to background size?

just add to div

style="overflow:hidden;"

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

Try this:

$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);

C# Generics and Type Checking

I hope you find this helpful:

  • typeof(IList<T>).IsGenericType == true
  • typeof(IList<T>).GetGenericTypeDefinition() == typeof(IList<>)
  • typeof(IList<int>).GetGenericArguments()[0] == typeof(int)

https://dotnetfiddle.net/5qUZnt

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

much simpler:

$("selector for element").get(0).scrollIntoView();

if more than one item returns in the selector, the get(0) will get only the first item.

How do you force a CIFS connection to unmount

I use lazy unmount: umount -l (that's a lowercase L)

Lazy unmount. Detach the filesystem from the filesystem hierarchy now, and cleanup all references to the filesystem as soon as it is not busy anymore. (Requires kernel 2.4.11 or later.)

Get url without querystring

simple example would be using substring like :

string your_url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path_you_want = your_url .Substring(0, your_url .IndexOf("?"));

How do I sort an observable collection?

Sorting an observable and returning the same object sorted can be done using an extension method. For larger collections watch out for the number of collection changed notifications.

I have updated my code to improve performance (thanks to nawfal) and to handle duplicates which no other answers here do at time of writing. The observable is partitioned into a left sorted half and a right unsorted half, where each time the minimum item (as found in the sorted list) is shifted to the end of the sorted partition from the unsorted. Worst case O(n). Essentially a selection sort (See below for output).

public static void Sort<T>(this ObservableCollection<T> collection)
        where T : IComparable<T>, IEquatable<T>
    {
        List<T> sorted = collection.OrderBy(x => x).ToList();

        int ptr = 0;
        while (ptr < sorted.Count - 1)
        {
            if (!collection[ptr].Equals(sorted[ptr]))
            {
                int idx = search(collection, ptr+1, sorted[ptr]);
                collection.Move(idx, ptr);
            }
            
            ptr++;
        }
    }

    public static int search<T>(ObservableCollection<T> collection, int startIndex, T other)
            {
                for (int i = startIndex; i < collection.Count; i++)
                {
                    if (other.Equals(collection[i]))
                        return i;
                }
    
                return -1; // decide how to handle error case
            }

usage: Sample with an observer (used a Person class to keep it simple)

    public class Person:IComparable<Person>,IEquatable<Person>
            { 
                public string Name { get; set; }
                public int Age { get; set; }
    
                public int CompareTo(Person other)
                {
                    if (this.Age == other.Age) return 0;
                    return this.Age.CompareTo(other.Age);
                }
    
                public override string ToString()
                {
                    return Name + " aged " + Age;
                }
    
                public bool Equals(Person other)
                {
                    if (this.Name.Equals(other.Name) && this.Age.Equals(other.Age)) return true;
                    return false;
                }
            }
    
          static void Main(string[] args)
            {
                Console.WriteLine("adding items...");
                var observable = new ObservableCollection<Person>()
                {
                    new Person {Name = "Katy", Age = 51},
                    new Person {Name = "Jack", Age = 12},
                    new Person {Name = "Bob", Age = 13},
                    new Person {Name = "Alice", Age = 39},
                    new Person {Name = "John", Age = 14},
                    new Person {Name = "Mary", Age = 41},
                    new Person {Name = "Jane", Age = 20},
                    new Person {Name = "Jim", Age = 39},
                    new Person {Name = "Sue", Age = 5},
                    new Person {Name = "Kim", Age = 19}
                };
    
                //what do observers see?
            
    
observable.CollectionChanged += (sender, e) =>
        {
            Console.WriteLine(
                e.OldItems[0] + " move from " + e.OldStartingIndex + " to " + e.NewStartingIndex);
            int i = 0;
            foreach (var person in sender as ObservableCollection<Person>)
            {
                if (i == e.NewStartingIndex)
                {
                    Console.Write("(" + (person as Person).Age + "),");
                }
                else
                {
                    Console.Write((person as Person).Age + ",");
                }
                
                i++;
            }

            Console.WriteLine();
        };

Details of sorting progress showing how the collection is pivoted:

Sue aged 5 move from 8 to 0
(5),51,12,13,39,14,41,20,39,19,
Jack aged 12 move from 2 to 1
5,(12),51,13,39,14,41,20,39,19,
Bob aged 13 move from 3 to 2
5,12,(13),51,39,14,41,20,39,19,
John aged 14 move from 5 to 3
5,12,13,(14),51,39,41,20,39,19,
Kim aged 19 move from 9 to 4
5,12,13,14,(19),51,39,41,20,39,
Jane aged 20 move from 8 to 5
5,12,13,14,19,(20),51,39,41,39,
Alice aged 39 move from 7 to 6
5,12,13,14,19,20,(39),51,41,39,
Jim aged 39 move from 9 to 7
5,12,13,14,19,20,39,(39),51,41,
Mary aged 41 move from 9 to 8
5,12,13,14,19,20,39,39,(41),51,

The Person class implements both IComparable and IEquatable the latter is used to minimise the changes to the collection so as to reduce the number of change notifications raised

  • EDIT Sorts same collection without creating a new copy *

To return an ObservableCollection, call .ToObservableCollection on *sortedOC* using e.g. [this implementation][1].

**** orig answer - this creates a new collection **** You can use linq as the doSort method below illustrates. A quick code snippet: produces

3:xey 6:fty 7:aaa

Alternatively you could use an extension method on the collection itself

var sortedOC = _collection.OrderBy(i => i.Key);

private void doSort()
{
    ObservableCollection<Pair<ushort, string>> _collection = 
        new ObservableCollection<Pair<ushort, string>>();

    _collection.Add(new Pair<ushort,string>(7,"aaa"));
    _collection.Add(new Pair<ushort, string>(3, "xey"));
    _collection.Add(new Pair<ushort, string>(6, "fty"));

    var sortedOC = from item in _collection
                   orderby item.Key
                   select item;

    foreach (var i in sortedOC)
    {
        Debug.WriteLine(i);
    }

}

public class Pair<TKey, TValue>
{
    private TKey _key;

    public TKey Key
    {
        get { return _key; }
        set { _key = value; }
    }
    private TValue _value;

    public TValue Value
    {
        get { return _value; }
        set { _value = value; }
    }
    
    public Pair(TKey key, TValue value)
    {
        _key = key;
        _value = value;

    }

    public override string ToString()
    {
        return this.Key + ":" + this.Value;
    }
}

Html.ActionLink as a button or an image, not a link

Do what Mehrdad says - or use the url helper from an HtmlHelper extension method like Stephen Walther describes here and make your own extension method which can be used to render all of your links.

Then it will be easy to render all links as buttons/anchors or whichever you prefer - and, most importantly, you can change your mind later when you find out that you actually prefer some other way of making your links.

Angular 6: How to set response type as text while making http call

To get rid of error:

Type '"text"' is not assignable to type '"json"'.

Use

responseType: 'text' as 'json'

import { HttpClient, HttpHeaders } from '@angular/common/http';
.....
 return this.http
        .post<string>(
            this.baseUrl + '/Tickets/getTicket',
            JSON.stringify(value),
        { headers, responseType: 'text' as 'json' }
        )
        .map(res => {
            return res;
        })
        .catch(this.handleError);

Asserting successive calls to a mock method

You can use the Mock.call_args_list attribute to compare parameters to previous method calls. That in conjunction with Mock.call_count attribute should give you full control.

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

PHP Fatal error: Using $this when not in object context

If you are invoking foobarfunc with resolution scope operator (::), then you are calling it statically, e.g. on the class level instead of the instance level, thus you are using $this when not in object context. $this does not exist in class context.

If you enable E_STRICT, PHP will raise a Notice about this:

Strict Standards: 
Non-static method foobar::foobarfunc() should not be called statically

Do this instead

$fb = new foobar;
echo $fb->foobarfunc();

On a sidenote, I suggest not to use global inside your classes. If you need something from outside inside your class, pass it through the constructor. This is called Dependency Injection and it will make your code much more maintainable and less dependant on outside things.

Effect of NOLOCK hint in SELECT statements

It will be faster because it doesnt have to wait for locks

jQuery .ready in a dynamically inserted iframe

I'm loading the PDF with jQuery ajax into browser cache. Then I create embedded element with data already in browser cache. I guess it will work with iframe too.


var url = "http://example.com/my.pdf";
// show spinner
$.mobile.showPageLoadingMsg('b', note, false);
$.ajax({
    url: url,
    cache: true,
    mimeType: 'application/pdf',
    success: function () {
        // display cached data
        $(scroller).append('<embed type="application/pdf" src="' + url + '" />');
        // hide spinner
        $.mobile.hidePageLoadingMsg();
    }
});

You have to set your http headers correctly as well.


HttpContext.Response.Expires = 1;
HttpContext.Response.Cache.SetNoServerCaching();
HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);
HttpContext.Response.CacheControl = "Private";

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

How to use jQuery in chrome extension?

Its very easy just do the following:

add the following line in your manifest.json

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",

Now you are free to load jQuery directly from url

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

Source: google doc

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

What version of JBoss I am running?

In your JBoss lib Directory:

  • Open the file jboss-system.jar by example
  • Extract the file MANIFEST.MF from the META-INF directory
  • Open MANIFEST.MF with a text editor and then look at the property Specification-Version and Implementation-Version

MySQL - Replace Character in Columns

maybe I'd go by this.

 SQL = SELECT REPLACE(myColumn, '""', '\'') FROM myTable

I used singlequotes because that's the one that registers string expressions in MySQL, or so I believe.

Hope that helps.

Strict Standards: Only variables should be assigned by reference PHP 5.4

You should remove the & (ampersand) symbol, so that line 4 will look like this:

$conn = ADONewConnection($config['db_type']);

This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

You could compile and link in one command:

gcc file1.c file2.c -o myprogram

And run with:

./myprogram

But to answer the question as asked, simply pass the object files to gcc:

gcc file1.o file2.o -o myprogram

Change EditText hint color when using TextInputLayout

I'm not sure what causes your problem put this code works perfectly for me. I think it has something to do with using the correct xml namespace (xmlns). I'm not sure if using android.support.design without xml namespace attribute is supported. Or it has something to do with the textColorHint attribute you are using on the EditText itself.

Layout:

<android.support.design.widget.TextInputLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    app:hintTextAppearance="@style/GreenTextInputLayout">

    <android.support.v7.widget.AppCompatEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="test"
        android:inputType="text" />
</android.support.design.widget.TextInputLayout>

Style:

<style name="GreenTextInputLayout" parent="@android:style/TextAppearance">
    <item name="android:textColor">#00FF00</item>
</style>

What are the file limits in Git (number and size)?

There is no real limit -- everything is named with a 160-bit name. The size of the file must be representable in a 64 bit number so no real limit there either.

There is a practical limit, though. I have a repository that's ~8GB with >880,000 files and git gc takes a while. The working tree is rather large so operations that inspect the entire working directory take quite a while. This repo is only used for data storage, though, so it's just a bunch of automated tools that handle it. Pulling changes from the repo is much, much faster than rsyncing the same data.

%find . -type f | wc -l
791887
%time git add .
git add .  6.48s user 13.53s system 55% cpu 36.121 total
%time git status
# On branch master
nothing to commit (working directory clean)
git status  0.00s user 0.01s system 0% cpu 47.169 total
%du -sh .
29G     .
%cd .git
%du -sh .
7.9G    .

Map a 2D array onto a 1D array

As other have said C maps in row order

   #include <stdio.h>

   int main(int argc, char **argv) {
   int i, j, k;
   int arr[5][3];
   int *arr2 = (int*)arr;

       for (k=0; k<15; k++) {
          arr2[k] = k;
          printf("arr[%d] = %2d\n", k, arr2[k]);
       }

       for (i=0; i<5; i++) {
         for (j=0; j< 3; j++) {
            printf("arr2[%d][%d] = %2d\n", i, j ,arr[i][j]);
         }
       } 
    } 

Output:

arr[0] =  0
arr[1] =  1
arr[2] =  2
arr[3] =  3
arr[4] =  4
arr[5] =  5
arr[6] =  6
arr[7] =  7
arr[8] =  8
arr[9] =  9
arr[10] = 10
arr[11] = 11
arr[12] = 12
arr[13] = 13
arr[14] = 14
arr2[0][0] =  0
arr2[0][1] =  1
arr2[0][2] =  2
arr2[1][0] =  3
arr2[1][1] =  4
arr2[1][2] =  5
arr2[2][0] =  6
arr2[2][1] =  7
arr2[2][2] =  8
arr2[3][0] =  9
arr2[3][1] = 10
arr2[3][2] = 11
arr2[4][0] = 12
arr2[4][1] = 13
arr2[4][2] = 14

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

How to use a table type in a SELECT FROM statement?

Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:

CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);


CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;

In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.