Programs & Examples On #Iphone sdk documentation

Use this tag for iOS SDK documentation related questions.

Xcode Project vs. Xcode Workspace - Differences

In brief

  • Xcode 3 introduced subproject, which is parent-child relationship, meaning that parent can reference its child target, but no vice versa
  • Xcode 4 introduced workspace, which is sibling relationship, meaning that any project can reference projects in the same workspace

How do I get an OAuth 2.0 authentication token in C#

https://github.com/IdentityModel/IdentityModel adds extensions to HttpClient to acquire tokens using different flows and the documentation is great too. It's very handy because you don't have to think how to implement it yourself. I'm not aware if any official MS implementation exists.

Bootstrap modal in React.js

You can use React-Bootstrap (https://react-bootstrap.github.io/components/modal). There is an example for modals at that link. Once you have loaded react-bootstrap, the modal component can be used as a react component:

var Modal = ReactBootstrap.Modal;

can then be used as a react component as <Modal/>.

For Bootstrap 4, there is react-strap (https://reactstrap.github.io). React-Bootstrap only supports Bootstrap 3.

How can I temporarily disable a foreign key constraint in MySQL?

In phpMyAdmin you can select multiple rows and can then click the delete action. You'll enter a screen which lists the delete queries. It looks like this:

enter image description here

Please uncheck the "Enable foreign key checks" checkbox, and click on Yes to execute them.

This will enable you to delete rows even if there is an ON DELETE restriction constraint.

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:

npx mocha <args>

Note: the optional args are forwarded to the command being executed (mocha in this case)

this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).

Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.

You can read more on npx here


Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...

you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:

node node_modules/.bin/mocha

npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:

"scripts": {
  "test": "mocha"
}

and invoke it with

npm test

Vendor code 17002 to connect to SQLDeveloper

Listed are the steps that could rectify the error:

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

404 Not Found The requested URL was not found on this server

In Ubuntu I did not found httpd.conf, It may not exit longer now. Edit in apache2.conf file working for me.

cd /etc/apache2
sudo gedit apache2.conf

Here in apache2.conf change

<Directory /var/www/>
     Options Indexes FollowSymLinks
     AllowOverride None
     Require all granted
</Directory>

to

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>  

How can my iphone app detect its own version number?

You can use the infoDictionary which gets the version details from info.plist of you app. This code works for swift 3. Just call this method and display the version in any preferred UI element.

Swift-3  

func getVersion() -> String {
    let dictionary = Bundle.main.infoDictionary!
    let version = dictionary["CFBundleShortVersionString"] as! String
    let build = dictionary["CFBundleVersion"] as! String
    return "v\(version).\(build)"
}

Set a cookie to never expire

If you want to persist data on the client machine permanently -or at least until browser cache is emptied completely, use Javascript local storage:

https://developer.mozilla.org/en-US/docs/DOM/Storage#localStorage

Do not use session storage, as it will be cleared just like a cookie with a maximum age of Zero.

Checkbox for nullable boolean

This is an old question, and the existing answers describe most of the alternatives. But there's one simple option, if you have bool? in your viewmodel, and you don't care about null in your UI:

@Html.CheckBoxFor(m => m.boolValue ?? false);

Reload the page after ajax success

use this Reload page

success: function(data){
   if(data.success == true){ // if true (1)
      setTimeout(function(){// wait for 5 secs(2)
           location.reload(); // then reload the page.(3)
      }, 5000); 
   }
}

failed to find target with hash string 'android-22'

Open project.properties file and change the line with target=android-22 to the desired value.
For example:

target=android-19

How to delete a module in Android Studio

  1. edit the project's settings.gradle file: delete the module name (, ':xxxxx') where xxxxx is the module name to be deleted

  2. using the file explorer delete the module folder

by the way, the current version of the Android Studio (v3.1.2) throws an exception and exits the removing with an error while I'm removing the module through Module Settings => selected module => - (minus)

Best Regards, thanks)

Is there a MySQL option/feature to track history of changes to records?

Why not simply use bin log files? If the replication is set on the Mysql server, and binlog file format is set to ROW, then all the changes could be captured.

A good python library called noplay can be used. More info here.

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

Laravel's Autoload is a bit different:

1) It will in fact use Composer for some stuff

2) It will call Composer with the optimize flag

3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php

4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I faced this issue:

(node:1131004) UnhandledPromiseRejectionWarning: Unhandled promise rejection (re jection id: 1): TypeError: res.json is not a function (node:1131004) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.j s process with a non-zero exit code.

It was my mistake, I was replacing res object in then(function(res), so changed res to result and now it is working.

Wrong

module.exports.update = function(req, res){
        return Services.User.update(req.body)
                .then(function(res){//issue was here, res overwrite
                    return res.json(res);
                }, function(error){
                    return res.json({error:error.message});
                }).catch(function () {
                   console.log("Promise Rejected");
              });

Correction

module.exports.update = function(req, res){
        return Services.User.update(req.body)
                .then(function(result){//res replaced with result
                    return res.json(result);
                }, function(error){
                    return res.json({error:error.message});
                }).catch(function () {
                   console.log("Promise Rejected");
              });

Service code:

function update(data){
   var id = new require('mongodb').ObjectID(data._id);
        userData = {
                    name:data.name,
                    email:data.email,
                    phone: data.phone
                };
 return collection.findAndModify(
          {_id:id}, // query
          [['_id','asc']],  // sort order
          {$set: userData}, // replacement
          { "new": true }
          ).then(function(doc) {
                if(!doc)
                    throw new Error('Record not updated.');
                return doc.value;   
          });
    }

module.exports = {
        update:update
}

Trying to use fetch and pass in mode: no-cors

mode: 'no-cors' won’t magically make things work. In fact it makes things worse, because one effect it has is to tell browsers, “Block my frontend JavaScript code from looking at contents of the response body and headers under all circumstances.” Of course you almost never want that.

What happens with cross-origin requests from frontend JavaScript is that browsers by default block frontend code from accessing resources cross-origin. If Access-Control-Allow-Origin is in a response, then browsers will relax that blocking and allow your code to access the response.

But if a site sends no Access-Control-Allow-Origin in its responses, your frontend code can’t directly access responses from that site. In particular, you can’t fix it by specifying mode: 'no-cors' (in fact that’ll ensure your frontend code can’t access the response contents).

However, one thing that will work: if you send your request through a CORS proxy.

You can also easily deploy your own proxy to Heroku in literally just 2-3 minutes, with 5 commands:

git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master

After running those commands, you’ll end up with your own CORS Anywhere server running at, for example, https://cryptic-headland-94862.herokuapp.com/.

Prefix your request URL with your proxy URL; for example:

https://cryptic-headland-94862.herokuapp.com/https://example.com

Adding the proxy URL as a prefix causes the request to get made through your proxy, which then:

  1. Forwards the request to https://example.com.
  2. Receives the response from https://example.com.
  3. Adds the Access-Control-Allow-Origin header to the response.
  4. Passes that response, with that added header, back to the requesting frontend code.

The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.

This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS request, because in that case, the proxy also sends back the Access-Control-Allow-Headers and Access-Control-Allow-Methods headers needed to make the preflight successful.


I can hit this endpoint, http://catfacts-api.appspot.com/api/facts?number=99 via Postman

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains why it is that even though you can access the response with Postman, browsers won’t let you access the response cross-origin from frontend JavaScript code running in a web app unless the response includes an Access-Control-Allow-Origin response header.

http://catfacts-api.appspot.com/api/facts?number=99 has no Access-Control-Allow-Origin response header, so there’s no way your frontend code can access the response cross-origin.

Your browser can get the response fine and you can see it in Postman and even in browser devtools—but that doesn’t mean browsers will expose it to your code. They won’t, because it has no Access-Control-Allow-Origin response header. So you must instead use a proxy to get it.

The proxy makes the request to that site, gets the response, adds the Access-Control-Allow-Origin response header and any other CORS headers needed, then passes that back to your requesting code. And that response with the Access-Control-Allow-Origin header added is what the browser sees, so the browser lets your frontend code actually access the response.


So I am trying to pass in an object, to my Fetch which will disable CORS

You don’t want to do that. To be clear, when you say you want to “disable CORS” it seems you actually mean you want to disable the same-origin policy. CORS itself is actually a way to do that — CORS is a way to loosen the same-origin policy, not a way to restrict it.

But anyway, it’s true you can — in just your local environment — do things like give your browser runtime flags to disable security and run insecurely, or you can install a browser extension locally to get around the same-origin policy, but all that does is change the situation just for you locally.

No matter what you change locally, anybody else trying to use your app is still going to run into the same-origin policy, and there’s no way you can disable that for other users of your app.

You most likely never want to use mode: 'no-cors' in practice except in a few limited cases, and even then only if you know exactly what you’re doing and what the effects are. That’s because what setting mode: 'no-cors' actually says to the browser is, “Block my frontend JavaScript code from looking into the contents of the response body and headers under all circumstances.” In most cases that’s obviously really not what you want.


As far as the cases when you would want to consider using mode: 'no-cors', see the answer at What limitations apply to opaque responses? for the details. The gist of it is that the cases are:

  • In the limited case when you’re using JavaScript to put content from another origin into a <script>, <link rel=stylesheet>, <img>, <video>, <audio>, <object>, <embed>, or <iframe> element (which works because embedding of resources cross-origin is allowed for those) — but for some reason you don’t want to or can’t do that just by having the markup of the document use the resource URL as the href or src attribute for the element.

  • When the only thing you want to do with a resource is to cache it. As alluded to in the answer What limitations apply to opaque responses?, in practice the scenario that applies to is when you’re using Service Workers, in which case the API that’s relevant is the Cache Storage API.

But even in those limited cases, there are some important gotchas to be aware of; see the answer at What limitations apply to opaque responses? for the details.


I have also tried to pass in the object { mode: 'opaque'}

There is no mode: 'opaque' request mode — opaque is instead just a property of the response, and browsers set that opaque property on responses from requests sent with the no-cors mode.

But incidentally the word opaque is a pretty explicit signal about the nature of the response you end up with: “opaque” means you can’t see it.

How to run multiple DOS commands in parallel?

You can execute commands in parallel with start like this:

start "" ping myserver
start "" nslookup myserver
start "" morecommands

They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.

Hope this helps!

Spark - load CSV file as DataFrame?

Default file format is Parquet with spark.read.. and file reading csv that why you are getting the exception. Specify csv format with api you are trying to use

What is the purpose of a question mark after a type (for example: int? myVariable)?

To add on to the answers above, here is a code sample

struct Test
{
    int something;
}
struct NullableTest
{
    int something;
}
class Example
{
    public void Demo()
    {
        Test t = new Test();
        t = null;

        NullableTest? t2 = new NullableTest();
        t2 = null;
    }
}

This would give a compilation error:

Error 12 Cannot convert null to 'Test' because it is a non-nullable value type

Notice that there is no compilation error for NullableTest. (note the ? in the declaration of t2)

How to show full height background image?

You can do it with the code you have, you just need to ensure that html and body are set to 100% height.

Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/

html, body {
    height:100%;
} 

body {
    background-color: white;
    background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: left top;
}

'uint32_t' identifier not found error

This type is defined in the C header <stdint.h> which is part of the C++11 standard but not standard in C++03. According to the Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010.

In the meantime, you could probably fake up your own version of the header by adding typedefs that map Microsoft's custom integer types to the types expected by C. For example:

typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
/* ... etc. ... */

Hope this helps!

How to get an Android WakeLock to work?

Add permission in AndroidManifest.xml, as given below

<uses-permission android:name="android.permission.WAKE_LOCK" />

preferably BEFORE your <application> declaration tags but AFTER the <manifest> tags, afterwards, try making your onCreate() method contain only the WakeLock instantiation.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "My Tag");
}

and then in your onResume() method place

@Override
public void onResume() {
   mWakeLock.aquire();
}

and in your onFinish() method place

@Override
public void onFinish() {
   mWakeLock.release();
}

How to set Python's default version to 3.x on OS X?

Well... It's kinda old. But still deserves a good answer.

And the good one is You Don't Wanna Touch The Default Python On Mac.

Install any Python version you need via Homebrew or whatever and use it in virtualenv. Virtualenv is often considered to be something crap-like, but it's still way, wayyyy better than changing python version system-wide (macOS is likely to protect itself from such actions) or user-wide, bash-wide... whatever. Just forget about the default Python. Using playgrounds like venv is what your OS will be most, very most grateful for.

The case is, for example, many modern Linux distributions get rid of Python2 installed out-of-the-box, leaving only Python3 in the system. But everytime you try to install something old with python2 as a dependency... hope you understand what I mean. A good developer doesn't care. Good developers create clean playgrounds with python version they desire.

Can you detect "dragging" in jQuery?

If you're using jQueryUI - there is an onDrag event. If you're not, then attach your listener to mouseup(), not click().

How can I deploy an iPhone application from Xcode to a real iPhone device?

It sounds like the application isn't signed. Download ldid from Cydia and then use it like so: ldid -S /Applications/AccelerometerGraph.app/AccelerometerGraph

Also be sure that the binary is marked as executable: chmod +x /Applications/AccelerometerGraph.app/AccelerometerGraph

Could not load file or assembly for Oracle.DataAccess in .NET

please register your Oracle.DataAccess to GAC

raProvCfg.exe /action:gac /providerpath:C:\oracle\product\11.2.0\x32\ODP.NET\bin\4\Oracle.DataAccess.dll

OraProvCfg.exe /action:gac /providerpath:C:\oracle\product\11.2.0\x64\ODP.NET\bin\4\Oracle.DataAccess.dll

Setting width/height as percentage minus pixels

I use Jquery for this

function setSizes() {
   var containerHeight = $("#listContainer").height();
   $("#myList").height(containerHeight - 18);
}

then I bind the window resize to recalc it whenever the browser window is resized (if container's size changed with window resize)

$(window).resize(function() { setSizes(); });

Extract digits from string - StringUtils Java

Just one line:

int value = Integer.parseInt(string.replaceAll("[^0-9]", ""));

How to assign name for a screen?

I am a beginner to screen but I find it immensely useful while restoring lost connections. Your question has already been answered but this information might serve as an add on - I use putty with putty connection manager and name my screens - "tab1", "tab2", etc. - as for me the overall picture of the 8-10 tabs is more important than each individual tab name. I use the 8th tab for connecting to db, the 7th for viewing logs, etc. So when I want to reattach my screens I have written a simple wrapper which says:

#!/bin/bash
screen -d -r tab$1

where first argument is the tab number.

Push git commits & tags simultaneously

@since Git 2.4

git push --atomic origin <branch name> <tag>

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

Quote:

The "BIGINT(20)" specification isn't a digit limit. It just means that when the data is displayed, if it uses less than 20 digits it will be left-padded with zeros. 2^64 is the hard limit for the BIGINT type, and has 20 digits itself, hence BIGINT(20) just means everything less than 10^20 will be left-padded with spaces on display.

How to convert hex to ASCII characters in the Linux shell?

I used to do this using xxd

echo -n 5a | xxd -r -p

But then I realised that in Debian/Ubuntu, xxd is part of vim-common and hence might not be present in a minimal system. To also avoid perl (imho also not part of a minimal system) I ended up using sed, xargs and printf like this:

echo -n 5a | sed 's/\([0-9A-F]\{2\}\)/\\\\\\x\1/gI' | xargs printf

Mostly I only want to convert a few bytes and it's okay for such tasks. The advantage of this solution over the one of ghostdog74 is, that this can convert hex strings of arbitrary lengths automatically. xargs is used because printf doesnt read from standard input.

UILabel font size?

I have modified the UILabel by following code:

label.font=[label.font fontWithSize:25];

Try this and see whether is it working in your case or not???

Extract a substring according to a pattern

If you are using data.table then tstrsplit() is a natural choice:

tstrsplit(string, ":")[[2]]
[1] "E001" "E002" "E003"

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

This worked for me.

You need to run it twice once for globals followed by locals

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

for name in dir():
    if not name.startswith('_'):
        del locals()[name]

Adding calculated column(s) to a dataframe in pandas

You could have is_hammer in terms of row["Open"] etc. as follows

def is_hammer(rOpen,rLow,rClose,rHigh):
    return lower_wick_at_least_twice_real_body(rOpen,rLow,rClose) \
       and closed_in_top_half_of_range(rHigh,rLow,rClose)

Then you can use map:

df["isHammer"] = map(is_hammer, df["Open"], df["Low"], df["Close"], df["High"])

Java - How do I make a String array with values?

Another way to create an array with String apart from

String[] strings =  { "abc", "def", "hij", "xyz" };

is to use split. I find this more readable if there are lots of Strings.

String[] strings =  "abc,def,hij,xyz".split(",");

or the following is good if you are parsing lines of strings from another source.

String[] strings =  ("abc\n" +
                     "def\n" +
                     "hij\n" +
                     "xyz").split("\n");

HTML button to NOT submit form

return false; at the end of the onclick handler will do the job. However, it's be better to simply add type="button" to the <button> - that way it behaves properly even without any JavaScript.

Simplest way to detect keypresses in javascript

There are a few ways to handle that; Vanilla JavaScript can do it quite nicely:

function code(e) {
    e = e || window.event;
    return(e.keyCode || e.which);
}
window.onload = function(){
    document.onkeypress = function(e){
        var key = code(e);
        // do something with key
    };
};

Or a more structured way of handling it:

(function(d){
    var modern = (d.addEventListener), event = function(obj, evt, fn){
        if(modern) {
            obj.addEventListener(evt, fn, false);
        } else {
            obj.attachEvent("on" + evt, fn);
        }
    }, code = function(e){
        e = e || window.event;
        return(e.keyCode || e.which);
    }, init = function(){
        event(d, "keypress", function(e){
            var key = code(e);
            // do stuff with key here
        });
    };
    if(modern) {
        d.addEventListener("DOMContentLoaded", init, false);
    } else {
        d.attachEvent("onreadystatechange", function(){
            if(d.readyState === "complete") {
                init();
            }
        });
    }
})(document);

How to hide first section header in UITableView (grouped style)

The following worked for me in with iOS 13.6 and Xcode 11.6 with a UITableViewController that was embedded in a UINavigationController:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    nil
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    .zero
}

No other trickery needed. The override keywords aren't needed when not using a UITableViewController (i.e. when just implemented the UITableViewDelegate methods). Of course if the goal was to hide just the first section's header, then this logic could be wrapped in a conditional as such:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0 {
        return nil
    } else {
        // Return some other view...
    }
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == 0 {
        return .zero
    } else {
        // Return some other height...
    }
}

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Lets see, numeric (3,2). That means you have 3 places for data and two of them are to the right of the decimal leaving only one to the left of the decimal. 15 has two places to the left of the decimal. BTW if you might have 100 as a value I'd increase that to numeric (5, 2)

Error in Swift class: Property not initialized at super.init call

swift enforces you to initialise every member var before it is ever/might ever be used. Since it can't be sure what happens when it is supers turn, it errors out: better safe than sorry

Defining TypeScript callback type

If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.

class CallbackTest {
  myCallback: Function;
}   

How to extract file name from path?

I've read through all the answers and I'd like to add one more that I think wins out because of its simplicity. Unlike the accepted answer this does not require recursion. It also does not require referencing a FileSystemObject.

Function FileNameFromPath(strFullPath As String) As String

    FileNameFromPath = Right(strFullPath, Len(strFullPath) - InStrRev(strFullPath, "\"))

End Function

http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/ has this code plus other functions for parsing out the file path, extension and even the filename without the extension.

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

An AnyCPU assembly will JIT to 64-bit code when loaded into a 64-bit process and 32 bit when loaded into a 32-bit process.

By limiting the CPU you would be saying: There is something being used by the assembly (something likely unmanaged) that requires 32 bits or 64 bits.

Java 8 lambdas, Function.identity() or t->t

From the JDK source:

static <T> Function<T, T> identity() {
    return t -> t;
}

So, no, as long as it is syntactically correct.

AngularJS toggle class using ng-class

I made this work in this way:

<button class="btn" ng-click='toggleClass($event)'>button one</button>
<button class="btn" ng-click='toggleClass($event)'>button two</button>

in your controller:

$scope.toggleClass = function (event) {
    $(event.target).toggleClass('active');
}

Get Selected value of a Combobox

If you're dealing with Data Validation lists, you can use the Worksheet_Change event. Right click on the sheet with the data validation and choose View Code. Then type in this:

Private Sub Worksheet_Change(ByVal Target As Range)

    MsgBox Target.Value

End Sub

If you're dealing with ActiveX comboboxes, it's a little more complicated. You need to create a custom class module to hook up the events. First, create a class module named CComboEvent and put this code in it.

Public WithEvents Cbx As MSForms.ComboBox

Private Sub Cbx_Change()

    MsgBox Cbx.Value

End Sub

Next, create another class module named CComboEvents. This will hold all of our CComboEvent instances and keep them in scope. Put this code in CComboEvents.

Private mcolComboEvents As Collection

Private Sub Class_Initialize()
    Set mcolComboEvents = New Collection
End Sub

Private Sub Class_Terminate()
    Set mcolComboEvents = Nothing
End Sub

Public Sub Add(clsComboEvent As CComboEvent)

    mcolComboEvents.Add clsComboEvent, clsComboEvent.Cbx.Name

End Sub

Finally, create a standard module (not a class module). You'll need code to put all of your comboboxes into the class modules. You might put this in an Auto_Open procedure so it happens whenever the workbook is opened, but that's up to you.

You'll need a Public variable to hold an instance of CComboEvents. Making it Public will kepp it, and all of its children, in scope. You need them in scope so that the events are triggered. In the procedure, loop through all of the comboboxes, creating a new CComboEvent instance for each one, and adding that to CComboEvents.

Public gclsComboEvents As CComboEvents

Public Sub AddCombox()

    Dim oleo As OLEObject
    Dim clsComboEvent As CComboEvent

    Set gclsComboEvents = New CComboEvents

    For Each oleo In Sheet1.OLEObjects
        If TypeName(oleo.Object) = "ComboBox" Then
            Set clsComboEvent = New CComboEvent
            Set clsComboEvent.Cbx = oleo.Object
            gclsComboEvents.Add clsComboEvent
        End If
    Next oleo

End Sub

Now, whenever a combobox is changed, the event will fire and, in this example, a message box will show.

You can see an example at https://www.dropbox.com/s/sfj4kyzolfy03qe/ComboboxEvents.xlsm

PHP session lost after redirect

I've been struggling with this for days, checking/trying all the solutions, but my problem was I didn't call session_start(); again after the redirect. I just assumed the session was 'still alive'.

So don't forget that!

Is there an "exists" function for jQuery?

Use the following syntax to check if the element actually exists using jQuery.

let oElement = $(".myElementClass");
if(oElement[0]) {
    // Do some jQuery operation here using oElement
}
else {
    // Unable to fetch the object
}

The cast to value type 'Int32' failed because the materialized value is null

To allow a nullable Amount field, just use the null coalescing operator to convert nulls to 0.

var creditsSum = (from u in context.User
              join ch in context.CreditHistory on u.ID equals ch.UserID                                        
              where u.ID == userID
              select ch.Amount ?? 0).Sum();

Using Eloquent ORM in Laravel to perform search of database using LIKE

If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent ORM:

public  function scopeLike($query, $field, $value){
        return $query->where($field, 'LIKE', "%$value%");
}

So then you can use this method in such way:

User::like('name', 'Tomas')->get();

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

I was facing a similar problem when starting up the application (using Spring Boot) with the database server down.

Hibernate can determine the correct dialect to use automatically, but in order to do this, it needs a live connection to the database.

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

The same error is produced in MariaDB (10.1.36-MariaDB) by using the combination of parenthesis and the COLLATE statement. My SQL was different, the error was the same, I had:

SELECT *
FROM table1
WHERE (field = 'STRING') COLLATE utf8_bin;

Omitting the parenthesis was solving it for me.

SELECT *
FROM table1
WHERE field = 'STRING' COLLATE utf8_bin;

Vertical Menu in Bootstrap

No, not in the current one. But you can take a look at the next version by downloading it from github. It has vertical pills and tabs. Maybe that will help? (be aware, it's under construction tho)

Play audio from a stream using C#

NAudio wraps the WaveOutXXXX API. I haven't looked at the source, but if NAudio exposes the waveOutWrite() function in a way that doesn't automatically stop playback on each call, then you should be able to do what you really want, which is to start playing the audio stream before you've received all the data.

Using the waveOutWrite() function allows you to "read ahead" and dump smaller chunks of audio into the output queue - Windows will automatically play the chunks seamlessly. Your code would have to take the compressed audio stream and convert it to small chunks of WAV audio on the fly; this part would be really difficult - all the libraries and components I've ever seen do MP3-to-WAV conversion an entire file at a time. Probably your only realistic chance is to do this using WMA instead of MP3, because you can write simple C# wrappers around the multimedia SDK.

What does $_ mean in PowerShell?

This is the variable for the current value in the pipe line, which is called $PSItem in Powershell 3 and newer.

1,2,3 | %{ write-host $_ } 

or

1,2,3 | %{ write-host $PSItem } 

For example in the above code the %{} block is called for every value in the array. The $_ or $PSItem variable will contain the current value.

Rails: How do I create a default value for attributes in Rails activerecord's model?

Just strengthening Jim's answer

Using presence one can do

class Task < ActiveRecord::Base
  before_save :default_values
  def default_values
    self.status = status.presence || 'P'
  end
end

Unresolved external symbol in object files

My issue was a sconscript did not have the cpp file defined in it. This can be very confusing because Visual Studio has the cpp file in the project but something else entirely is building.

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

I solved in this way: I logged in with root username

mysql -u root -p -h localhost

I created a new user with

CREATE USER 'francesco'@'localhost' IDENTIFIED BY 'some_pass';

then I created the database

CREATE DATABASE shop;

I granted privileges for new user for this database

GRANT ALL PRIVILEGES ON shop.* TO 'francesco'@'localhost';

Then I logged out root and logged in new user

quit;
mysql -u francesco -p -h localhost

I rebuilt my database using a script

source shop.sql;

And that's it.. Now from php works without problems with the call

 $conn = new mysqli("localhost", "francesco", "some_pass", "shop");

Thanks to all for your time :)

Calculate cosine similarity given 2 sentence strings

A simple pure-Python implementation would be:

import math
import re
from collections import Counter

WORD = re.compile(r"\w+")


def get_cosine(vec1, vec2):
    intersection = set(vec1.keys()) & set(vec2.keys())
    numerator = sum([vec1[x] * vec2[x] for x in intersection])

    sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])
    sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])
    denominator = math.sqrt(sum1) * math.sqrt(sum2)

    if not denominator:
        return 0.0
    else:
        return float(numerator) / denominator


def text_to_vector(text):
    words = WORD.findall(text)
    return Counter(words)


text1 = "This is a foo bar sentence ."
text2 = "This sentence is similar to a foo bar sentence ."

vector1 = text_to_vector(text1)
vector2 = text_to_vector(text2)

cosine = get_cosine(vector1, vector2)

print("Cosine:", cosine)

Prints:

Cosine: 0.861640436855

The cosine formula used here is described here.

This does not include weighting of the words by tf-idf, but in order to use tf-idf, you need to have a reasonably large corpus from which to estimate tfidf weights.

You can also develop it further, by using a more sophisticated way to extract words from a piece of text, stem or lemmatise it, etc.

Why is there no ForEach extension method on IEnumerable?

One workaround is to write .ToList().ForEach(x => ...).

pros

Easy to understand - reader only needs to know what ships with C#, not any additional extension methods.

Syntactic noise is very mild (only adds a little extranious code).

Doesn't usually cost extra memory, since a native .ForEach() would have to realize the whole collection, anyway.

cons

Order of operations isn't ideal. I'd rather realize one element, then act on it, then repeat. This code realizes all elements first, then acts on them each in sequence.

If realizing the list throws an exception, you never get to act on a single element.

If the enumeration is infinite (like the natural numbers), you're out of luck.

Set encoding and fileencoding to utf-8 in Vim

TL;DR

In the first case with set encoding=utf-8, you'll change the output encoding that is shown in the terminal.

In the second case with set fileencoding=utf-8, you'll change the output encoding of the file that is written.

As stated by @Dennis, you can set them both in your ~/.vimrc if you always want to work in utf-8.

More details

From the wiki of VIM about working with unicode

"encoding sets how vim shall represent characters internally. Utf-8 is necessary for most flavors of Unicode."

"fileencoding sets the encoding for a particular file (local to buffer); :setglobal sets the default value. An empty value can also be used: it defaults to same as 'encoding'. Or you may want to set one of the ucs encodings, It might make the same disk file bigger or smaller depending on your particular mix of characters. Also, IIUC, utf-8 is always big-endian (high bit first) while ucs can be big-endian or little-endian, so if you use it, you will probably need to set 'bomb" (see below)."

Laravel 5 - redirect to HTTPS

You can make it works with a Middleware class. Let me give you an idea.

namespace MyApp\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class HttpsProtocol {

    public function handle($request, Closure $next)
    {
            if (!$request->secure() && App::environment() === 'production') {
                return redirect()->secure($request->getRequestUri());
            }

            return $next($request); 
    }
}

Then, apply this middleware to every request adding setting the rule at Kernel.php file, like so:

protected $middleware = [
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',

    // appending custom middleware 
    'MyApp\Http\Middleware\HttpsProtocol'       

];

At sample above, the middleware will redirect every request to https if:

  1. The current request comes with no secure protocol (http)
  2. If your environment is equals to production. So, just adjust the settings according to your preferences.

Cloudflare

I am using this code in production environment with a WildCard SSL and the code works correctly. If I remove && App::environment() === 'production' and test it in localhost, the redirection also works. So, having or not a installed SSL is not the problem. Looks like you need to keep a very hard attention to your Cloudflare layer in order to get redirected to Https protocol.

Edit 23/03/2015

Thanks to @Adam Link's suggestion: it is likely caused by the headers that Cloudflare is passing. CloudFlare likely hits your server via HTTP and passes a X-Forwarded-Proto header that declares it is forwarding a HTTPS request. You need add another line in your Middleware that say...

$request->setTrustedProxies( [ $request->getClientIp() ] ); 

...to trust the headers CloudFlare is sending. This will stop the redirect loop

Edit 27/09/2016 - Laravel v5.3

Just need to add the middleware class into web group in kernel.php file:

protected $middlewareGroups = [
    'web' => [
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,

        // here
        \MyApp\Http\Middleware\HttpsProtocol::class

    ],
];

Remember that web group is applied to every route by default, so you do not need to set web explicitly in routes nor controllers.

Edit 23/08/2018 - Laravel v5.7

  • To redirect a request depending the environment you can use App::environment() === 'production'. For previous version was env('APP_ENV') === 'production'.
  • Using \URL::forceScheme('https'); actually does not redirect. It just builds links with https:// once the website is rendered.

How to error handle 1004 Error with WorksheetFunction.VLookup?

There is a way to skip the errors inside the code and go on with the loop anyway, hope it helps:

Sub new1()

Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
Dim ws As Worksheet: Set ws = Sheets(1)
Dim rngLook As Range: Set rngLook = ws.Range("A:M")

currName = "Example"
On Error Resume Next ''if error, the code will go on anyway
cellNum = wsFunc.VLookup(currName, rngLook, 13, 0)

If Err.Number <> 0 Then
''error appeared
    MsgBox "currName not found" ''optional, no need to do anything
End If

On Error GoTo 0 ''no error, coming back to default conditions

End Sub

How to execute Python code from within Visual Studio Code

Super simple:

Press the F5 key and the code will run.

If a breakpoint is set, pressing F5 will stop at the breakpoint and run the code in debug mode.

Other Method - To add Shortcut

Note: You must have Python Extension By Microsoft installed in Visual Studio Code, and the Python interpreter selected in the lower-left corner.

Go to File ? Preferences ? Keyboard Shortcuts (alternatively, you can press Ctrl + K + S) In the search box, enter python.execInTerminal Double click that result (alternatively, you can click the plus icon) Press Ctrl + Alt + B to register this as the keybinding (alternatively, you can enter your own keybinding)

Now you can close the Keyboard Shortcuts tab Go to the Python file you want to run and press Ctrl + Alt + B (alternatively, you can press the keybinding you set) to run it. The output will be shown in the bottom terminal tab.

How to delete a record in Django models?

If you want to delete one item

wishlist = Wishlist.objects.get(id = 20)
wishlist.delete()

If you want to delete all items in Wishlist for example

Wishlist.objects.all().delete()

Default settings Raspberry Pi /etc/network/interfaces

For my Raspberry Pi 3B model it was

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

Java String new line

Example

System.out.printf("I %n am %n a %n boy");

Output

I 
 am 
 a 
 boy

Explanation

It's better to use %n as an OS independent new-line character instead of \n and it's easier than using System.lineSeparator()

Why to use %n, because on each OS, new line refers to a different set of character(s);

Unix and modern Mac's   :   LF     (\n)
Windows                 :   CR LF  (\r\n)
Older Macintosh Systems :   CR     (\r)

LF is the acronym of Line Feed and CR is the acronym of Carriage Return. The escape characters are written inside the parenthesis. So on each OS, new line stands for something specific to the system. %n is OS agnostic, it is portable. It stands for \n on Unix systems or \r\n on Windows systems and so on. Thus, Do not use \n, instead use %n.

Quickly create a large file on a Linux system

Examples where seek is the size of the file you want in bytes

#kilobytes
dd if=/dev/zero of=filename bs=1 count=0 seek=200K

#megabytes
dd if=/dev/zero of=filename bs=1 count=0 seek=200M

#gigabytes
dd if=/dev/zero of=filename bs=1 count=0 seek=200G

#terabytes
dd if=/dev/zero of=filename bs=1 count=0 seek=200T


From the dd manpage:

BLOCKS and BYTES may be followed by the following multiplicative suffixes: c=1, w=2, b=512, kB=1000, K=1024, MB=1000*1000, M=1024*1024, GB =1000*1000*1000, G=1024*1024*1024, and so on for T, P, E, Z, Y.

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

If you set CURLOPT_RETURNTRANSFER to true or 1 then the return value from curl_exec will be the actual result from the successful operation. In other words it will not return TRUE on success. Although it will return FALSE on failure.

As described in the Return Values section of curl-exec PHP manual page: http://php.net/manual/function.curl-exec.php

You should enable the CURLOPT_FOLLOWLOCATION option for redirects but this would be a problem if your server is in safe_mode and/or open_basedir is in effect which can cause issues with curl as well.

How to copy folders to docker image from Dockerfile?

As mentioned in your ticket:

You have COPY files/* /test/ which expands to COPY files/dir files/file1 files/file2 files/file /test/.
If you split this up into individual COPY commands (e.g. COPY files/dir /test/) you'll see that (for better or worse) COPY will copy the contents of each arg dir into the destination directory. Not the arg dir itself, but the contents.

I'm not thrilled with that fact that COPY doesn't preserve the top-level dir but its been that way for a while now.

so in the name of preserving a backward compatibility, it is not possible to COPY/ADD a directory structure.

The only workaround would be a series of RUN mkdir -p /x/y/z to build the target directory structure, followed by a series of docker ADD (one for each folder to fill).
(ADD, not COPY, as per comments)

How to pass variable as a parameter in Execute SQL Task SSIS?

In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:

enter image description here

Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:

enter image description here

Now when this task runs it will pass the SSIS variables to the stored proc.

Leader Not Available Kafka in Console Producer

If you are running kafka on local machine, try updating $KAFKA_DIR/config/server.properties with below line: listeners=PLAINTEXT://localhost:9092 and then restarting kafka.

How to detect a loop in a linked list?

Detecting a loop in a linked list can be done in one of the simplest ways, which results in O(N) complexity using hashmap or O(NlogN) using a sort based approach.

As you traverse the list starting from head, create a sorted list of addresses. When you insert a new address, check if the address is already there in the sorted list, which takes O(logN) complexity.

Convert IEnumerable to DataTable

Firstly you need to add a where T:class constraint - you can't call GetValue on value types unless they're passed by ref.

Secondly GetValue is very slow and gets called a lot.

To get round this we can create a delegate and call that instead:

MethodInfo method = property.GetGetMethod(true);
Delegate.CreateDelegate(typeof(Func<TClass, TProperty>), method );

The problem is that we don't know TProperty, but as usual on here Jon Skeet has the answer - we can use reflection to retrieve the getter delegate, but once we have it we don't need to reflect again:

public class ReflectionUtility
{
    internal static Func<object, object> GetGetter(PropertyInfo property)
    {
        // get the get method for the property
        MethodInfo method = property.GetGetMethod(true);

        // get the generic get-method generator (ReflectionUtility.GetSetterHelper<TTarget, TValue>)
        MethodInfo genericHelper = typeof(ReflectionUtility).GetMethod(
            "GetGetterHelper",
            BindingFlags.Static | BindingFlags.NonPublic);

        // reflection call to the generic get-method generator to generate the type arguments
        MethodInfo constructedHelper = genericHelper.MakeGenericMethod(
            method.DeclaringType,
            method.ReturnType);

        // now call it. The null argument is because it's a static method.
        object ret = constructedHelper.Invoke(null, new object[] { method });

        // cast the result to the action delegate and return it
        return (Func<object, object>) ret;
    }

    static Func<object, object> GetGetterHelper<TTarget, TResult>(MethodInfo method)
        where TTarget : class // target must be a class as property sets on structs need a ref param
    {
        // Convert the slow MethodInfo into a fast, strongly typed, open delegate
        Func<TTarget, TResult> func = (Func<TTarget, TResult>) Delegate.CreateDelegate(typeof(Func<TTarget, TResult>), method);

        // Now create a more weakly typed delegate which will call the strongly typed one
        Func<object, object> ret = (object target) => (TResult) func((TTarget) target);
        return ret;
    }
}

So now your method becomes:

public static DataTable ToDataTable<T>(this IEnumerable<T> items) 
    where T: class
{  
    // ... create table the same way

    var propGetters = new List<Func<T, object>>();
foreach (var prop in props)
    {
        Func<T, object> func = (Func<T, object>) ReflectionUtility.GetGetter(prop);
        propGetters.Add(func);
    }

    // Add the property values per T as rows to the datatable
    foreach (var item in items) 
    {  
        var values = new object[props.Length];  
        for (var i = 0; i < props.Length; i++) 
        {
            //values[i] = props[i].GetValue(item, null);   
            values[i] = propGetters[i](item);
        }    

        table.Rows.Add(values);  
    } 

    return table; 
} 

You could further optimise it by storing the getters for each type in a static dictionary, then you will only have the reflection overhead once for each type.

Redis: Show database size/size for keys

How about redis-cli get KEYNAME | wc -c

How to pass data from child component to its parent in ReactJS?

from child component to parent component as below

parent component

class Parent extends React.Component {
   state = { message: "parent message" }
   callbackFunction = (childData) => {
       this.setState({message: childData})
   },
   render() {
        return (
            <div>
                 <Child parentCallback = {this.callbackFunction}/>
                 <p> {this.state.message} </p>
            </div>
        );
   }
}

child component

class Child extends React.Component{
    sendBackData = () => {
         this.props.parentCallback("child message");
    },
    render() { 
       <button onClick={sendBackData}>click me to send back</button>
    }
};

I hope this work

how to fetch array keys with jQuery?

I use something like this function I created...

Object.getKeys = function(obj, add) {
    if(obj === undefined || obj === null) {
        return undefined;
    }
    var keys = [];
    if(add !== undefined) {
        keys = jQuery.merge(keys, add);
    }
    for(key in obj) {
        if(obj.hasOwnProperty(key)) {
                keys.push(key);
        }
    }
    return keys;
};

I think you could set obj to self or something better in the first test. It seems sometimes I'm checking if it's empty too so I did it that way. Also I don't think {} is Object.* or at least there's a problem finding the function getKeys on the Object that way. Maybe you're suppose to put prototype first, but that seems to cause a conflict with GreenSock etc.

Redirecting from HTTP to HTTPS with PHP

Redirecting from HTTP to HTTPS with PHP on IIS

I was having trouble getting redirection to HTTPS to work on a Windows server which runs version 6 of MS Internet Information Services (IIS). I’m more used to working with Apache on a Linux host so I turned to the Internet for help and this was the highest ranking Stack Overflow question when I searched for “php redirect http to https”. However, the selected answer didn’t work for me.

After some trial and error, I discovered that with IIS, $_SERVER['HTTPS'] is set to off for non-TLS connections. I thought the following code should help any other IIS users who come to this question via search engine.

<?php
if (! isset($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off' ) {
    $redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header("Location: $redirect_url");
    exit();
}
?>

Edit: From another Stack Overflow answer, a simpler solution is to check if($_SERVER["HTTPS"] != "on").

XPath selecting a node with some attribute value equals to some other node's attribute value

This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

To get age //child[@id='#grand']/@age

Hope this helps

How to escape a single quote inside awk

awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'

Get the Id of current table row with Jquery

$('input[type=button]' ).click(function() {
   var bid = jQuery(this).attr('id'); // button ID 
   var trid = $(this).parents('tr:first').attr('id'); // table row ID 
 });

Storing query results into a variable and modifying it inside a Stored Procedure

Yup, this is possible of course. Here are several examples.

-- one way to do this
DECLARE @Cnt int

SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn

-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)

-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double

SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable

Newline in string attribute

May be you can use the attribute xml:space="preserve" for preserving whitespace in the source XAML

<TextBlock xml:space="preserve">
Stuff on line 1
Stuff on line 2
</TextBlock>

Adding an arbitrary line to a matplotlib plot in ipython notebook

It's not too late for the newcomers.

plt.axvline(x, color='r')

It takes the range of y as well, using ymin and ymax.

Trying to SSH into an Amazon Ec2 instance - permission error

Alternative log-in using PuTTY. Its good but needs a few steps.

  1. Get your .pem that was generated when you first made the EC2 instance.
  2. Convert the .pem file .ppk using PuttyGen since PuTTY does not read .pem.
  3. Open PuTTY and enter your Host Name which is your instance username + Public DNS (Ex. [email protected]). Not your AWS account username.
  4. Then navigate to Connection > SSH > Auth. Then add your .ppk file. Click on Browse where it says "Private key file for authentication".
  5. Click Open and you should be able to immediately establish connection.

Im using PuTTY 0.66 in Windows.

How to show Snackbar when Activity starts?

Just point to any View inside the Activity's XML. You can give an id to the root viewGroup, for example, and use:

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);    
   setContentView(R.layout.main_activity);
   View parentLayout = findViewById(android.R.id.content);
   Snackbar.make(parentLayout, "This is main activity", Snackbar.LENGTH_LONG) 
        .setAction("CLOSE", new View.OnClickListener() {
            @Override 
            public void onClick(View view) {

            } 
        }) 
        .setActionTextColor(getResources().getColor(android.R.color.holo_red_light ))
        .show(); 
   //Other stuff in OnCreate();
}

How do I set the timeout for a JAX-WS webservice client?

Not sure if this will help in your context...

Can the soap object be cast as a BindingProvider ?

MyWebServiceSoap soap;
MyWebService service = new MyWebService("http://www.google.com");
soap = service.getMyWebServiceSoap();
// set timeouts here
((BindingProvider)soap).getRequestContext().put("com.sun.xml.internal.ws.request.timeout", 10000);
    soap.sendRequestToMyWebService();

On the other hand if you are wanting to set the timeout on the initialization of the MyWebService object then this will not help.

This worked for me when wanting to timeout the individual WebService calls.

Unit testing click event in Angular

I'm using Angular 6. I followed Mav55's answer and it worked. However I wanted to make sure if fixture.detectChanges(); was really necessary so I removed it and it still worked. Then I removed tick(); to see if it worked and it did. Finally I removed the test from the fakeAsync() wrap, and surprise, it worked.

So I ended up with this:

it('should call onClick method', () => {
  const onClickMock = spyOn(component, 'onClick');
  fixture.debugElement.query(By.css('button')).triggerEventHandler('click', null);
  expect(onClickMock).toHaveBeenCalled();
});

And it worked just fine.

Download a file from NodeJS Server using Express

Here's how I do it:

  1. create file
  2. send file to client
  3. remove file

Code:

let fs = require('fs');
let path = require('path');

let myController = (req, res) => {
  let filename = 'myFile.ext';
  let absPath = path.join(__dirname, '/my_files/', filename);
  let relPath = path.join('./my_files', filename); // path relative to server root

  fs.writeFile(relPath, 'File content', (err) => {
    if (err) {
      console.log(err);
    }
    res.download(absPath, (err) => {
      if (err) {
        console.log(err);
      }
      fs.unlink(relPath, (err) => {
        if (err) {
          console.log(err);
        }
        console.log('FILE [' + filename + '] REMOVED!');
      });
    });
  });
};

What is the difference between rb and r+b modes in file objects

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Source: Reading and Writing Files

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

Understanding Chrome network log "Stalled" state

My case is the page is sending multiple requests with different parameters when it was open. So most are being "stalled". Following requests immediately sent gets "stalled". Avoiding unnecessary requests would be better (to be lazy...).

Reimport a module in python while interactive

Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

However, if using the __all__ variable to define the public API, it is possible to automatically reload all publicly available modules:

# Python >= 3.5
import importlib
import types


def walk_reload(module: types.ModuleType) -> None:
    if hasattr(module, "__all__"):
        for submodule_name in module.__all__:
            walk_reload(getattr(module, submodule_name))
    importlib.reload(module)


walk_reload(my_module)

The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__ variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.

How do I run a Java program from the command line on Windows?

As of Java 9, the JDK includes jshell, a Java REPL.

Assuming the JDK 9+ bin directory is correctly added to your path, you will be able to simply:

  1. Run jshell File.javaFile.java being your file of course.
  2. A prompt will open, allowing you to call the main method: jshell> File.main(null).
  3. To close the prompt and end the JVM session, use /exit

Full documentation for JShell can be found here.

How do I view / replay a chrome network debugger har file saved with content?

The Most Reliable way to replay har file is using a free tool like Fiddler, the tool is always free and can be downloaded quickly. The sites for the opening har file are all buggy and cannot open large files. Fiddler is available for all platforms.

https://www.telerik.com/download/fiddler

Go to File Menu -> Import Sessions...

Open Fiddler

Select the "HTTPArchive" Option

Select the Http Archieve option

Browse to your HAR file

enter image description here

The HAR file will open and replay on the fiddler window.

How do I determine whether an array contains a particular value in Java?

Check this

String[] VALUES = new String[] {"AB","BC","CD","AE"};
String s;

for(int i=0; i< VALUES.length ; i++)
{
    if ( VALUES[i].equals(s) )
    { 
        // do your stuff
    } 
    else{    
        //do your stuff
    }
}

Jersey Exception : SEVERE: A message body reader for Java class

Try adding:

<dependency>
    <groupId>com.owlike</groupId>
    <artifactId>genson</artifactId>
    <version>1.4</version>
</dependency>

Also this problem may occur if you're using HTTP GET with message body so in this case adding jersey-json lib, @XmlRootElement or modifying web.xml won't help. You should use URL QueryParam or HTTP POST.

Stored procedure - return identity as output parameter or scalar

SELECT IDENT_CURRENT('databasename.dbo.tablename') AS your identity column;

Preview an image before it is uploaded

for my app, with encryped GET url parameters, only this worked. I always got a TypeError: $(...) is null. Taken from https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

_x000D_
_x000D_
function previewFile() {_x000D_
  var preview = document.querySelector('img');_x000D_
  var file    = document.querySelector('input[type=file]').files[0];_x000D_
  var reader  = new FileReader();_x000D_
_x000D_
  reader.addEventListener("load", function () {_x000D_
    preview.src = reader.result;_x000D_
  }, false);_x000D_
_x000D_
  if (file) {_x000D_
    reader.readAsDataURL(file);_x000D_
  }_x000D_
}
_x000D_
<input type="file" onchange="previewFile()"><br>_x000D_
<img src="" height="200" alt="Image preview...">
_x000D_
_x000D_
_x000D_

WPF loading spinner

Here's an example of an all-xaml solution. It binds to an "IsWorking" boolean in the viewmodel to show the control and start the animation.

<UserControl x:Class="MainApp.Views.SpinnerView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">

    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>
    </UserControl.Resources>

    <StackPanel Orientation="Horizontal" Margin="5"
                     Visibility="{Binding IsWorking, Converter={StaticResource BoolToVisConverter}}">
        <Label>Wait...</Label>
        <Ellipse x:Name="spinnerEllipse" 
                     Width="20" Height="20">
            <Ellipse.Fill>
                <LinearGradientBrush StartPoint="1,1" EndPoint="0,0" >
                    <GradientStop Color="White" Offset="0"/>
                    <GradientStop Color="CornflowerBlue" Offset="1"/>
                </LinearGradientBrush>
            </Ellipse.Fill>
            <Ellipse.RenderTransform>
                <RotateTransform x:Name="SpinnerRotate" CenterX="10" CenterY="10"/>
            </Ellipse.RenderTransform>
            <Ellipse.Style>
                <Style TargetType="Ellipse">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsWorking}" Value="True">
                            <DataTrigger.EnterActions>
                                <BeginStoryboard x:Name="SpinStoryboard">
                                    <Storyboard TargetProperty="RenderTransform.Angle" >
                                        <DoubleAnimation
                                            From="0" To="360" Duration="0:0:01"
                                            RepeatBehavior="Forever" />
                                    </Storyboard>
                                </BeginStoryboard>
                            </DataTrigger.EnterActions>
                            <DataTrigger.ExitActions>
                                <StopStoryboard BeginStoryboardName="SpinStoryboard"></StopStoryboard>
                            </DataTrigger.ExitActions>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Ellipse.Style>
        </Ellipse>
    </StackPanel>
</UserControl>  

Simple Android RecyclerView example

Since I cant comment yet im gonna post as an answer the link.. I have found a simple, well organized tutorial on recyclerview http://www.androiddeft.com/2017/10/01/recyclerview-android/

Apart from that when you are going to add a recycler view into you activity what you want to do is as below and how you should do this has been described on the link

  • add RecyclerView component into your layout file
  • make a class which you are going to display as list rows
  • make a layout file which is the layout of a row of you list
  • now we need a custom adapter so create a custom adapter by extending from the parent class RecyclerView.Adapter
  • add recyclerview into your mainActivity oncreate
  • adding separators
  • adding Touch listeners

SQL DELETE with JOIN another table for WHERE condition

How about:

DELETE guide_category  
  WHERE id_guide_category IN ( 

        SELECT id_guide_category 
          FROM guide_category AS gc
     LEFT JOIN guide AS g 
            ON g.id_guide = gc.id_guide
         WHERE g.title IS NULL

  )

Online SQL syntax checker conforming to multiple databases

Only know about this. Not sure how well does it against MySQL http://developer.mimer.se/validator/

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

You need to use a global regular expression for this. Try it this way:

str.replace(/"/g, '\\"');

Check out regex syntax and options for the replace function in Using Regular Expressions with JavaScript.

Android Viewpager as Image Slide Gallery

Just use this https://gist.github.com/8cbe094bb7a783e37ad1 for make surrounding pages visible and http://viewpagerindicator.com/ this, for indicator. That's pretty cool, i'm using it for a gallery.

How to return the output of stored procedure into a variable in sql server

Use this code, Working properly

CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT

AS
Begin
 DECLARE @cnt int;
 DECLARE @status int =0;
 SET NOCOUNT OFF
 SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
 if(@cnt = 1)
   Begin
     return @status;
   End
 else
  Begin
   SET @status =1;
    return @status;
 End
END

Execute SP

DECLARE @statuss bit;
EXECUTE  [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;

Bootstrap: wider input field

In bootstrap 4, they have designed a bigger input file.

A simple solution to increase the size input file is to use font-size:

Add you style, for example:

input[type="file"] {
  font-size:35px
}

Otherwise, you can make one custom class and add to input control.

What does 'synchronized' mean?

synchronized simple means no two threads can access the block/method simultaneously. When we say any block/method of a class is synchronized it means only one thread can access them at a time. Internally the thread which tries to access it first take a lock on that object and as long as this lock is not available no other thread can access any of the synchronized methods/blocks of that instance of the class.

Note another thread can access a method of the same object which is not defined to be synchronized. A thread can release the lock by calling

Object.wait()

Illegal Escape Character "\"

I think ("\") may be causing the problem because \ is the escape character. change it to ("\\")

How to embed HTML into IPython output?

Some time ago Jupyter Notebooks started stripping JavaScript from HTML content [#3118]. Here are two solutions:

Serving Local HTML

If you want to embed an HTML page with JavaScript on your page now, the easiest thing to do is to save your HTML file to the directory with your notebook and then load the HTML as follows:

from IPython.display import IFrame

IFrame(src='./nice.html', width=700, height=600)

Serving Remote HTML

If you prefer a hosted solution, you can upload your HTML page to an Amazon Web Services "bucket" in S3, change the settings on that bucket so as to make the bucket host a static website, then use an Iframe component in your notebook:

from IPython.display import IFrame

IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)

This will render your HTML content and JavaScript in an iframe, just like you can on any other web page:

_x000D_
_x000D_
<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>
_x000D_
_x000D_
_x000D_

How do I find out my root MySQL password?

Here is the best way to set your root password : Source Link Step 3 is working perfectly for me.

Commands for You

  1. sudo mysql
  2. SELECT user,authentication_string,plugin,host FROM mysql.user;
  3. ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
  4. FLUSH PRIVILEGES;
  5. SELECT user,authentication_string,plugin,host FROM mysql.user;
  6. exit

Now you can use the Password for the root user is 'password' :

  1. mysql -u root -p
  2. CREATE USER 'sammy'@'localhost' IDENTIFIED BY 'password';
  3. GRANT ALL PRIVILEGES ON . TO 'sammy'@'localhost' WITH GRANT OPTION;
  4. FLUSH PRIVILEGES;
  5. exit

Test your MySQL Service and Version:

systemctl status mysql.service
sudo mysqladmin -p -u root version

Java - How to access an ArrayList of another class?

Two ways

1)instantiate the first class and getter for arrayList

or

2)Make arraylist as static

And finally

Java Basics By Oracle

How to replace (null) values with 0 output in PIVOT

Sometimes it's better to think like a parser, like T-SQL parser. While executing the statement, parser does not have any value in Pivot section and you can't have any check expression in that section. By the way, you can simply use this:

SELECT  CLASS
,   IsNull([AZ], 0)
,   IsNull([CA], 0)
,   IsNull([TX], 0)
    FROM #TEMP
    PIVOT (
        SUM(DATA)
        FOR STATE IN (
            [AZ]
        ,   [CA]
        ,   [TX]
        )
    )   AS  PVT
    ORDER   BY  CLASS

How to change the remote repository for a git submodule?

These commands will do the work on command prompt without altering any files on local repository

git config --file=.gitmodules submodule.Submod.url https://github.com/username/ABC.git
git config --file=.gitmodules submodule.Submod.branch Development
git submodule sync
git submodule update --init --recursive --remote

Please look at the blog for screenshots: Changing GIT submodules URL/Branch to other URL/branch of same repository

How to set the text/value/content of an `Entry` widget using a button in tkinter

You can choose between the following two methods to set the text of an Entry widget. For the examples, assume imported library import tkinter as tk and root window root = tk.Tk().


  • Method A: Use delete and insert

    Widget Entry provides methods delete and insert which can be used to set its text to a new value. First, you'll have to remove any former, old text from Entry with delete which needs the positions where to start and end the deletion. Since we want to remove the full old text, we start at 0 and end at wherever the end currently is. We can access that value via END. Afterwards the Entry is empty and we can insert new_text at position 0.

    entry = tk.Entry(root)
    new_text = "Example text"
    entry.delete(0, tk.END)
    entry.insert(0, new_text)
    

  • Method B: Use StringVar

    You have to create a new StringVar object called entry_text in the example. Also, your Entry widget has to be created with keyword argument textvariable. Afterwards, every time you change entry_text with set, the text will automatically show up in the Entry widget.

    entry_text = tk.StringVar()
    entry = tk.Entry(root, textvariable=entry_text)
    new_text = "Example text"
    entry_text.set(new_text)
    

  • Complete working example which contains both methods to set the text via Button:

    This window

    screenshot

    is generated by the following complete working example:

    import tkinter as tk
    
    def button_1_click():
        # define new text (you can modify this to your needs!)
        new_text = "Button 1 clicked!"
        # delete content from position 0 to end
        entry.delete(0, tk.END)
        # insert new_text at position 0
        entry.insert(0, new_text)
    
    def button_2_click():
        # define new text (you can modify this to your needs!)
        new_text = "Button 2 clicked!"
        # set connected text variable to new_text
        entry_text.set(new_text)
    
    root = tk.Tk()
    
    entry_text = tk.StringVar()
    entry = tk.Entry(root, textvariable=entry_text)
    
    button_1 = tk.Button(root, text="Button 1", command=button_1_click)
    button_2 = tk.Button(root, text="Button 2", command=button_2_click)
    
    entry.pack(side=tk.TOP)
    button_1.pack(side=tk.LEFT)
    button_2.pack(side=tk.LEFT)
    
    root.mainloop()
    

Datatable select with multiple conditions

Try this,
I think ,this is one of the simple solutions.

int rowIndex = table.Rows.IndexOf(table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'")[0]);
string strD= Convert.ToString(table.Rows[rowIndex]["D"]);

Make sure,combination of values for column A, B and C is unique in the datatable.

How do you format an unsigned long long int using printf?

In addition to what people wrote years ago:

  • you might get this error on gcc/mingw:

main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=]

printf("%llu\n", k);

Then your version of mingw does not default to c99. Add this compiler flag: -std=c99.

Create pandas Dataframe by appending one row at a time

Instead of a list of dictionaries as in ShikharDua's answer, we can also represent our table as a dictionary of lists, where each list stores one column in row-order, given we know our columns beforehand. At the end we construct our DataFrame once.

For c columns and n rows, this uses 1 dictionary and c lists, versus 1 list and n dictionaries. The list of dictionaries method has each dictionary storing all keys and requires creating a new dictionary for every row. Here we only append to lists, which is constant time and theoretically very fast.

# current data
data = {"Animal":["cow", "horse"], "Color":["blue", "red"]}

# adding a new row (be careful to ensure every column gets another value)
data["Animal"].append("mouse")
data["Color"].append("black")

# at the end, construct our DataFrame
df = pd.DataFrame(data)
#   Animal  Color
# 0    cow   blue
# 1  horse    red
# 2  mouse  black

How to import jquery using ES6 syntax?

webpack users, add the below to your plugins array.

let plugins = [
  // expose $ and jQuery to global scope.
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery'
  })
];

Process all arguments except the first one (in a bash script)

Came across this looking for something else. While the post looks fairly old, the easiest solution in bash is illustrated below (at least bash 4) using set -- "${@:#}" where # is the starting number of the array element we want to preserve forward:

    #!/bin/bash

    someVar="${1}"
    someOtherVar="${2}"
    set -- "${@:3}"
    input=${@}

    [[ "${input[*],,}" == *"someword"* ]] && someNewVar="trigger"

    echo -e "${someVar}\n${someOtherVar}\n${someNewVar}\n\n${@}"

Basically, the set -- "${@:3}" just pops off the first two elements in the array like perl's shift and preserves all remaining elements including the third. I suspect there's a way to pop off the last elements as well.

Get query string parameters url values with jQuery / Javascript (querystring)

After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!

//Assuming URL has "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

UPDATE : IE is not supported

use this function from an answer below instead of URLSearchParams

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('action')); //edit

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

Access Tomcat Manager App from different host

To access the tomcat manager from different machine you have to follow bellow steps:

1. Update conf/tomcat-users.xml file with user and some roles:

<role rolename="manager-gui"/>
 <role rolename="manager-script"/>
 <role rolename="manager-jmx"/>
 <role rolename="manager-status"/>
 <user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>

Here admin user is assigning roles="manager-gui,manager-script,manager-jmx,manager-status".

Here tomcat user and password is : admin

2. Update webapps/manager/META-INF/context.xml file (Allowing IP address):

Default configuration:

<Context antiResourceLocking="false" privileged="true" >
  
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
  
  <Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>

Here in Valve it is allowing only local machine IP start with 127.\d+.\d+.\d+ .

2.a : Allow specefic IP:

<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|YOUR.IP.ADDRESS.HERE" />

Here you just replace |YOUR.IP.ADDRESS.HERE with your IP address

2.b : Allow all IP:

<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow=".*" />

Here using allow=".*" you are allowing all IP.

Thanks :)

How to log out user from web site using BASIC authentication?

The following function is confirmed working for Firefox 40, Chrome 44, Opera 31 and IE 11.
Bowser is used for browser detection, jQuery is also used.

- secUrl is the url to a password protected area from which to log out.
- redirUrl is the url to a non password protected area (logout success page).
- you might wish to increase the redirect timer (currently 200ms).

_x000D_
_x000D_
function logout(secUrl, redirUrl) {_x000D_
    if (bowser.msie) {_x000D_
        document.execCommand('ClearAuthenticationCache', 'false');_x000D_
    } else if (bowser.gecko) {_x000D_
        $.ajax({_x000D_
            async: false,_x000D_
            url: secUrl,_x000D_
            type: 'GET',_x000D_
            username: 'logout'_x000D_
        });_x000D_
    } else if (bowser.webkit) {_x000D_
        var xmlhttp = new XMLHttpRequest();_x000D_
        xmlhttp.open("GET", secUrl, true);_x000D_
        xmlhttp.setRequestHeader("Authorization", "Basic logout");_x000D_
        xmlhttp.send();_x000D_
    } else {_x000D_
        alert("Logging out automatically is unsupported for " + bowser.name_x000D_
            + "\nYou must close the browser to log out.");_x000D_
    }_x000D_
    setTimeout(function () {_x000D_
        window.location.href = redirUrl;_x000D_
    }, 200);_x000D_
}
_x000D_
_x000D_
_x000D_

Remove all special characters from a string in R?

Convert the Special characters to apostrophe,

Data  <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)

Below code it to remove extra ''' apostrophe

Data <- gsub("''","" , Data ,ignore.case = TRUE)

Use gsub(..) function for replacing the special character with apostrophe

Display a float with two decimal places in Python

I know it is an old question, but I was struggling finding the answer myself. Here is what I have come up with:

Python 3:

>>> num_dict = {'num': 0.123, 'num2': 0.127}
>>> "{0[num]:.2f}_{0[num2]:.2f}".format(num_dict) 
0.12_0.13

Rolling back local and remote git repository by 1 commit

For Windows Machines, use:

git reset HEAD~1  #Remove Commit Locally

Group list by values

>>> xs = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
>>> xs.sort(key=lambda x: x[1])
>>> reduce(lambda l, x: (l.append([x]) if l[-1][0][1] != x[1] else l[-1].append(x)) or l, xs[1:], [[xs[0]]]) if xs else []
[[['A', 0], ['C', 0]], [['B', 1]], [['D', 2], ['E', 2]]]

Basically, if the list is sorted, it is possible to reduce by looking at the last group constructed by the previous steps - you can tell if you need to start a new group, or modify an existing group. The ... or l bit is a trick that enables us to use lambda in Python. (append returns None. It is always better to return something more useful than None, but, alas, such is Python.)

Simple Pivot Table to Count Unique Values

Excel 2013 can do Count distinct in pivots. If no access to 2013, and it's a smaller amount of data, I make two copies of the raw data, and in copy b, select both columns and remove duplicates. Then make the pivot and count your column b.

Connecting to remote MySQL server using PHP

This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:

The client have two network cards,a wireless one and a normal one. The ping to server can be succeed.However telnet serverAddress 3306 would fail. And would complain

Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)

when try to connect to server.So I forbidden the normal network adapters. And tried telnet serverAddress 3306 it works.And then it work when connect to MySQL server.

Bootstrap center heading

Just use "justify-content-center" in the row's class attribute.

<div class="container">
  <div class="row justify-content-center">
    <h1>This is a header</h1>
  </div>
</div>

Regex - Should hyphens be escaped?

Outside of character classes, it is conventional not to escape hyphens. If I saw an escaped hyphen outside of a character class, that would suggest to me that it was written by someone who was not very comfortable with regexes.

Inside character classes, I don't think one way is conventional over the other; in my experience, it usually seems to be to put either first or last, as in [-._:] or [._:-], to avoid the backslash; but I've also often seen it escaped instead, as in [._\-:], and I wouldn't call that unconventional.

What is SaaS, PaaS and IaaS? With examples

SaaS: Software as a Service Cloud application services or “Software as a Service” (SaaS) are probably the most popular form of cloud computing and are easy to use. SaaS uses the Web to deliver applications that are managed by a third-party vendor and whose interface is accessed on the clients’ side. Most SaaS applications can be run directly from a Web browser, without any downloads or installations required. SaaS eliminates the need to install and run applications on individual computers. With SaaS, it’s easy for enterprises to streamline their maintenance and support, because everything can be managed by vendors: applications, runtime, data, middleware, O/S, virtualization, servers, storage, and networking. Gmail is one famous example of an SaaS mail provider.

PaaS: Platform as a Service The most complex of the three, cloud platform services or “Platform as a Service” (PaaS) deliver computational resources through a platform. What developers gain with PaaS is a framework they can build upon to develop or customize applications. PaaS makes the development, testing, and deployment of applications quick, simple, and cost-effective, eliminating the need to buy the underlying layers of hardware and software. One comparison between SaaS vs. PaaS has to do with what aspects must be managed by users, rather than providers: With PaaS, vendors still manage runtime, middleware, O/S, virtualization, servers, storage, and networking, but users manage applications and data.

IaaS: Infrastructure as a Service Cloud infrastructure services, known as “Infrastructure as a Service” (IaaS), deliver computer infrastructure (such as a platform virtualization environment), storage, and networking. Instead of having to purchase software, servers, or network equipment, users can buy these as a fully outsourced service that is usually billed according to the amount of resources consumed. Basically, in exchange for a rental fee, a third party allows you to install a virtual server on their IT infrastructure. Compared to SaaS and PaaS, IaaS users are responsible for managing more: applications, data, runtime, middleware, and O/S. Vendors still manage virtualization, servers, hard drives, storage, and networking. What users gain with IaaS is infrastructure on top of which they can install any required platforms. Users are responsible for updating these if new versions are released.

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}

How to compare two double values in Java?

Consider this line of code:

Math.abs(firstDouble - secondDouble) < Double.MIN_NORMAL

It returns whether firstDouble is equal to secondDouble. I'm unsure as to whether or not this would work in your exact case (as Kevin pointed out, performing any math on floating points can lead to imprecise results) however I was having difficulties with comparing two double which were, indeed, equal, and yet using the 'compareTo' method didn't return 0.

I'm just leaving this there in case anyone needs to compare to check if they are indeed equal, and not just similar.

How to change RGB color to HSV?

The EasyRGB has many color space conversions. Here is the code for the RGB->HSV conversion.

SSL Connection / Connection Reset with IISExpress

Another problem that happened me twice:
In IIS Express's applicationhost.config the order of the bindings does matter. One binding could take precedence over your SSL binding, making it not working.

Example:

<site name="MySite007" id="1">
    <application path="/" applicationPool="Clr4IntegratedAppPool">
        <virtualDirectory path="/" physicalPath="C:\Users\myuser\projects\mysolutionfolder\MyProject.Service" />
    </application>
    <bindings>
        <binding protocol="http" bindingInformation=":8081:localhost" />
        <binding protocol="http" bindingInformation=":8080:" /><!-- evil binding -->
        <binding protocol="https" bindingInformation="*:44327:localhost" />
    </bindings>
</site>

You may have added a binding similar to the second one to be able to access your WebService from outside localhost. Because this binding listens on any adress, it seems to override the SSL binding although a different port was used.

Remove the evil binding or move it down.

cut or awk command to print first field of first row

You can kill the process which is running the container.

With this command you can list the processes related with the docker container:

ps -aux | grep $(docker ps -a | grep container-name | awk '{print $1}')

Now you have the process ids to kill with kill or kill -9.

no suitable HttpMessageConverter found for response type

From a Spring point of view, none of the HttpMessageConverter instances registered with the RestTemplate can convert text/html content to a ProductList object. The method of interest is HttpMessageConverter#canRead(Class, MediaType). The implementation for all of the above returns false, including Jaxb2RootElementHttpMessageConverter.

Since no HttpMessageConverter can read your HTTP response, processing fails with an exception.

If you can control the server response, modify it to set the Content-type to application/xml, text/xml, or something matching application/*+xml.

If you don't control the server response, you'll need to write and register your own HttpMessageConverter (which can extend the Spring classes, see AbstractXmlHttpMessageConverter and its sub classes) that can read and convert text/html.

How do I commit only some files?

Some of this seems "incomplete"

Groups of people are NOT going to know if they should use quotes etc..

Add 1 specific file showing the location paths as well

git add JobManager/Controllers/APIs/ProfileApiController.cs

Commit (remember, commit is local only, it is not affecting any other system)

git commit -m "your message"  

Push to remote repo

git push  (this is after the commit and this attempts to Merge INTO the remote location you have instructed it to merge into)

Other answer(s) show the stash etc. which you sometimes will want to do

Two color borders

Yep: Use the outline property; it acts as a second border outside of your border. Beware, tho', it can interact in a wonky fashion with margins, paddings and drop-shadows. In some browsers you might have to use a browser-specific prefix as well; in order to make sure it picks up on it: -webkit-outline and the like (although WebKit in particular doesn't require this).

This can also be useful in the case where you want to jettison the outline for certain browsers (such as is the case if you want to combine the outline with a drop shadow; in WebKit the outline is inside of the shadow; in FireFox it is outside, so -moz-outline: 0 is useful to ensure that you don't get a gnarly line around your beautiful CSS drop shadow).

.someclass {
  border: 1px solid blue;
  outline: 1px solid darkblue;
}

Edit: Some people have remarked that outline doesn't jive well with IE < 8. While this is true; supporting IE < 8 really isn't something you should be doing.

No numeric types to aggregate - change in groupby() behaviour?

I got this error generating a data frame consisting of timestamps and data:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))

Adding the suggested solution works for me:

df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))

Thanks Chang She!

Example:

                     data
2005-01-01 00:10:00  7.53
2005-01-01 00:20:00  7.54
2005-01-01 00:30:00  7.62
2005-01-01 00:40:00  7.68
2005-01-01 00:50:00  7.81
2005-01-01 01:00:00  7.95
2005-01-01 01:10:00  7.96
2005-01-01 01:20:00  7.95
2005-01-01 01:30:00  7.98
2005-01-01 01:40:00  8.06
2005-01-01 01:50:00  8.04
2005-01-01 02:00:00  8.06
2005-01-01 02:10:00  8.12
2005-01-01 02:20:00  8.12
2005-01-01 02:30:00  8.25
2005-01-01 02:40:00  8.27
2005-01-01 02:50:00  8.17
2005-01-01 03:00:00  8.21
2005-01-01 03:10:00  8.29
2005-01-01 03:20:00  8.31
2005-01-01 03:30:00  8.25
2005-01-01 03:40:00  8.19
2005-01-01 03:50:00  8.17
2005-01-01 04:00:00  8.18
                     data
2005-01-01 00:00:00  7.636000
2005-01-01 01:00:00  7.990000
2005-01-01 02:00:00  8.165000
2005-01-01 03:00:00  8.236667
2005-01-01 04:00:00  8.180000

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

For me this problem occurred because I had a some invalid character in my Groovy script. In our case this was an extra blank line after the closing bracket of the script.

How to replace all special character into a string using C#

Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):

string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,

You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s to pattern: \[^\w\d\s]

Global variables in c#.net

I second jdk's answer: any public static member of any class of your application can be considered as a "global variable".

However, do note that this is an ASP.NET application, and as such, it's a multi-threaded context for your global variables. Therefore, you should use some locking mechanism when you update and/or read the data to/from these variables. Otherwise, you might get your data in a corrupted state.

Table with table-layout: fixed; and how to make one column wider

What you could do is something like this (pseudocode):

<container table>
  <tr>
    <td>
      <"300px" table>
    <td>
      <fixed layout table>

Basically, split up the table into two tables and have it contained by another table.

Is a Python dictionary an example of a hash table?

To expand upon nosklo's explanation:

a = {}
b = ['some', 'list']
a[b] = 'some' # this won't work
a[tuple(b)] = 'some' # this will, same as a['some', 'list']

Remove border radius from Select tag in bootstrap 3

You can use -webkit-border-radius: 0;. Like this:-

-webkit-border-radius: 0;
border: 0;
outline: 1px solid grey;
outline-offset: -1px;

This will give square corners as well as dropdown arrows. Using -webkit-appearance: none; is not recommended as it will turn off all the styling done by Chrome.

Submitting form and pass data to controller method of type FileStreamResult

here the problem is model binding if you specify a class then the model binding can understand it during the post if it an integer or string then you have to specify the [FromBody] to bind it properly.

make the following changes in FormMethod

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){

}

and inside your home controller for binding the string you should specify [FromBody]

using System.Web.Http;
[HttpPost]
public FileStreamResult myMethod([FromBody]string id)
{
     // Set a local variable with the incoming data
     string str = id;

}

FromBody is available in System.Web.Http. make sure you have the reference to that class and added it in the cs file.

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

How to prevent IFRAME from redirecting top-level window

Since the page you load inside the iframe can execute the "break out" code with a setInterval, onbeforeunload might not be that practical, since it could flud the user with 'Are you sure you want to leave?' dialogs.

There is also the iframe security attribute which only works on IE & Opera

:(

How do android screen coordinates work?

enter image description here

This image presents both orientation(Landscape/Portrait)

To get MaxX and MaxY, read on.

For Android device screen coordinates, below concept will work.

Display mdisp = getWindowManager().getDefaultDisplay();
Point mdispSize = new Point();
mdisp.getSize(mdispSize);
int maxX = mdispSize.x; 
int maxY = mdispSize.y;

EDIT:- ** **for devices supporting android api level older than 13. Can use below code.

    Display mdisp = getWindowManager().getDefaultDisplay();
    int maxX= mdisp.getWidth();
    int maxY= mdisp.getHeight();

(x,y) :-

1) (0,0) is top left corner.

2) (maxX,0) is top right corner

3) (0,maxY) is bottom left corner

4) (maxX,maxY) is bottom right corner

here maxX and maxY are screen maximum height and width in pixels, which we have retrieved in above given code.

'dict' object has no attribute 'has_key'

has_key has been deprecated in Python 3.0. Alternatively you can use 'in'

graph={'A':['B','C'],
   'B':['C','D']}

print('A' in graph)
>> True

print('E' in graph)
>> False

What does int argc, char *argv[] mean?

Suppose you run your program thus (using sh syntax):

myprog arg1 arg2 'arg 3'

If you declared your main as int main(int argc, char *argv[]), then (in most environments), your main() will be called as if like:

p = { "myprog", "arg1", "arg2", "arg 3", NULL };
exit(main(4, p));

However, if you declared your main as int main(), it will be called something like

exit(main());

and you don't get the arguments passed.

Two additional things to note:

  1. These are the only two standard-mandated signatures for main. If a particular platform accepts extra arguments or a different return type, then that's an extension and should not be relied upon in a portable program.
  2. *argv[] and **argv are exactly equivalent, so you can write int main(int argc, char *argv[]) as int main(int argc, char **argv).

Reading HTTP headers in a Spring REST controller

Instead of taking the HttpServletRequest object in every method, keep in controllers' context by auto-wiring via the constructor. Then you can access from all methods of the controller.

public class OAuth2ClientController {
    @Autowired
    private OAuth2ClientService oAuth2ClientService;

    private HttpServletRequest request;

    @Autowired
    public OAuth2ClientController(HttpServletRequest request) {
        this.request = request;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<String> createClient(@RequestBody OAuth2Client client) {
        System.out.println(request.getRequestURI());
        System.out.println(request.getHeader("Content-Type"));

        return ResponseEntity.ok();
    }
}

how to change background image of button when clicked/focused?

Sorry this is wrong.

For changing background color/image based on the particular event(focus, press, normal), you need to define a button selector file and implement it as background for button.

For example: button_selector.xml (define this file inside the drawable folder)

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:color="#000000" /> <!-- pressed -->
     <item android:state_focused="true"
           android:color="#000000" /> <!-- focused -->
     <item android:color="#FFFFFF" /> <!-- default -->
 </selector>

    <!-- IF you want image instead of color then write 
android:drawable="@drawable/your_image" inside the <item> tag -->

And apply it as:

 <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:drawable="@drawable/button_selector.xml" />

Updating a JSON object using Javascript

use:

var parsedobj = jQuery.parseJSON( jsonObj);

This will only be useful if you don't need the format to stay in string. otherwise you'd have to convert this back to JSON using the JSON library.

How can you get the Manifest Version number from the App's (Layout) XML variables?

I solved this issue by extending the Preference class.

package com.example.android;

import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;

public class VersionPreference extends Preference {
    public VersionPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        String versionName;
        final PackageManager packageManager = context.getPackageManager();
        if (packageManager != null) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                versionName = null;
            }
            setSummary(versionName);
        }
    }
}

Then in my preferences XML:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <com.example.android.VersionPreference android:title="Version" />
</PreferenceScreen>

Rails filtering array of objects by attribute value

have you tried eager loading?

@attachments = Job.includes(:attachments).find(1).attachments

Move cursor to end of file in vim

If you want to paste some clipboard content at the end of the file type:

:$ put +

$ ............ last line
put .......... paste 
+ ............ clipboard

To delay JavaScript function call using jQuery

function sample() {
    alert("This is sample function");
}

$(function() {
    $("#button").click(function() {
        setTimeout(sample, 2000);
    });

});

jsFiddle.

If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().

IE9 jQuery AJAX with CORS returns "Access is denied"

To solve this problem, also check if you have some included .js into your ajax file called: I received Access denied error while including shadowbox.js in my ajax.php

What is the difference between Numpy's array() and asarray() functions?

The definition of asarray is:

def asarray(a, dtype=None, order=None):
    return array(a, dtype, copy=False, order=order)

So it is like array, except it has fewer options, and copy=False. array has copy=True by default.

The main difference is that array (by default) will make a copy of the object, while asarray will not unless necessary.

How to set Spring profile from system variable?

If i run the command line : java -Dspring.profiles.active=development -jar yourApplication.jar from my webapplication directory it states that the path is incorrect. So i just defined the profile in manualy in the application.properties file like this :

spring.profiles.active=mysql 

or

spring.profiles.active=postgres

or

spring.profiles.active=mongodb

PHP foreach loop key value

You can also use array_keys() . Newbie friendly:

$keys = array_keys($arrayToWalk);
$arraySize = count($arrayToWalk); 

for($i=0; $i < $arraySize; $i++) {
    echo '<option value="' . $keys[$i] . '">' . $arrayToWalk[$keys[$i]] . '</option>';
}

Running Jupyter via command line on Windows

Please try either of these commands first;

$ py -m notebook
$ python -m notebook

for jupyterlab users

py -m jupyterlab

Otherwise

$ python -m pip install jupyter --user
$ jupyter notebook

If this does not work.

pip does not add jupyter directly to path for local.

The output from

$ which python
/c/Users/<username>/AppData/Local/Programs/Python/Python35-32/python

After some digging I found a executable for jupyter in the folder:

C:\Users\<username>\AppData\Roaming\Python\Python35\Scripts\jupyter.exe

Difference between local and roaming folder

So if you want to be able to execute a program via command line, you need to add it into the %PATH variable. Here is a powershell script to do it. BE SURE TO ADD THE ";" before adding the new path.

$ [Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\Users\<username>\AppData\Roaming\Python\Python35\Scripts", [EnvironmentVariableTarget]::User)

Update:

if you are using python3, switch out python with python3 but I encourage you to use pyenv instead :)

failed to push some refs to [email protected]

Make sure you’re pushing the right branch. I wasn’t on master and kept wondering why it was complaining :P

Insert new item in array on any position in PHP

For inserting elements into an array with string keys you can do something like this:

/* insert an element after given array key
 * $src = array()  array to work with
 * $ins = array() to insert in key=>array format
 * $pos = key that $ins will be inserted after
 */ 
function array_insert_string_keys($src,$ins,$pos) {

    $counter=1;
    foreach($src as $key=>$s){
        if($key==$pos){
            break;
        }
        $counter++;
    } 

    $array_head = array_slice($src,0,$counter);
    $array_tail = array_slice($src,$counter);

    $src = array_merge($array_head, $ins);
    $src = array_merge($src, $array_tail);

    return($src); 
} 

npm global path prefix

If you have linked the node packages using sudo command

Then go to the folder where node_modules are installed globally.

On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node.

Windows XP - %USERPROFILE%\Application Data\npm\node_modules Windows 7 - %AppData%\npm\node_modules

and then run the command

ls -l

This will give the list of all global node_modules and you can easily see the linked node modules.

set environment variable in python script

Compact solution (provided you don't need other environment variables):

call('sqsub -np {} /homedir/anotherdir/executable'.format(var1).split(),
      env=dict(LD_LIBRARY_PATH=my_path))

Using the env command line tool:

call('env LD_LIBRARY_PATH=my_path sqsub -np {} /homedir/anotherdir/executable'.format(var1).split())

What is "origin" in Git?

Git has the concept of "remotes", which are simply URLs to other copies of your repository. When you clone another repository, Git automatically creates a remote named "origin" and points to it.

You can see more information about the remote by typing git remote show origin.

How to compare arrays in C#?

You can use the Enumerable.SequenceEqual() in the System.Linq to compare the contents in the array

bool isEqual = Enumerable.SequenceEqual(target1, target2);

Why does find -exec mv {} ./target/ + not work?

The standard equivalent of find -iname ... -exec mv -t dest {} + for find implementations that don't support -iname or mv implementations that don't support -t is to use a shell to re-order the arguments:

find . -name '*.[cC][pP][pP]' -type f -exec sh -c '
  exec mv "$@" /dest/dir/' sh {} +

By using -name '*.[cC][pP][pP]', we also avoid the reliance on the current locale to decide what's the uppercase version of c or p.

Note that +, contrary to ; is not special in any shell so doesn't need to be quoted (though quoting won't harm, except of course with shells like rc that don't support \ as a quoting operator).

The trailing / in /dest/dir/ is so that mv fails with an error instead of renaming foo.cpp to /dest/dir in the case where only one cpp file was found and /dest/dir didn't exist or wasn't a directory (or symlink to directory).

How can I split a text file using PowerShell?

As the lines can be variable in logs I thought it best to take a number of lines per file approach. The following code snippet processed a 4 million line log file in under 19 seconds (18.83.. seconds)splitting it into 500,000 line chunks:

$sourceFile = "c:\myfolder\mylargeTextyFile.csv"
$partNumber = 1
$batchSize = 500000
$pathAndFilename = "c:\myfolder\mylargeTextyFile part $partNumber file.csv"

[System.Text.Encoding]$enc = [System.Text.Encoding]::GetEncoding(65001)  # utf8 this one

$fs=New-Object System.IO.FileStream ($sourceFile,"OpenOrCreate", "Read", "ReadWrite",8,"None") 
$streamIn=New-Object System.IO.StreamReader($fs, $enc)
$streamout = new-object System.IO.StreamWriter $pathAndFilename

$line = $streamIn.readline()
$counter = 0
while ($line -ne $null)
{
    $streamout.writeline($line)
    $counter +=1
    if ($counter -eq $batchsize)
    {
        $partNumber+=1
        $counter =0
        $streamOut.close()
        $pathAndFilename = "c:\myfolder\mylargeTextyFile part $partNumber file.csv"
        $streamout = new-object System.IO.StreamWriter $pathAndFilename

    }
    $line = $streamIn.readline()
}
$streamin.close()
$streamout.close()

This can easily be turned into a function or script file with parameters to make it more versatile. It uses a StreamReader and StreamWriter to achieve its speed and tiny memory footprint

CSS hover vs. JavaScript mouseover

In reguards to using jQuery to do hover, I always use the plugin HoverIntent as it doesn't fire the event until you pause over an element for brief period of time... this stops firing off lots of mouse over events if you accidentally run the mouse over them or simply whilst choosing an option.

Why do we use web.xml?

Generally speaking, this is the configuration file of web applications in java. It instructs the servlet container (tomcat for ex.) which classes to load, what parameters to set in the context, and how to intercept requests coming from browsers.

There you specify:

  • what servlets (and filters) you want to use and what URLs you want to map them to
  • listeners - classes that are notified when some events happen (context starts, session created, etc)
  • configuration parameters (context-params)
  • error pages, welcome files
  • security constraints

In servlet 3.0 many of the web.xml parts are optional. These configurations can be done via annotations (@WebServlet, @WebListener)

How to expand a list to function arguments in Python

You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.

Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

def foo(x,y,z):
   return "%d, %d, %d" % (x,y,z)

values = [1,2,3]

# the solution.
foo(*values)

Fastest Way of Inserting in Entity Framework

To your remark in the comments to your question:

"...SavingChanges (for each record)..."

That's the worst thing you can do! Calling SaveChanges() for each record slows bulk inserts extremely down. I would do a few simple tests which will very likely improve the performance:

  • Call SaveChanges() once after ALL records.
  • Call SaveChanges() after for example 100 records.
  • Call SaveChanges() after for example 100 records and dispose the context and create a new one.
  • Disable change detection

For bulk inserts I am working and experimenting with a pattern like this:

using (TransactionScope scope = new TransactionScope())
{
    MyDbContext context = null;
    try
    {
        context = new MyDbContext();
        context.Configuration.AutoDetectChangesEnabled = false;

        int count = 0;            
        foreach (var entityToInsert in someCollectionOfEntitiesToInsert)
        {
            ++count;
            context = AddToContext(context, entityToInsert, count, 100, true);
        }

        context.SaveChanges();
    }
    finally
    {
        if (context != null)
            context.Dispose();
    }

    scope.Complete();
}

private MyDbContext AddToContext(MyDbContext context,
    Entity entity, int count, int commitCount, bool recreateContext)
{
    context.Set<Entity>().Add(entity);

    if (count % commitCount == 0)
    {
        context.SaveChanges();
        if (recreateContext)
        {
            context.Dispose();
            context = new MyDbContext();
            context.Configuration.AutoDetectChangesEnabled = false;
        }
    }

    return context;
}

I have a test program which inserts 560.000 entities (9 scalar properties, no navigation properties) into the DB. With this code it works in less than 3 minutes.

For the performance it is important to call SaveChanges() after "many" records ("many" around 100 or 1000). It also improves the performance to dispose the context after SaveChanges and create a new one. This clears the context from all entites, SaveChanges doesn't do that, the entities are still attached to the context in state Unchanged. It is the growing size of attached entities in the context what slows down the insertion step by step. So, it is helpful to clear it after some time.

Here are a few measurements for my 560000 entities:

  • commitCount = 1, recreateContext = false: many hours (That's your current procedure)
  • commitCount = 100, recreateContext = false: more than 20 minutes
  • commitCount = 1000, recreateContext = false: 242 sec
  • commitCount = 10000, recreateContext = false: 202 sec
  • commitCount = 100000, recreateContext = false: 199 sec
  • commitCount = 1000000, recreateContext = false: out of memory exception
  • commitCount = 1, recreateContext = true: more than 10 minutes
  • commitCount = 10, recreateContext = true: 241 sec
  • commitCount = 100, recreateContext = true: 164 sec
  • commitCount = 1000, recreateContext = true: 191 sec

The behaviour in the first test above is that the performance is very non-linear and decreases extremely over time. ("Many hours" is an estimation, I never finished this test, I stopped at 50.000 entities after 20 minutes.) This non-linear behaviour is not so significant in all other tests.

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

Delete files or folder recursively on Windows CMD

After the blog post How Can I Use Windows PowerShell to Delete All the .TMP Files on a Drive?, you can use something like this to delete all .tmp for example from a folder and all subfolders in PowerShell:

get-childitem [your path/ or leave empty for current path] -include
*.tmp -recurse | foreach ($_) {remove-item $_.fullname}

How to use org.apache.commons package?

Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

React proptype array with shape

This was my solution to protect against an empty array as well:

import React, { Component } from 'react';
import { arrayOf, shape, string, number } from 'prop-types';

ReactComponent.propTypes = {
  arrayWithShape: (props, propName, componentName) => {
    const arrayWithShape = props[propName]
    PropTypes.checkPropTypes({ arrayWithShape:
        arrayOf(
          shape({
            color: string.isRequired,
            fontSize: number.isRequired,
          }).isRequired
      ).isRequired
    }, {arrayWithShape}, 'prop', componentName);
    if(arrayWithShape.length < 1){
      return new Error(`${propName} is empty`)
    }
  }
}

Using LINQ to concatenate strings

Have you looked at the Aggregate extension method?

var sa = (new[] { "yabba", "dabba", "doo" }).Aggregate((a,b) => a + "," + b);

Why is division in Ruby returning an integer instead of decimal value?

Change the 5 to 5.0. You're getting integer division.

How to make certain text not selectable with CSS

The CSS below stops users from being able to select text.

-webkit-user-select: none; /* Safari */        
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */

To target IE9 downwards the html attribute unselectable must be used instead:

<p unselectable="on">Test Text</p>

Does MS Access support "CASE WHEN" clause if connect with ODBC?

You could use IIF statement like in the next example:

SELECT
   IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
   TABLE_NAME

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

Your mileage may vary (mine sure did), but here's what worked for me (current version of Chrome as of this post is 33.x, and I was interested in 24.x)

  • Visit the Chromium repo proxy lookup site: http://omahaproxy.appspot.com/

  • In the little box called "Revision Lookup" type in the version number. This will translate it to a Subversion revision number. Keep that number in mind.

  • Visit the build repository: http://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html

  • Select the folder corresponding to the OS you're interested in (I have Win x64, but had to use Win,because there was no x64 build corresponding to the version I was looking for).

  • If you select Win, you could be in for a wait - as some of the pages have a lot of entries. Once the page loads, scroll to the folder containing the revision number you identified in an earlier step. If you don't find one, choose the next one up. This is a bit of trial and error to be honest - I had to back up about 50 revisions until I found a version close to the one I was looking for

  • Drill into that folder and download (on the Win version) chrome-win32.zip. That's all you need.

  • Unzip that file and then run chrome.exe

This worked for me and I'm running the latest Chrome alongside version 25, without problems (some profile issues on the older version, but that's neither here nor there). Didn't need to do anything else.

Again, YMMV, but try this solution first since it requires the least amount of tomfoolery.

npm install doesn't create node_modules directory

my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine

Select tableview row programmatically

Like Jaanus told:

Calling this (-selectRowAtIndexPath:animated:scrollPosition:) method does not cause the delegate to receive a tableView:willSelectRowAtIndexPath: or tableView:didSelectRowAtIndexPath: message, nor will it send UITableViewSelectionDidChangeNotification notifications to observers.

So you just have to call the delegate method yourself.

For example:

Swift 3 version:

let indexPath = IndexPath(row: 0, section: 0);
self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
self.tableView(self.tableView, didSelectRowAt: indexPath)

ObjectiveC version:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView selectRowAtIndexPath:indexPath 
                            animated:YES 
                      scrollPosition:UITableViewScrollPositionNone];
[self tableView:self.tableView didSelectRowAtIndexPath:indexPath];

Swift 2.3 version:

 let indexPath = NSIndexPath(forRow: 0, inSection: 0);
 self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
 self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)

Does C have a string type?

C does not support a first class string type.

C++ has std::string

CSS '>' selector; what is it?

As others have said, it's a direct child, but it's worth noting that this is different to just leaving a space... a space is for any descendant.

<div>
  <span>Some text</span>
</div>

div>span would match this, but it would not match this:

<div>
  <p><span>Some text</span></p>
</div>

To match that, you could do div>p>span or div span.