Programs & Examples On #Editview

How to print all key and values from HashMap in Android?

for (Map.Entry<String,String> entry : map.entrySet()) {
  String key = entry.getKey();
  String value = entry.getValue();
  // do stuff
}

Paste text on Android Emulator

On Linux this will paste text directly from the clipboard

adb shell input text "'$(xclip -selection c -o)'"

Also it very useful to create global keyboard shortkey with this command for example Ctrl+Shift+Super+V

How do I make an Android EditView 'Done' button and hide the keyboard when clicked?

I have to point that out as a lot of people can struggle into that without knowing the problem.

If you want the kb to hide when clicking Done, and you set android:imeOptions="actionDone" & android:maxLines="1" without setting your EditText inputType it will NOT work as the default inputType for the EditText is not "text" as a lot of people think.

so, setting only inputType will give you the results you desire whatever what you are setting it to like "text", "number", ...etc.

How to cast an object in Objective-C

((SelectionListViewController *)myEditController).list

More examples:

int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly

How to change Vagrant 'default' machine name?

You can change vagrant default machine name by changing value of config.vm.define.

Here is the simple Vagrantfile which uses getopts and allows you to change the name dynamically:

# -*- mode: ruby -*-
require 'getoptlong'

opts = GetoptLong.new(
  [ '--vm-name',        GetoptLong::OPTIONAL_ARGUMENT ],
)
vm_name        = ENV['VM_NAME'] || 'default'

begin
  opts.each do |opt, arg|
    case opt
      when '--vm-name'
        vm_name = arg
    end
  end
  rescue
end

Vagrant.configure(2) do |config|
  config.vm.define vm_name
  config.vm.provider "virtualbox" do |vbox, override|
    override.vm.box = "ubuntu/wily64"
    # ...
  end
  # ...
end

So to use different name, you can run for example:

vagrant --vm-name=my_name up --no-provision

Note: The --vm-name parameter needs to be specified before up command.

or:

VM_NAME=my_name vagrant up --no-provision

How to make a rest post call from ReactJS code?

I think this way also a normal way. But sorry, I can't describe in English ((

_x000D_
_x000D_
    submitHandler = e => {_x000D_
    e.preventDefault()_x000D_
    console.log(this.state)_x000D_
    fetch('http://localhost:5000/questions',{_x000D_
        method: 'POST',_x000D_
        headers: {_x000D_
            Accept: 'application/json',_x000D_
                    'Content-Type': 'application/json',_x000D_
        },_x000D_
        body: JSON.stringify(this.state)_x000D_
    }).then(response => {_x000D_
            console.log(response)_x000D_
        })_x000D_
        .catch(error =>{_x000D_
            console.log(error)_x000D_
        })_x000D_
    _x000D_
}
_x000D_
_x000D_
_x000D_

https://googlechrome.github.io/samples/fetch-api/fetch-post.html

fetch('url/questions',{ method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(this.state) }).then(response => { console.log(response) }) .catch(error =>{ console.log(error) })

How can I get the last 7 characters of a PHP string?

umh.. like that?

$newstring = substr($dynamicstring, -7);

Project Links do not work on Wamp Server

I believe this is the best solution:

Open index.php in www folder and set

change line 30:$suppress_localhost = true;

to $suppress_localhost = false;

This will ensure the project is prefixed with your local host IP/name

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I had this problem, and turns out the problem was that I had used

new SimpleJdbcCall(jdbcTemplate)
    .withProcedureName("foo")

instead of

new SimpleJdbcCall(jdbcTemplate)
    .withFunctionName("foo")

How to set a timer in android

yes java's timer can be used, but as the question asks for better way (for mobile). Which is explained Here.


For the sake of StackOverflow:

Since Timer creates a new thread it may be considered heavy,

if all you need is to get is a call back while the activity is running a Handler can be used in conjunction with a

Runnable:

private final int interval = 1000; // 1 Second
private Handler handler = new Handler();
private Runnable runnable = new Runnable(){
    public void run() {
        Toast.makeText(MyActivity.this, "C'Mom no hands!", Toast.LENGTH_SHORT).show();
    }
};
...
handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);

or a Message

private final int EVENT1 = 1; 
private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {         
        case Event1:
            Toast.makeText(MyActivity.this, "Event 1", Toast.LENGTH_SHORT).show();
            break;

        default:
            Toast.makeText(MyActivity.this, "Unhandled", Toast.LENGTH_SHORT).show();
            break;
        }
    }
};

...

Message msg = handler.obtainMessage(EVENT1);
handler.sendMessageAtTime(msg, System.currentTimeMillis()+interval);
handler.sendMessageDelayed(msg, interval);

on a side note this approach can be used, if you want to run a piece of code in the UI thread from an another thread.

if you need to get a call back even if your activity is not running then, you can use an AlarmManager

Floating divs in Bootstrap layout

I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding

style="position: relative; bottom: 0px"

to your Widget2 tag. Also try:

style="position: absolute; bottom: 0px"

if you want to snap your widget to the bottom of the screen.

I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.

How do I call Objective-C code from Swift?

After you created a Bridging header, go to Build Setting => Search for "Objective-C Bridging Header".

Just below you will find the ""Objective-C Generated Interface Header Name" file.

Import that file in your view controller.

Example: In my case: "Dauble-Swift.h"

eEter image description here

'Framework not found' in Xcode

Besides from removing the framework from the Podfile and Linked Frameworks and Libraries, I also had to remove the reference to the framework in Other Linker Flags.

Importing the private-key/public-certificate pair in the Java KeyStore

With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.

# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

To verify the contents of the JKS, you can use this command:

keytool -list -v -keystore mykeystore.jks

If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.

jQuery toggle animation

I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

For example:

$('.btnName').click(function() {
 top.$('#panel').toggle(function() {
   $(this).animate({ 
     // style change
   }, 500);
   },
   function() {
   $(this).animate({ 
     // style change back
   }, 500);
 });

Call web service in excel

Yes You Can!

I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:

How you can integrate data from several Web services using Excel and VBA

STEP BY STEP: Consuming Web Services through VBA (Excel or Word)

VBA: Consume Soap Web Services

jquery $(this).id return Undefined

$(this) and this aren't the same. The first represents a jQuery object wrapped around your element. The second is just your element. The id property exists on the element, but not the jQuery object. As such, you have a few options:

  1. Access the property on the element directly:

    this.id

  2. Access it from the jQuery object:

    $(this).attr("id")

  3. Pull the object out of jQuery:

    $(this).get(0).id; // Or $(this)[0].id

  4. Get the id from the event object:

    When events are raised, for instance a click event, they carry important information and references around with them. In your code above, you have a click event. This event object has a reference to two items: currentTarget and target.

    Using target, you can get the id of the element that raised the event. currentTarget would simply tell you which element the event is currently bubbling through. These are not always the same.

    $("#button").on("click", function(e){ console.log( e.target.id ) });

Of all of these, the best option is to just access it directly from this itself, unless you're engaged in a series of nested events, then it might be best to use the event object of each nested event (give them all unique names) to reference elements in higher or lower scopes.

Available text color classes in Bootstrap

There are few more classess in Bootstrap 4 (added in recent versions) not mentioned in other answers.

.text-black-50 and .text-white-50 are 50% transparent.

_x000D_
_x000D_
.text-body {_x000D_
  color: #212529 !important;_x000D_
}_x000D_
_x000D_
.text-black-50 {_x000D_
  color: rgba(0, 0, 0, 0.5) !important;_x000D_
}_x000D_
_x000D_
.text-white-50 {_x000D_
  color: rgba(255, 255, 255, 0.5) !important;_x000D_
}_x000D_
_x000D_
/*DEMO*/_x000D_
p{padding:.5rem}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
_x000D_
<p class="text-body">.text-body</p>_x000D_
<p class="text-black-50">.text-black-50</p>_x000D_
<p class="text-white-50 bg-dark">.text-white-50</p>
_x000D_
_x000D_
_x000D_

How to copy selected lines to clipboard in vim

I have added the following line to my .vimrc

vnoremap <F5> "+y<CR>

This allows you to copy the selected text to the clipboard by pressing F5. You must be in visual mode for this to work.

Why do I always get the same sequence of random numbers with rand()?

There's a lot of answers here, but no-one seems to have really explained why it is that rand() always generates the same sequence given the same seed - or even what the seed is really doing. So here goes.

The rand() function maintains an internal state. Conceptually, you could think of this as a global variable of some type called rand_state. Each time you call rand(), it does two things. It uses the existing state to calculate a new state, and it uses the new state to calculate a number to return to you:

state_t rand_state = INITIAL_STATE;

state_t calculate_next_state(state_t s);
int calculate_return_value(state_t s);

int rand(void)
{
    rand_state = calculate_next_state(rand_state);
    return calculate_return_value(rand_state);
}

Now you can see that each time you call rand(), it's going to make rand_state move one step along a pre-determined path. The random values you see are just based on where you are along that path, so they're going to follow a pre-determined sequence too.

Now here's where srand() comes in. It lets you jump to a different point on the path:

state_t generate_random_state(unsigned int seed);

void srand(unsigned int seed)
{
    rand_state = generate_random_state(seed);
}

The exact details of state_t, calculate_next_state(), calculate_return_value() and generate_random_state() can vary from platform to platform, but they're usually quite simple.

You can see from this that every time your program starts, rand_state is going to start off at INITIAL_STATE (which is equivalent to generate_random_state(1)) - which is why you always get the same sequence if you don't use srand().

How to get text from each cell of an HTML table?

Here's a C# example I just cooked up, loosely based on the answer using CSS selectors, hopefully of use to others for seeing how to setup a ReadOnlyCollection of table rows and iterate over it in MS land at least. I'm looking through a collection of table rows to find a row with an OriginatorsRef (just a string) and a TD with an image that contains a title attribute with Overdue by in it:

    public ReadOnlyCollection<IWebElement> GetTableRows()
    {
        this.iwebElement = GetElement();
        return this.iwebElement.FindElements(By.CssSelector("tbody tr"));
    }

And within my main code:

        ...
        ReadOnlyCollection<IWebElement> TableRows;
        TableRows = f.Grid_Fault.GetTableRows();

        foreach (IWebElement row in TableRows)
        {
            if (row.Text.Contains(CustomTestContext.Current.OriginatorsRef) &&
              row.FindElements(By.CssSelector("td img[title*='Overdue by']")).Count > 0)
                return true;
        }

svn list of files that are modified in local copy

If you only want the filenames and also want any files that have been added (A).

svn st | grep ^[AM] | cut -c9-

Note: The first 7 columns are each one character wide followed by a space then the filename.

How do I use raw_input in Python 3

This works in Python 3.x and 2.x:

# Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))

Get folder up one level

You could do either:

dirname(__DIR__);

Or:

__DIR__ . '/..';

...but in a web server environment you will probably find that you are already working from current file's working directory, so you can probably just use:

'../'

...to reference the directory above. You can replace __DIR__ with dirname(__FILE__) before PHP 5.3.0.

You should also be aware what __DIR__ and __FILE__ refers to:

The full path and filename of the file. If used inside an include, the name of the included file is returned.

So it may not always point to where you want it to.

How to turn on line numbers in IDLE?

Line numbers were added to the IDLE editor two days ago and will appear in the upcoming 3.8.0a3 and later 3.7.5. For new windows, they are off by default, but this can be reversed on the Setting dialog, General tab, Editor section. For existing windows, there is a new Show (Hide) Line Numbers entry on the Options menu. There is currently no hotkey. One can select a line or bloc of lines by clicking on a line or clicking and dragging.

Some people may have missed Edit / Go to Line. The right-click context menu Goto File/Line works on grep (Find in Files) output as well as on trackbacks.

How to set default value for HTML select?

Simplay you can place HTML select attribute to option a like shown below

Define the attributes like selected="selected"

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

Rownum in postgresql

use the limit clausule, with the offset to choose the row number -1 so if u wanna get the number 8 row so use:

limit 1 offset 7

CSS Pseudo-classes with inline styles

You could try https://hacss.io:

<a href="http://www.google.com" class=":hover{text-decoration:none;}">Google</a>

Demo

When to use 'raise NotImplementedError'?

As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.

There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.

Here's a Python 3 example:

class C(abc.ABC):
    @abc.abstractmethod
    def my_abstract_method(self, ...):
        ...

When instantiating C, you'll get an error because my_abstract_method is abstract. You need to implement it in a child class.

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

Subclass C and implement my_abstract_method.

class D(C):
    def my_abstract_method(self, ...):
        ...

Now you can instantiate D.

C.my_abstract_method does not have to be empty. It can be called from D using super().

An advantage of this over NotImplementedError is that you get an explicit Exception at instantiation time, not at method call time.

How to set the font size in Emacs?

Aquamacs:

(set-face-attribute 'default nil :font "Monaco-16" )

From the Emacs Wiki Globally Change the Default Font, it says you can use either of these:

(set-face-attribute 'default nil :font FONT )

(set-frame-font FONT nil t)

Where FONT is something like "Monaco-16", e.g.:

(set-face-attribute 'default nil :font "Monaco-16" )

There was an extra closing parenthesis in the first suggestion on the wiki, which caused an error on startup. I finally noticed the extra closing parenthesis, and I subsequently corrected the suggestion on the wiki. Then both of the suggestions worked for me.

CMake is not able to find BOOST libraries

I'm using this to set up boost from cmake in my CMakeLists.txt. Try something similar (make sure to update paths to your installation of boost).

SET (BOOST_ROOT "/opt/boost/boost_1_57_0")
SET (BOOST_INCLUDEDIR "/opt/boost/boost-1.57.0/include")
SET (BOOST_LIBRARYDIR "/opt/boost/boost-1.57.0/lib")

SET (BOOST_MIN_VERSION "1.55.0")
set (Boost_NO_BOOST_CMAKE ON)
FIND_PACKAGE(Boost ${BOOST_MIN_VERSION} REQUIRED)
if (NOT Boost_FOUND)
  message(FATAL_ERROR "Fatal error: Boost (version >= 1.55) required.")
else()
  message(STATUS "Setting up BOOST")
  message(STATUS " Includes - ${Boost_INCLUDE_DIRS}")
  message(STATUS " Library  - ${Boost_LIBRARY_DIRS}")
  include_directories(${Boost_INCLUDE_DIRS})
  link_directories(${Boost_LIBRARY_DIRS})
endif (NOT Boost_FOUND)

This will either search default paths (/usr, /usr/local) or the path provided through the cmake variables (BOOST_ROOT, BOOST_INCLUDEDIR, BOOST_LIBRARYDIR). It works for me on cmake > 2.6.

"unexpected token import" in Nodejs5 and babel?

Current method is to use:

npm install --save-dev babel-cli babel-preset-env

And then in in .babelrc

{
    "presets": ["env"]
}

this install Babel support for latest version of js (es2015 and beyond) Check out babeljs

Do not forget to add babel-node to your scripts inside package.json use when running your js file as follows.

"scripts": {
   "test": "mocha",
    //Add this line to your scripts
   "populate": "node_modules/babel-cli/bin/babel-node.js" 
},

Now you can npm populate yourfile.js inside terminal.

If you are running windows and running error internal or external command not recognized, use node infront of the script as follow

node node_modules/babel-cli/bin/babel-node.js

Then npm run populate

DataSet panel (Report Data) in SSRS designer is gone

With a report (rdl) file selected in your solution, select View and then Report Data.

It is a shortcut of Ctrl+Alt+D.

enter image description here

How to make Visual Studio copy a DLL file to the output directory?

The details in the comments section above did not work for me (VS 2013) when trying to copy the output dll from one C++ project to the release and debug folder of another C# project within the same solution.

I had to add the following post build-action (right click on the project that has a .dll output) then properties -> configuration properties -> build events -> post-build event -> command line

now I added these two lines to copy the output dll into the two folders:

xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Release
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Debug

Adding images or videos to iPhone Simulator

quit the simulator.

Run simulator from the dock by clicking on it.

Drag & drop the image into simulator which you want to add.

it will open image in safari .

tap and hold the image and click the save option.

then open gallery and you will see the image which u had saved recently.

PHP function to get the subdomain of a URL

I'm doing something like this

$url = https://en.example.com

$splitedBySlash = explode('/', $url);
$splitedByDot = explode('.', $splitedBySlash[2]);

$subdomain = $splitedByDot[0];

css absolute position won't work with margin-left:auto margin-right: auto

if the absolute element has a width,you can use the code below

.divtagABS{
    width:300px;
    positon:absolute;
    left:0;
    right:0;
    margin:0 auto;
}

Java Set retain order?

A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

if your application accepts errors raise from Oracle, then you can use it. we have an application, each time when an error happens, we call raise_application_error, the application will popup a red box to show the error message we provide through this method.

When using dotnet code, I just use "raise", dotnet exception mechanisim will automatically capture the error passed by Oracle ODP and shown inside my catch exception code.

vue.js 'document.getElementById' shorthand

Theres no shorthand way in vue 2.

Jeff's method seems already deprecated in vue 2.

Heres another way u can achieve your goal.

_x000D_
_x000D_
 var app = new Vue({_x000D_
    el:'#app',_x000D_
    methods: {    _x000D_
        showMyDiv() {_x000D_
           console.log(this.$refs.myDiv);_x000D_
        }_x000D_
    }_x000D_
    _x000D_
   });
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id='app'>_x000D_
   <div id="myDiv" ref="myDiv"></div>_x000D_
   <button v-on:click="showMyDiv" >Show My Div</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I remove leading whitespace in Python?

The function strip will remove whitespace from the beginning and end of a string.

my_str = "   text "
my_str = my_str.strip()

will set my_str to "text".

How can I simulate mobile devices and debug in Firefox Browser?

You can use tools own browser (Firefox, IE, Chrome...) to debug your JavaScript.

As for resizing, Firefox/Chrome has own resources accessible via Ctrl + Shift + I OR F12. Going tab "style editor" and clicking "adaptive/responsive design" icon.

Old Firefox versions

Old Firefox

New Firefox/Firebug

Firefox

Chrome

Chrome

*Another way is to install an addon like "Web Developer"

How to get all of the IDs with jQuery?

It's a late answer but now there is an easy way. Current version of jquery lets you search if attribute exists. For example

$('[id]')

will give you all the elements if they have id. If you want all spans with id starting with span you can use

$('span[id^="span"]')

How can I use Google's Roboto font on a website?

This is what I did to get the woff2 files I wanted for static deployment without having to use a CDN

TEMPORARILY add the cdn for the css to load the roboto fonts into index.html and let the page load. from google dev tools look at sources and expand the fonts.googleapis.com node and view the content of the css?family=Roboto:300,400,500&display=swap file and copy the content. Put this content in a css file in your assets directory.

In the css file, remove all the greek, cryllic and vietnamese stuff.

Look at the lines in this css file that are similar to:

    src: local('Roboto Light'), local('Roboto-Light'), url(https://fonts.gstatic.com/s/roboto/v20/KFOlCnqEu92Fr1MmSU5fBBc4.woff2) format('woff2');

copy the link address and paste it in your browser, it will download the font. Put this font into your assets folder and rename it here, as well as in the css file. Do this to the other links, I had 6 unique woff2 files.

I followed the same steps for material icons.

Now go back and comment the line where you call the cdn and instead use use the new css file you created.

Auto reloading python Flask app upon code changes

If you are talking about test/dev environments, then just use the debug option. It will auto-reload the flask app when a code change happens.

app.run(debug=True)

Or, from the shell:

$ export FLASK_DEBUG=1
$ flask run

http://flask.pocoo.org/docs/quickstart/#debug-mode

How to compare if two structs, slices or maps are equal?

Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb

func compare(a, b T) bool {
  if &a == &b {
    return true
  }
  if a.X != b.X || a.Y != b.Y {
    return false
  }
  if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
    return false
  }
  for i, v := range a.Z {
    if b.Z[i] != v {
      return false
    }
  }
  for k, v := range a.M {
    if b.M[k] != v {
      return false
    }
  }
  return true
}

How to create threads in nodejs

If you're using Rx, it's rather simple to plugin in rxjs-cluster to split work into parallel execution. (disclaimer: I'm the author)

https://www.npmjs.com/package/rxjs-cluster

How to define static property in TypeScript interface

I found a way to do this (without decorators) for my specific use case.

The important part that checks for static members is IObjectClass and using cls: IObjectClass<T> in the createObject method:

//------------------------
// Library
//------------------------
interface IObject {
  id: number;
}
interface IObjectClass<T> {
  new(): T;
  table_name: string;
}
function createObject<T extends IObject>(cls: IObjectClass<T>, data:Partial<T>):T {
  let obj:T = (<any>Object).assign({},
    data,
    {
      id: 1,
      table_name: cls.table_name,
    }
  )
  return obj;
}

//------------------------
// Implementation
//------------------------
export class User implements IObject {
  static table_name: string = 'user';
  id: number;
  name: string;
}

//------------------------
// Application
//------------------------
let user = createObject(User, {name: 'Jimmy'});
console.log(user.name);

Extracting the last n characters from a string in R

I used the following code to get the last character of a string.

    substr(output, nchar(stringOfInterest), nchar(stringOfInterest))

You can play with the nchar(stringOfInterest) to figure out how to get last few characters.

How to check if a function exists on a SQL database

Why not just:

IF object_id('YourFunctionName', 'FN') IS NOT NULL
BEGIN
    DROP FUNCTION [dbo].[YourFunctionName]
END
GO

The second argument of object_id is optional, but can help to identify the correct object. There are numerous possible values for this type argument, particularly:

  • FN : Scalar function
  • IF : Inline table-valued function
  • TF : Table-valued-function
  • FS : Assembly (CLR) scalar-function
  • FT : Assembly (CLR) table-valued function

How can I quickly sum all numbers in a file?

You can do it with Alacon - command-line utility for Alasql database.

It works with Node.js, so you need to install Node.js and then Alasql package:

To calculate sum from TXT file you can use the following command:

> node alacon "SELECT VALUE SUM([0]) FROM TXT('mydata.txt')"

LIKE operator in LINQ

Typically you use String.StartsWith/EndsWith/Contains. For example:

var portCode = Database.DischargePorts
                       .Where(p => p.PortName.Contains("BALTIMORE"))
                       .Single()
                       .PortCode;

I don't know if there's a way of doing proper regular expressions via LINQ to SQL though. (Note that it really does depend on which provider you're using - it would be fine in LINQ to Objects; it's a matter of whether the provider can convert the call into its native query format, e.g. SQL.)

EDIT: As BitKFu says, Single should be used when you expect exactly one result - when it's an error for that not to be the case. Options of SingleOrDefault, FirstOrDefault or First should be used depending on exactly what's expected.

Unused arguments in R

You could use dots: ... in your function definition.

myfun <- function(a, b, ...){
  cat(a,b)
}

myfun(a=4,b=7,hello=3)

# 4 7

Newline in JLabel

You can do

JLabel l = new JLabel("<html><p>Hello World! blah blah blah</p></html>", SwingConstants.CENTER);

and it will automatically wrap it where appropriate.

How to redirect 404 errors to a page in ExpressJS?

The 404 page should be set up just before the call to app.listen.Express has support for * in route paths. This is a special character which matches anything. This can be used to create a route handler that matches all requests.

app.get('*', (req, res) => {
  res.render('404', {
    title: '404',
    name: 'test',
    errorMessage: 'Page not found.'
  })
})

Virtual Serial Port for Linux

Use socat for this:

For example:

socat PTY,link=/dev/ttyS10 PTY,link=/dev/ttyS11

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

In your app/config/parameters.yml

# This file is auto-generated during the composer install
parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: 3306
    database_name: symfony
    database_user: root
    database_password: "your_password"
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    locale: en
    secret: ThisTokenIsNotSoSecretChangeIt

The value of database_password should be within double or single quotes as in: "your_password" or 'your_password'.

I have seen most of users experiencing this error because they are using password with leading zero or numeric values.

How to validate phone number in laravel 5.2?

One possible solution would to use regex.

'phone' => 'required|regex:/(01)[0-9]{9}/'

This will check the input starts with 01 and is followed by 9 numbers. By using regex you don't need the numeric or size validation rules.

If you want to reuse this validation method else where, it would be a good idea to create your own validation rule for validating phone numbers.

Docs: Custom Validation

In your AppServiceProvider's boot method:

Validator::extend('phone_number', function($attribute, $value, $parameters)
{
    return substr($value, 0, 2) == '01';
});

This will allow you to use the phone_number validation rule anywhere in your application, so your form validation could be:

'phone' => 'required|numeric|phone_number|size:11'

In your validator extension you could also check if the $value is numeric and 11 characters long.

What is the difference between & and && in Java?

& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false

(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.

(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).

EDIT:

exprA | exprB <-- this means evaluate exprA then evaluate exprB then do the |.

exprA || exprB <-- this means evaluate exprA and only if this is false then evaluate exprB and do the ||.

How to Deserialize JSON data?

Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.

Step 2: Let's say you're using Java. You would use JSONArray like this:

JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
    JSONArray myInteriorArray=myArray.getJSONArray(i);
    if (i==0) {
        //this is the first one and is special because it holds the name of the query.
    }else{
        //do your stuff
        String stateCode=myInteriorArray.getString(0);
        String stateName=myInteriorArray.getString(1);
    }
}

Dynamically change bootstrap progress bar value when checkboxes checked

Bootstrap 4 progress bar

<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>

Javascript

change progress bar on next/previous page actions

var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);        
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever?

Override service method like this:

protected void service(HttpServletRequest request, HttpServletResponse   response) throws ServletException, IOException {
        doPost(request, response);
}

And Voila!

When to use Interface and Model in TypeScript / Angular

Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure. For this you can cast your content to this interface:

this.http.get('...')
    .map(res => <Product[]>res.json());

See these questions:

You can do something similar with class but the main differences with class are that they are present at runtime (constructor function) and you can define methods in them with processing. But, in this case, you need to instantiate objects to be able to use them:

this.http.get('...')
    .map(res => {
      var data = res.json();
      return data.map(d => {
        return new Product(d.productNumber,
          d.productName, d.productDescription);
      });
    });

How to create a hash or dictionary object in JavaScript

if( a['desiredKey'] !== undefined )
{
   // it exists
}

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

The problem is that you're trying to print an unicode character to a possibly non-unicode terminal. You need to encode it with the 'replace option before printing it, e.g. print ch.encode(sys.stdout.encoding, 'replace').

JS map return object

Use .map without return in simple way. Also start using let and const instead of var because let and const is more recommended

_x000D_
_x000D_
const rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
const launchOptimistic = rockets.map(elem => (_x000D_
  {_x000D_
    country: elem.country,_x000D_
    launches: elem.launches+10_x000D_
  } _x000D_
));_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
_x000D_
_x000D_

Finding elements not in a list

No, z is undefined. item contains a list of integers.

I think what you're trying to do is this:

#z defined elsewhere
item = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in item:
  if i not in z: print i

As has been stated in other answers, you may want to try using sets.

Curl Command to Repeat URL Request

You could use URL sequence substitution with a dummy query string (if you want to use CURL and save a few keystrokes):

curl http://www.myurl.com/?[1-20]

If you have other query strings in your URL, assign the sequence to a throwaway variable:

curl http://www.myurl.com/?myVar=111&fakeVar=[1-20]

Check out the URL section on the man page: https://curl.haxx.se/docs/manpage.html

How to change the current URL in javascript?

Even it is not a good way of doing what you want try this hint: var url = MUST BE A NUMER FIRST

function nextImage (){
url = url + 1;  
location.href='http://mywebsite.com/' + url+'.html';
}

What is the purpose of the "final" keyword in C++11 for functions?

Nothing to add to the semantic aspects of "final".

But I'd like to add to chris green's comment that "final" might become a very important compiler optimization technique in the not so distant future. Not only in the simple case he mentioned, but also for more complex real-world class hierarchies which can be "closed" by "final", thus allowing compilers to generate more efficient dispatching code than with the usual vtable approach.

One key disadvantage of vtables is that for any such virtual object (assuming 64-bits on a typical Intel CPU) the pointer alone eats up 25% (8 of 64 bytes) of a cache line. In the kind of applications I enjoy to write, this hurts very badly. (And from my experience it is the #1 argument against C++ from a purist performance point of view, i.e. by C programmers.)

In applications which require extreme performance, which is not so unusual for C++, this might indeed become awesome, not requiring to workaround this problem manually in C style or weird Template juggling.

This technique is known as Devirtualization. A term worth remembering. :-)

There is a great recent speech by Andrei Alexandrescu which pretty well explains how you can workaround such situations today and how "final" might be part of solving similar cases "automatically" in the future (discussed with listeners):

http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-Quickly

How do you copy and paste into Git Bash

The way I do this is to hold Alt then press Space, then E and finally P.

On Windows Alt jumps to the window menu, Space opens it, E selects Edit and P executes the Paste command.

Get these correct in succession and you can paste a snippet in under 2 seconds.

Parse JSON String to JSON Object in C#.NET

Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.

It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.

And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D

There is a System.Json.dll you should add to your project References.

-Jesse

Binary Data in JSON String. Something better than Base64

Data type really concerns. I have tested different scenarios on sending the payload from a RESTful resource. For encoding I have used Base64(Apache) and for compression GZIP(java.utils.zip.*).The payload contains information about film,an image and an audio file. I have compressed and encoded the image and audio files which drastically degraded the performance. Encoding before compression turned out well. Image and audio content were sent as encoded and compressed bytes [] .

How can I get a first element from a sorted list?

Matthew's answer is correct:

list.get(0);

To do what you tried:

list[0];

you'll have to wait until Java 7 is released:

devoxx conference http://img718.imageshack.us/img718/11/capturadepantalla201003cg.png

Here's an interesting presentation by Mark Reinhold about Java 7

It looks like parleys site is currently down, try later :(

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

How to express a NOT IN query with ActiveRecord/Rails?

Here is a more complex "not in" query, using a subquery in rails 4 using squeel. Of course very slow compared to the equivalent sql, but hey, it works.

    scope :translations_not_in_english, ->(calmapp_version_id, language_iso_code){
      join_to_cavs_tls_arr(calmapp_version_id).
      joins_to_tl_arr.
      where{ tl1.iso_code == 'en' }.
      where{ cavtl1.calmapp_version_id == my{calmapp_version_id}}.
      where{ dot_key_code << (Translation.
        join_to_cavs_tls_arr(calmapp_version_id).
        joins_to_tl_arr.    
        where{ tl1.iso_code == my{language_iso_code} }.
        select{ "dot_key_code" }.all)}
    }

The first 2 methods in the scope are other scopes which declare the aliases cavtl1 and tl1. << is the not in operator in squeel.

Hope this helps someone.

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

In case of Request to a REST Service:

You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:

@CrossOrigin(origins = "http://localhost:8080")

Very good tutorial: https://spring.io/guides/gs/rest-service-cors/

Convert Xml to Table SQL Server

This is the answer, hope it helps someone :)

First there are two variations on how the xml can be written:

1

<row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row>

Answer:

SELECT  
       Tbl.Col.value('IdInvernadero[1]', 'smallint'),  
       Tbl.Col.value('IdProducto[1]', 'smallint'),  
       Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
       Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
       Tbl.Col.value('Cantidad[1]', 'int'),
       Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM   @xml.nodes('//row') Tbl(Col)  

2.

<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />                         
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />

Answer:

SELECT  
       Tbl.Col.value('@IdInvernadero', 'smallint'),  
       Tbl.Col.value('@IdProducto', 'smallint'),  
       Tbl.Col.value('@IdCaracteristica1', 'smallint'),
       Tbl.Col.value('@IdCaracteristica2', 'smallint'),
       Tbl.Col.value('@Cantidad', 'int'),
       Tbl.Col.value('@Folio', 'varchar(7)')

FROM   @xml.nodes('//row') Tbl(Col)

Taken from:

  1. http://kennyshu.blogspot.com/2007/12/convert-xml-file-to-table-in-sql-2005.html

  2. http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx

Possible heap pollution via varargs parameter

When you use varargs, it can result in the creation of an Object[] to hold the arguments.

Due to escape analysis, the JIT can optimise away this array creation. (One of the few times I have found it does so) Its not guaranteed to be optimised away, but I wouldn't worry about it unless you see its an issue in your memory profiler.

AFAIK @SafeVarargs suppresses a warning by the compiler and doesn't change how the JIT behaves.

Have bash script answer interactive prompts

If you only have Y to send :

$> yes Y |./your_script

If you only have N to send :

$> yes N |./your_script

Sending HTML Code Through JSON

All string data must be UTF-8 encoded.

$out = array(
   'render' => utf8_encode($renderOutput), 
   'text' => utf8_encode($textOutput)
);

$out = json_encode($out);
die($out);

Save ArrayList to SharedPreferences

/**
 *     Save and get ArrayList in SharedPreference
 */

JAVA:

public void saveArrayList(ArrayList<String> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply();    

}

public ArrayList<String> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    return gson.fromJson(json, type);
}

Kotlin

fun saveArrayList(list: java.util.ArrayList<String?>?, key: String?) {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
    val editor: Editor = prefs.edit()
    val gson = Gson()
    val json: String = gson.toJson(list)
    editor.putString(key, json)
    editor.apply()
}

fun getArrayList(key: String?): java.util.ArrayList<String?>? {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity)
    val gson = Gson()
    val json: String = prefs.getString(key, null)
    val type: Type = object : TypeToken<java.util.ArrayList<String?>?>() {}.getType()
    return gson.fromJson(json, type)
}

What Language is Used To Develop Using Unity

As far as I know, you can go with c#.

You can also use the obscure language "Boo". (Found at https://boo-language.github.io/)

In the past (before about 2012) it was possible to use a strange variant of Java but that is now deprecated and does not work.

Note that Unity builds to Android / iOS, and many other platforms. The fact that iOS programming uses objective-c or Swift, is, completely irrelevant at the Unity3D level. Unity is programmed using c#.

PHP: Split a string in to an array foreach char

You can access a string using [], as you do for arrays:

$stringLength = strlen($str);
for ($i = 0; $i < $stringLength; $i++)
    $char = $str[$i];

jQuery $.cookie is not a function

You should add first jquery.cookie.js then add your js or jQuery where you are using that function.

When browser loads the webpage first it loads this jquery.cookie.js and after then you js or jQuery and now that function is available for use

Export to csv/excel from kibana

FYI : How to download data in CSV from Kibana:

In Kibana--> 1. Go to 'Discover' in left side

  1. Select Index Field (based on your dashboard data) (*** In case if you are not sure which index to select-->go to management tab-->Saved Objects-->Dashboard-->select dashboard name-->scroll down to JSON-->you will see the Index name )

  2. left side you see all the variables available in the data-->click over the variable name that you want to have in csv-->click add-->this variable will be added on the right side of the columns avaliable

  3. Top right section of the kibana-->there is the time filter-->click -->select the duration for which you want the csv

  4. Top upper right -->Reporting-->save this time/variable selection with a new report-->click generate CSV

  5. Go to 'Management' in left side--> 'Reporting'-->download your csv

How do I plot only a table in Matplotlib?

This is another option to write a pandas dataframe directly into a matplotlib table:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# hide axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')

df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))

ax.table(cellText=df.values, colLabels=df.columns, loc='center')

fig.tight_layout()

plt.show()

enter image description here

Bloomberg BDH function with ISIN

I had the same problem. Here's what I figured out:

=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")

A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.

What's the difference between returning value or Promise.resolve from then()

The only difference is that you're creating an unnecessary promise when you do return Promise.resolve("bbb"). Returning a promise from an onFulfilled() handler kicks off promise resolution. That's how promise chaining works.

CSS3 transition on click using pure CSS

If you want a css only solution you can use active

.crossRotate:active {
   transform: rotate(45deg);
   -webkit-transform: rotate(45deg);
   -ms-transform: rotate(45deg);
}

But the transformation will not persist when the activity moves. For that you need javascript (jquery click and css is the cleanest IMO).

$( ".crossRotate" ).click(function() {
    if (  $( this ).css( "transform" ) == 'none' ){
        $(this).css("transform","rotate(45deg)");
    } else {
        $(this).css("transform","" );
    }
});

Fiddle

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

CSS Box Shadow - Top and Bottom Only

As Kristian has pointed out, good control over z-values will often solve your problems.

If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.

I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:

box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;

This will give you some control over the "amount" of shadow in each direction.

Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.

Hope this was what you were looking for!

Difference between View and ViewGroup in Android

Viewgroup inherits properties of views and does more with other views and viewgroup.

See the Android API: http://developer.android.com/reference/android/view/ViewGroup.html

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You can trigger a file input element by sending it a Javascript click event, e.g.

<input type="file" ... id="file-input">

$("#file-input").click();

You could put this in a click event handler for the image, for instance, then hide the file input with CSS. It'll still work even if it's invisible.

Once you've got that part working, you can set a change event handler on the input element to see when the user puts a file into it. This event handler can create a temporary "blob" URL for the image by using window.URL.createObjectURL, e.g.:

var file = document.getElementById("file-input").files[0];
var blob_url = window.URL.createObjectURL(file);

That URL can be set as the src for an image on the page. (It only works on that page, though. Don't try to save it anywhere.)

Note that not all browsers currently support camera capture. (In fact, most desktop browsers don't.) Make sure your interface still makes sense if the user gets asked to pick a file.

How to copy std::string into std::vector<char>?

std::vector has a constructor that takes two iterators. You can use that:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

If you already have a vector and want to add the characters at the end, you need a back inserter:

std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));

Add/remove class with jquery based on vertical scroll?

Is this value intended? if (scroll <= 500) { ... This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"

How to redirect to a 404 in Rails?

routes.rb
  get '*unmatched_route', to: 'main#not_found'

main_controller.rb
  def not_found
    render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
  end

Expanding a parent <div> to the height of its children

Using something like self-clearing div is perfect for a situation like this. Then you'll just use a class on the parent... like:

<div id="parent" class="clearfix">

Git undo changes in some files

There are three basic ways to do this depending on what you have done with the changes to the file A. If you have not yet added the changes to the index or committed them, then you just want to use the checkout command - this will change the state of the working copy to match the repository:

git checkout A

If you added it to the index already, use reset:

git reset A

If you had committed it, then you use the revert command:

# the -n means, do not commit the revert yet
git revert -n <sha1>
# now make sure we are just going to commit the revert to A
git reset B
git commit

If on the other hand, you had committed it, but the commit involved rather a lot of files that you do not also want to revert, then the above method might involve a lot of "reset B" commands. In this case, you might like to use this method:

# revert, but do not commit yet
git revert -n <sha1>
# clean all the changes from the index
git reset
# now just add A
git add A
git commit

Another method again, requires the use of the rebase -i command. This one can be useful if you have more than one commit to edit:

# use rebase -i to cherry pick the commit you want to edit
# specify the sha1 of the commit before the one you want to edit
# you get an editor with a file and a bunch of lines starting with "pick"
# change the one(s) you want to edit to "edit" and then save the file
git rebase -i <sha1>
# now you enter a loop, for each commit you set as "edit", you get to basically redo that commit from scratch
# assume we just picked the one commit with the erroneous A commit
git reset A
git commit --amend
# go back to the start of the loop
git rebase --continue

json.dumps vs flask.jsonify

consider

data={'fld':'hello'}

now

jsonify(data)

will yield {'fld':'hello'} and

json.dumps(data)

gives

"<html><body><p>{'fld':'hello'}</p></body></html>"

Calling a parent window function from an iframe

parent.abc() will only work on same domain due to security purposes. i tried this workaround and mine worked perfectly.

<head>
    <script>
    function abc() {
        alert("sss");
    }

    // window of the iframe
    var innerWindow = document.getElementById('myFrame').contentWindow;
    innerWindow.abc= abc;

    </script>
</head>
<body>
    <iframe id="myFrame">
        <a onclick="abc();" href="#">Click Me</a>
    </iframe>
</body>

Hope this helps. :)

Pointer to 2D arrays in C

Both your examples are equivalent. However, the first one is less obvious and more "hacky", while the second one clearly states your intention.

int (*pointer)[280];
pointer = tab1;

pointer points to an 1D array of 280 integers. In your assignment, you actually assign the first row of tab1. This works since you can implicitly cast arrays to pointers (to the first element).

When you are using pointer[5][12], C treats pointer as an array of arrays (pointer[5] is of type int[280]), so there is another implicit cast here (at least semantically).

In your second example, you explicitly create a pointer to a 2D array:

int (*pointer)[100][280];
pointer = &tab1;

The semantics are clearer here: *pointer is a 2D array, so you need to access it using (*pointer)[i][j].

Both solutions use the same amount of memory (1 pointer) and will most likely run equally fast. Under the hood, both pointers will even point to the same memory location (the first element of the tab1 array), and it is possible that your compiler will even generate the same code.

The first solution is "more advanced" since one needs quite a deep understanding on how arrays and pointers work in C to understand what is going on. The second one is more explicit.

How do I convert from a string to an integer in Visual Basic?

Convert.ToIntXX doesn't like being passed strings of decimals.

To be safe use

Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))

Fail to create Android virtual Device, "No system image installed for this Target"

If you use Android Studio .Open the SDK-Manager, checked "Show Package Details" you will find out "Android Wear ARM EABI v7a System Image" download it , success !

HTML5 video - show/hide controls programmatically

CARL LANGE also showed how to get hidden, autoplaying audio in html5 on a iOS device. Works for me.

In HTML,

<div id="hideme">
    <audio id="audioTag" controls>
        <source src="/path/to/audio.mp3">
    </audio>
</div>

with JS

<script type="text/javascript">
window.onload = function() {
    var audioEl = document.getElementById("audioTag");
    audioEl.load();
    audioEl.play();
};
</script>

In CSS,

#hideme {display: none;}

How to use table variable in a dynamic sql statement?

On SQL Server 2008+ it is possible to use Table Valued Parameters to pass in a table variable to a dynamic SQL statement as long as you don't need to update the values in the table itself.

So from the code you posted you could use this approach for @TSku but not for @RelPro

Example syntax below.

CREATE TYPE MyTable AS TABLE 
( 
Foo int,
Bar int
);
GO


DECLARE @T AS MyTable;

INSERT INTO @T VALUES (1,2), (2,3)

SELECT *,
        sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM @T

EXEC sp_executesql
  N'SELECT *,
        sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
    FROM @T',
  N'@T MyTable READONLY',
  @T=@T 

The physloc column is included just to demonstrate that the table variable referenced in the child scope is definitely the same one as the outer scope rather than a copy.

Changing the highlight color when selecting text in an HTML text input

All answers here are correct when it comes to the ::selection pseudo element, and how it works. However, the question does in fact specifically ask how to use it on text inputs.

The only way to do that is to apply the rule via a parent of the input (any parent for that matter):

_x000D_
_x000D_
.parent ::-webkit-selection, [contenteditable]::-webkit-selection {_x000D_
 background: #ffb7b7;_x000D_
}_x000D_
_x000D_
.parent ::-moz-selection, [contenteditable]::-moz-selection {_x000D_
 background: #ffb7b7;_x000D_
}_x000D_
_x000D_
.parent ::selection, [contenteditable]::selection {_x000D_
 background: #ffb7b7;_x000D_
}_x000D_
_x000D_
/* Aesthetics */_x000D_
input, [contenteditable] {_x000D_
  border:1px solid black;_x000D_
  display:inline-block;_x000D_
  width: 150px;_x000D_
  height: 20px;_x000D_
  line-height: 20px;_x000D_
  padding: 3px;_x000D_
}
_x000D_
<span class="parent"><input type="text" value="Input" /></span>_x000D_
<span contenteditable>Content Editable</span>
_x000D_
_x000D_
_x000D_

Undoing accidental git stash pop

Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show them to see the diff and use patch -R to unapply them.

In which conda environment is Jupyter executing?

to show which conda env a notebook is using just type in a cell:

!conda info

if you have grep, a more direct way:

!conda info | grep 'active env'

What is the difference between "::" "." and "->" in c++

You have a pointer to an object. Therefore, you need to access a field of an object that's pointed to by the pointer. To dereference the pointer you use *, and to access a field, you use ., so you can use:

cout << (*kwadrat).val1;

Note that the parentheses are necessary. This operation is common enough that long ago (when C was young) they decided to create a "shorthand" method of doing it:

cout << kwadrat->val1;

These are defined to be identical. As you can see, the -> basically just combines a * and a . into a single operation. If you were dealing directly with an object or a reference to an object, you'd be able to use the . without dereferencing a pointer first:

Kwadrat kwadrat2(2,3,4);

cout << kwadrat2.val1;

The :: is the scope resolution operator. It is used when you only need to qualify the name, but you're not dealing with an individual object at all. This would be primarily to access a static data member:

struct something { 
    static int x; // this only declares `something::x`. Often found in a header
};

int something::x;  // this defines `something::x`. Usually in .cpp/.cc/.C file.

In this case, since x is static, it's not associated with any particular instance of something. In fact, it will exist even if no instance of that type of object has been created. In this case, we can access it with the scope resolution operator:

something::x = 10;

std::cout << something::x;

Note, however, that it's also permitted to access a static member as if it was a member of a particular object:

something s;

s.x = 1;

At least if memory serves, early in the history of C++ this wasn't allowed, but the meaning is unambiguous, so they decided to allow it.

How to calculate an age based on a birthday?

Another clever way from that ancient thread:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;

Cloning an array in Javascript/Typescript

The following line in your code creates a new array, copies all object references from genericItems into that new array, and assigns it to backupData:

this.backupData = this.genericItems.slice();

So while backupData and genericItems are different arrays, they contain the same exact object references.

You could bring in a library to do deep copying for you (as @LatinWarrior mentioned).

But if Item is not too complex, maybe you can add a clone method to it to deep clone the object yourself:

class Item {
  somePrimitiveType: string;
  someRefType: any = { someProperty: 0 };

  clone(): Item {
    let clone = new Item();

    // Assignment will copy primitive types

    clone.somePrimitiveType = this.somePrimitiveType;

    // Explicitly deep copy the reference types

    clone.someRefType = {
      someProperty: this.someRefType.someProperty
    };

    return clone;
  }
}

Then call clone() on each item:

this.backupData = this.genericItems.map(item => item.clone());

Save internal file in my own internal folder in Android

The answer of Mintir4 is fine, I would also do the following to load the file.

FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";

while ((s = r.readLine()) != null) {
    txt += s;
}

r.close();

UICollectionView spacing margins

Modern Swift, Automatic Layout Calculation

While this thread already contains a bunch of useful answers, I want to add a modern Swift version, based on William Hu's answer. It also improves two things:

  • The spacing between different lines will now always match the spacing between items in the same line.
  • By setting a minimum width, the code automatically calculates the number of items in a row and applies that style to the flow layout.

Here's the code:

// Create flow layout
let flow = UICollectionViewFlowLayout()

// Define layout constants
let itemSpacing: CGFloat = 1
let minimumCellWidth: CGFloat = 120
let collectionViewWidth = collectionView!.bounds.size.width

// Calculate other required constants
let itemsInOneLine = CGFloat(Int((collectionViewWidth - CGFloat(Int(collectionViewWidth / minimumCellWidth) - 1) * itemSpacing) / minimumCellWidth))
let width = collectionViewWidth - itemSpacing * (itemsInOneLine - 1)
let cellWidth = floor(width / itemsInOneLine)
let realItemSpacing = itemSpacing + (width / itemsInOneLine - cellWidth) * itemsInOneLine / max(1, itemsInOneLine - 1))

// Apply values
flow.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
flow.itemSize = CGSize(width: cellWidth, height: cellWidth)
flow.minimumInteritemSpacing = realItemSpacing
flow.minimumLineSpacing = realItemSpacing

// Apply flow layout
collectionView?.setCollectionViewLayout(flow, animated: false)

How can strings be concatenated?

you can also do this:

section = "C_type"
new_section = "Sec_%s" % section

This allows you not only append, but also insert wherever in the string:

section = "C_type"
new_section = "Sec_%s_blah" % section

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

I'm using a popup to show the map in a new window. I'm using the following url

https://www.google.com/maps?z=15&daddr=LATITUDE,LONGITUDE

HTML snippet

<a target='_blank' href='https://www.google.com/maps?z=15&daddr=${location.latitude},${location.longitude}'>Calculate route</a>

How to refresh a Page using react-route Link

If you just put '/' in the href it will reload the current window.

_x000D_
_x000D_
<a href="/">
  Reload the page
</a>
_x000D_
_x000D_
_x000D_

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

Here is the solution that worked for us. Not the best but maybe one can benefit.

Background:

  • Our scripts were developed with VS 2013 and used NUnit VS Adapter 2.1..
  • Recently we migrated to VS 2017 and when open the same solution - test wouldn't show in the Test Explorer

Upon Build we would see this message:

[Informational] NUnit Adapter 3.10.0.21: Test discovery starting
[Informational] Assembly contains no NUnit 3.0 tests: C:\ihealautomatedTests\SeleniumTest\bin\x86\Debug\SeleniumTest.dll
[Informational] NUnit Adapter 3.10.0.21: Test discovery complete

Solution (temporary):

  • Uninstall NUnit Adapter 3.10...
  • Install NUnit VS Adapter 2.1..

Now the Tests are shown.

Is there a bash command which counts files?

Here's what I always do:

ls log* | awk 'END{print NR}'

Razor-based view doesn't see referenced assemblies

In my case, the separate project that contained the namespace was a Console Application. Changing it to a Class Library fixed the problem.

NameError: uninitialized constant (rails)

Some things to try:

  1. Restart the rails console; changes to your models will only get picked up by a rails console that is already open if you do > reload! (although I have found this to be unpredictable), or by restarting the console.

  2. Is your model file called "phone_number.rb" and is it in "/app/models"?

  3. You should double-check the "--sandbox" option on your rails console command. AFAIK, this prevents changes. Try it without the switch.

Checking if a SQL Server login already exists

From here

If not Exists (select loginname from master.dbo.syslogins 
    where name = @loginName and dbname = 'PUBS')
Begin
    Select @SqlStatement = 'CREATE LOGIN ' + QUOTENAME(@loginName) + ' 
    FROM WINDOWS WITH DEFAULT_DATABASE=[PUBS], DEFAULT_LANGUAGE=[us_english]')

    EXEC sp_executesql @SqlStatement
End

Parsing PDF files (especially with tables) with PDFBox

http://swftools.org/ these guys have a pdf2swf component. They are also able to show tables. They are also giving the source. So you could possibly check it out.

OTP (token) should be automatically read from the message

Sorry for late reply but still felt like posting my answer if it helps.It works for 6 digits OTP.

    @Override
    public void onOTPReceived(String messageBody)
    {
        Pattern pattern = Pattern.compile(SMSReceiver.OTP_REGEX);
        Matcher matcher = pattern.matcher(messageBody);
        String otp = HkpConstants.EMPTY;
        while (matcher.find())
        {
            otp = matcher.group();
        }
        checkAndSetOTP(otp);
    }
Adding constants here

public static final String OTP_REGEX = "[0-9]{1,6}";

For SMS listener one can follow the below class

public class SMSReceiver extends BroadcastReceiver
{
    public static final String SMS_BUNDLE = "pdus";
    public static final String OTP_REGEX = "[0-9]{1,6}";
    private static final String FORMAT = "format";

    private OnOTPSMSReceivedListener otpSMSListener;

    public SMSReceiver(OnOTPSMSReceivedListener listener)
    {
        otpSMSListener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null)
        {
            Object[] sms_bundle = (Object[]) intentExtras.get(SMS_BUNDLE);
            String format = intent.getStringExtra(FORMAT);
            if (sms_bundle != null)
            {
                otpSMSListener.onOTPSMSReceived(format, sms_bundle);
            }
            else {
                // do nothing
            }
        }
    }

    @FunctionalInterface
    public interface OnOTPSMSReceivedListener
    {
        void onOTPSMSReceived(@Nullable String format, Object... smsBundle);
    }
}

    @Override
    public void onOTPSMSReceived(@Nullable String format, Object... smsBundle)
    {
        for (Object aSmsBundle : smsBundle)
        {
            SmsMessage smsMessage = getIncomingMessage(format, aSmsBundle);
            String sender = smsMessage.getDisplayOriginatingAddress();
            if (sender.toLowerCase().contains(ONEMG))
            {
                getIncomingMessage(smsMessage.getMessageBody());
            } else
            {
                // do nothing
            }
        }
    }

    private SmsMessage getIncomingMessage(@Nullable String format, Object aObject)
    {
        SmsMessage currentSMS;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && format != null)
        {
            currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
        } else
        {
            currentSMS = SmsMessage.createFromPdu((byte[]) aObject);
        }

        return currentSMS;
    }

Converting Go struct to JSON

You need to export the User.name field so that the json package can see it. Rename the name field to Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Output:

{"Name":"Frank"}

Dealing with HTTP content in HTTPS pages

Your worst case scenario isn't as bad as you think.

You are already parsing the RSS feed, so you already have the image URLs. Say you have an image URL like http://otherdomain.com/someimage.jpg. You rewrite this URL as https://mydomain.com/imageserver?url=http://otherdomain.com/someimage.jpg&hash=abcdeafad. This way, the browser always makes request over https, so you get rid of the problems.

The next part - create a proxy page or servlet that does the following -

  1. Read the url parameter from the query string, and verify the hash
  2. Download the image from the server, and proxy it back to the browser
  3. Optionally, cache the image on disk

This solution has some advantages. You don't have to download the image at the time of creating the html. You don't have to store the images locally. Also, you are stateless; the url contains all the information necessary to serve the image.

Finally, the hash parameter is for security; you only want your servlet to serve images for urls you have constructed. So, when you create the url, compute md5(image_url + secret_key) and append it as the hash parameter. Before you serve the request, recompute the hash and compare it to what was passed to you. Since the secret_key is only known to you, nobody else can construct valid urls.

If you are developing in java, the Servlet is just a few lines of code. You should be able to port the code below on any other back-end technology.

/*
targetURL is the url you get from RSS feeds
request and response are wrt to the browser
Assumes you have commons-io in your classpath
*/

protected void proxyResponse (String targetURL, HttpServletRequest request,
 HttpServletResponse response) throws IOException {
    GetMethod get = new GetMethod(targetURL);
    get.setFollowRedirects(true);    
    /*
     * Proxy the request headers from the browser to the target server
     */
    Enumeration headers = request.getHeaderNames();
    while(headers!=null && headers.hasMoreElements())
    {
        String headerName = (String)headers.nextElement();

        String headerValue = request.getHeader(headerName);

        if(headerValue != null)
        {
            get.addRequestHeader(headerName, headerValue);
        }            
    }        

    /*Make a request to the target server*/
    m_httpClient.executeMethod(get);
    /*
     * Set the status code
     */
    response.setStatus(get.getStatusCode());

    /*
     * proxy the response headers to the browser
     */
    Header responseHeaders[] = get.getResponseHeaders();
    for(int i=0; i<responseHeaders.length; i++)
    {
        String headerName = responseHeaders[i].getName();
        String headerValue = responseHeaders[i].getValue();

        if(headerValue != null)
        {
            response.addHeader(headerName, headerValue);
        }
    }

    /*
     * Proxy the response body to the browser
     */
    InputStream in = get.getResponseBodyAsStream();
    OutputStream out = response.getOutputStream();

    /*
     * If the server sends a 204 not-modified response, the InputStream will be null.
     */
    if (in !=null) {
        IOUtils.copy(in, out);
    }    
}

How can I capitalize the first letter of each word in a string using JavaScript?

Or it can be done using replace(), and replace each word's first letter with its "upperCase".

function titleCase(str) {
    return str.toLowerCase().split(' ').map(function(word) {
               return word.replace(word[0], word[0].toUpperCase());
           }).join(' ');
}

titleCase("I'm a little tea pot");

ASP.NET MVC: Custom Validation by DataAnnotation

You could write a custom validation attribute:

public class CombinedMinLengthAttribute: ValidationAttribute
{
    public CombinedMinLengthAttribute(int minLength, params string[] propertyNames)
    {
        this.PropertyNames = propertyNames;
        this.MinLength = minLength;
    }

    public string[] PropertyNames { get; private set; }
    public int MinLength { get; private set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
        var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();
        var totalLength = values.Sum(x => x.Length) + Convert.ToString(value).Length;
        if (totalLength < this.MinLength)
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }
}

and then you might have a view model and decorate one of its properties with it:

public class MyViewModel
{
    [CombinedMinLength(20, "Bar", "Baz", ErrorMessage = "The combined minimum length of the Foo, Bar and Baz properties should be longer than 20")]
    public string Foo { get; set; }
    public string Bar { get; set; }
    public string Baz { get; set; }
}

Setting new value for an attribute using jQuery

Works fine for me

See example here. http://jsfiddle.net/blowsie/c6VAy/

Make sure your jquery is inside $(document).ready function or similar.

Also you can improve your code by using jquery data

$('#amount').data('min','1000');

<div id="amount" data-min=""></div>

Update,

A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/

TypeScript and array reduce function

Just a note in addition to the other answers.

If an initial value is supplied to reduce then sometimes its type must be specified, viz:-

a.reduce(fn, [])

may have to be

a.reduce<string[]>(fn, [])

or

a.reduce(fn, <string[]>[])

Could not load the Tomcat server configuration

A quick solution in eclipse to resolve when Tomcat could not load as per the following error: Tomcat Error

Just refresh the Tomcat folder should do the trick. If it still does not work, delete all files in eclipse under the Tomcat folder, re-copy the server files then refresh the Tomcat folder. Tomcat should restart correctly after that.

Refresh Tomcat folder

How to fix 'Microsoft Excel cannot open or save any more documents'

I had this same issue, there was no issue regarding memory in my server machine, Finally i was able to fix it by following steps

  1. In your application hosting server, go to its "Component Services"
  2. enter image description here

3.Find "Microsoft Excel Application" in right side.

4.Open its properties by right click

5.Under Identity tab select the option interactive user and click Ok button.

Check once again. Hope it helps

NOTE: But now you may end up with another COM error "Retrieving the COM class factory for component...". In that case Just set the Identity to this User and enter the username and password of a user who has sufficient rights. In my case I entered a user of power user group.

How to view method information in Android Studio?

In addition to the answers here you might want to make sure that the documentation is downloaded. To do that go to SDK Manager

enter image description here

and then the SDK Tools tab and make sure Documentation for Android SDK is installed.

enter image description here

If it isn't check the box and click Apply.

How do I get my Maven Integration tests to run

You can follow the maven documentation to run the unit tests with the build and run the integration tests separately.

<project>
    <properties>
        <skipTests>true</skipTests>
    </properties>
    [...]
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.20.1</version>
                <configuration>
                    <skipITs>${skipTests}</skipITs>
                </configuration>
            </plugin>
        </plugins>
    </build>
    [...]
</project>

This will allow you to run with all integration tests disabled by default. To run them, you use this command:

mvn install -DskipTests=false

Check if xdebug is working

in your question you mentioned that your phpinfo was stating that apache was loading xdebug's configuration in /etc/php5/apache2/conf.d/xdebug.ini In many of the instructions online you may note that they ask you to put xdebug config in php.ini (and that is what I did) HOWEVER, if the configuration is set to /etc/php5/apache2/conf.d/xdebug.ini, then you should remove the [XDebug] configuration settings from /etc/php5/apache2/php.ini and put it in /etc/php5/apache2/conf.d/xdebug.ini INSTEAD. Once I removed from /etc/php5/apache2/php.ini and put in /etc/php5/apache2/conf.d/xdebug.ini instead, and restarted apache, it worked!!

Therefore, in your /etc/php5/apache2/conf.d/xdebug.ini, put the following:

[XDebug]
zend_extension="/usr/lib/php5/20121212+lfs/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_port="9000"
xdebug.profiler_enable=1
xdebug.profiler_output_dir="/home/paul/tmp"

xdebug.remote_host="localhost"
xdebug.remote_handler="dbgp";
xdebug.idekey="phpstorm_xdebug"

then remove this from the /etc/php5/apache2/php.ini if you put it there as well.

Then do:

sudo service apache2 restart

Then it should work!!!

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

How to convert Blob to File in JavaScript

This function converts a Blob into a File and it works great for me.

Vanilla JavaScript

function blobToFile(theBlob, fileName){
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

TypeScript (with proper typings)

public blobToFile = (theBlob: Blob, fileName:string): File => {
    var b: any = theBlob;
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    b.lastModifiedDate = new Date();
    b.name = fileName;

    //Cast to a File() type
    return <File>theBlob;
}

Usage

var myBlob = new Blob();

//do stuff here to give the blob some data...

var myFile = blobToFile(myBlob, "my-image.png");

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

How to make HTML open a hyperlink in another window or tab?

the target = _blank is will open in new tab or windows based on browser setting.

To force a new window use javascript onclick all three parts are needed. url, a name, and window width and height size or it will just open in a new tab.

<a onclick="window.open('http://www.starfall.com/','name','width=600,height=400')">Starfall</a>

How do I select which GPU to run a job on?

The problem was caused by not setting the CUDA_VISIBLE_DEVICES variable within the shell correctly.

To specify CUDA device 1 for example, you would set the CUDA_VISIBLE_DEVICES using

export CUDA_VISIBLE_DEVICES=1

or

CUDA_VISIBLE_DEVICES=1 ./cuda_executable

The former sets the variable for the life of the current shell, the latter only for the lifespan of that particular executable invocation.

If you want to specify more than one device, use

export CUDA_VISIBLE_DEVICES=0,1

or

CUDA_VISIBLE_DEVICES=0,1 ./cuda_executable

Debug/run standard java in Visual Studio Code IDE and OS X?

Code Runner Extension will only let you "run" java files.

To truly debug 'Java' files follow the quick one-time setup:

  • Install Java Debugger Extension in VS Code and reload.
  • open an empty folder/project in VS code.
  • create your java file (s).
  • create a folder .vscode in the same folder.
  • create 2 files inside .vscode folder: tasks.json and launch.json
  • copy paste below config in tasks.json:
{
    "version": "2.0.0",
    "type": "shell",
    "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": false,
        "panel": "shared"
    },
    "isBackground": true,
    "tasks": [
        {
            "taskName": "build",
            "args": ["-g", "${file}"],
            "command": "javac"
        }
    ]
}
  • copy paste below config in launch.json:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug Java",
            "type": "java",
            "request": "launch",
            "externalConsole": true,                //user input dosen't work if set it to false :(
            "stopOnEntry": true,
            "preLaunchTask": "build",                 // Runs the task created above before running this configuration
            "jdkPath": "${env:JAVA_HOME}/bin",        // You need to set JAVA_HOME enviroment variable
            "cwd": "${workspaceRoot}",
            "startupClass": "${workspaceRoot}${file}",
            "sourcePath": ["${workspaceRoot}"],   // Indicates where your source (.java) files are
            "classpath": ["${workspaceRoot}"],    // Indicates the location of your .class files
            "options": [],                             // Additional options to pass to the java executable
            "args": []                                // Command line arguments to pass to the startup class
        }

    ],
    "compounds": []
}

You are all set to debug java files, open any java file and press F5 (Debug->Start Debugging).


Tip: *To hide .class files in the side explorer of VS code, open settings of VS code and paste the below config:

"files.exclude": {
        "*.class": true
    }

enter image description here

Can I make a function available in every controller in angular?

AngularJs has "Services" and "Factories" just for problems like yours.These are used to have something global between Controllers, Directives, Other Services or any other angularjs components..You can defined functions, store data, make calculate functions or whatever you want inside Services and use them in AngularJs Components as Global.like

angular.module('MyModule', [...])
  .service('MyService', ['$http', function($http){
    return {
       users: [...],
       getUserFriends: function(userId){
          return $http({
            method: 'GET',
            url: '/api/user/friends/' + userId
          });
       }
       ....
    }
  }])

if you need more

Find More About Why We Need AngularJs Services and Factories

What does the term "Tuple" Mean in Relational Databases?

Tuples are known values which is used to relate the table in relational DB.

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

I've found an issue happen to be with the Firewall. So, make sure your IP is whitelisted and the firewall does not block your connection. You can check connectivity with:

tsql -H somehost.com -p 1433

In my case, the output was:

Error 20009 (severity 9):
  Unable to connect: Adaptive Server is unavailable or does not exist
  OS error 111, "Connection refused"
There was a problem connecting to the server

How to query DATETIME field using only date in Microsoft SQL Server?

This works for me for MS SQL server:

select * from test
where 
year(date) = 2015
and month(date) = 10
and day(date)= 28 ;

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

Also In VS 2015 Community Edition

go to Debug->Options or Tools->Options

and check Debugging->General->Suppress JIT optimization on module load (Managed only)

Query to get only numbers from a string

T-SQL function to read all the integers from text and return the one at the indicated index, starting from left or right, also using a starting search term (optional):

create or alter function dbo.udf_number_from_text(
    @text nvarchar(max),
    @search_term nvarchar(1000) = N'',
    @number_position tinyint = 1,
    @rtl bit = 0
) returns int
as
    begin
        declare @result int = 0;
        declare @search_term_index int = 0;

        if @text is null or len(@text) = 0 goto exit_label;
        set @text = trim(@text);
        if len(@text) = len(@search_term) goto exit_label;

        if len(@search_term) > 0
            begin
                set @search_term_index = charindex(@search_term, @text);
                if @search_term_index = 0 goto exit_label;
            end;

        if @search_term_index > 0
            if @rtl = 0
                set @text = trim(right(@text, len(@text) - @search_term_index - len(@search_term) + 1));
            else
                set @text = trim(left(@text, @search_term_index - 1));
        if len(@text) = 0 goto exit_label;

        declare @patt_number nvarchar(10) = '%[0-9]%';
        declare @patt_not_number nvarchar(10) = '%[^0-9]%';
        declare @number_start int = 1;
        declare @number_end int;
        declare @found_numbers table (id int identity(1,1), val int);

        while @number_start > 0
        begin
            set @number_start = patindex(@patt_number, @text);
            if @number_start > 0
                begin
                    if @number_start = len(@text)
                        begin
                            insert into @found_numbers(val)
                            select cast(substring(@text, @number_start, 1) as int);

                            break;
                        end;
                    else
                        begin
                            set @text = right(@text, len(@text) - @number_start + 1);
                            set @number_end = patindex(@patt_not_number, @text);

                            if @number_end = 0
                                begin
                                    insert into @found_numbers(val)
                                    select cast(@text as int);

                                    break;
                                end;
                            else
                                begin
                                    insert into @found_numbers(val)
                                    select cast(left(@text, @number_end - 1) as int);

                                    if @number_end = len(@text)
                                        break;
                                    else
                                        begin
                                            set @text = trim(right(@text, len(@text) - @number_end));
                                            if len(@text) = 0 break;
                                        end;
                                end;
                        end;
                end;
        end;

        if @rtl = 0
            select @result = coalesce(a.val, 0)
            from (select row_number() over (order by m.id asc) as c_row, m.val
                    from @found_numbers as m) as a
            where a.c_row = @number_position;
        else
            select @result = coalesce(a.val, 0)
            from (select row_number() over (order by m.id desc) as c_row, m.val
                    from @found_numbers as m) as a
            where a.c_row = @number_position;


        exit_label:
            return @result;
    end;

Example:

select dbo.udf_number_from text(N'Text text 10 text, 25 term', N'term',2,1);

returns 10;

"Parameter not valid" exception loading System.Drawing.Image

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
ImageConverter imageConverter = new System.Drawing.ImageConverter();
System.Drawing.Image image = imageConverter.ConvertFrom(fileData) as System.Drawing.Image;
image.Save(imageFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);

HTML-encoding lost when attribute read from input field

var htmlEnDeCode = (function() {
    var charToEntityRegex,
        entityToCharRegex,
        charToEntity,
        entityToChar;

    function resetCharacterEntities() {
        charToEntity = {};
        entityToChar = {};
        // add the default set
        addCharacterEntities({
            '&amp;'     :   '&',
            '&gt;'      :   '>',
            '&lt;'      :   '<',
            '&quot;'    :   '"',
            '&#39;'     :   "'"
        });
    }

    function addCharacterEntities(newEntities) {
        var charKeys = [],
            entityKeys = [],
            key, echar;
        for (key in newEntities) {
            echar = newEntities[key];
            entityToChar[key] = echar;
            charToEntity[echar] = key;
            charKeys.push(echar);
            entityKeys.push(key);
        }
        charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g');
        entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
    }

    function htmlEncode(value){
        var htmlEncodeReplaceFn = function(match, capture) {
            return charToEntity[capture];
        };

        return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
    }

    function htmlDecode(value) {
        var htmlDecodeReplaceFn = function(match, capture) {
            return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
        };

        return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
    }

    resetCharacterEntities();

    return {
        htmlEncode: htmlEncode,
        htmlDecode: htmlDecode
    };
})();

This is from ExtJS source code.

How to hide element label by element id in CSS?

If you don't care about IE6 users, use the equality attribute selector.

label[for="foo"] { display:none; }

Android "elevation" not showing a shadow

If you have a view with no background this line will help you

android:outlineProvider="bounds"

If you have a view with background this line will help you

android:outlineProvider="paddedBounds"

What is the use of hashCode in Java?

A hashcode is a number generated from any object.

This is what allows objects to be stored/retrieved quickly in a Hashtable.

Imagine the following simple example:

On the table in front of you. you have nine boxes, each marked with a number 1 to 9. You also have a pile of wildly different objects to store in these boxes, but once they are in there you need to be able to find them as quickly as possible.

What you need is a way of instantly deciding which box you have put each object in. It works like an index. you decide to find the cabbage so you look up which box the cabbage is in, then go straight to that box to get it.

Now imagine that you don't want to bother with the index, you want to be able to find out immediately from the object which box it lives in.

In the example, let's use a really simple way of doing this - the number of letters in the name of the object. So the cabbage goes in box 7, the pea goes in box 3, the rocket in box 6, the banjo in box 5 and so on.

What about the rhinoceros, though? It has 10 characters, so we'll change our algorithm a little and "wrap around" so that 10-letter objects go in box 1, 11 letters in box 2 and so on. That should cover any object.

Sometimes a box will have more than one object in it, but if you are looking for a rocket, it's still much quicker to compare a peanut and a rocket, than to check a whole pile of cabbages, peas, banjos, and rhinoceroses.

That's a hash code. A way of getting a number from an object so it can be stored in a Hashtable. In Java, a hash code can be any integer, and each object type is responsible for generating its own. Lookup the "hashCode" method of Object.

Source - here

"Error: Main method not found in class MyClass, please define the main method as..."

Other answers are doing a good job of summarizing the requirements of main. I want to gather references to where those requirements are documented.

The most authoritative source is the VM spec (second edition cited). As main is not a language feature, it is not considered in the Java Language Specification.

Another good resource is the documentation for the application launcher itself:

How to create materialized views in SQL Server?

When indexed view is not an option, and quick updates are not necessary, you can create a hack cache table:

select * into cachetablename from myviewname
alter table cachetablename add primary key (columns)
-- OR alter table cachetablename add rid bigint identity primary key
create index...

then sp_rename view/table or change any queries or other views that reference it to point to the cache table.

schedule daily/nightly/weekly/whatnot refresh like

begin transaction
truncate table cachetablename
insert into cachetablename select * from viewname
commit transaction

NB: this will eat space, also in your tx logs. Best used for small datasets that are slow to compute. Maybe refactor to eliminate "easy but large" columns first into an outer view.

is there a 'block until condition becomes true' function in java?

Similar to EboMike's answer you can use a mechanism similar to wait/notify/notifyAll but geared up for using a Lock.

For example,

public void doSomething() throws InterruptedException {
    lock.lock();
    try {
        condition.await(); // releases lock and waits until doSomethingElse is called
    } finally {
        lock.unlock();
    }
}

public void doSomethingElse() {
    lock.lock();
    try {
        condition.signal();
    } finally {
        lock.unlock();
    }
}

Where you'll wait for some condition which is notified by another thread (in this case calling doSomethingElse), at that point, the first thread will continue...

Using Locks over intrinsic synchronisation has lots of advantages but I just prefer having an explicit Condition object to represent the condition (you can have more than one which is a nice touch for things like producer-consumer).

Also, I can't help but notice how you deal with the interrupted exception in your example. You probably shouldn't consume the exception like this, instead reset the interrupt status flag using Thread.currentThread().interrupt.

This because if the exception is thrown, the interrupt status flag will have been reset (it's saying "I no longer remember being interrupted, I won't be able to tell anyone else that I have been if they ask") and another process may rely on this question. The example being that something else has implemented an interruption policy based on this... phew. A further example might be that your interruption policy, rather that while(true) might have been implemented as while(!Thread.currentThread().isInterrupted() (which will also make your code be more... socially considerate).

So, in summary, using Condition is rougly equivalent to using wait/notify/notifyAll when you want to use a Lock, logging is evil and swallowing InterruptedException is naughty ;)

Git error: src refspec master does not match any

You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

 git add a_text_file.txt 

... do:

 git commit -m "Initial commit."

... and those errors should go away.

Rails 4 Authenticity Token

All my tests were working fine. But for some reason I had set my environment variable to non-test:

export RAILS_ENV=something_non_test

I forgot to unset this variable because of which I started getting ActionController::InvalidAuthenticityToken exception.

After unsetting $RAILS_ENV, my tests started working again.

How to connect to a MS Access file (mdb) using C#?

Try this..

using System.Data.OleDb;

OleDbConnection dbConn;

dConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Registration.accdb;");

Java Equivalent of C# async/await?

Java itself has no equivalent features, but third-party libraries exist which offer similar functionality, e.g.Kilim.

What is 'Context' on Android?

Context is an "interface" to the global information about an application environment. In practice, Context is actually an abstract class, whose implementation is provided by the Android system.

It allows access to application-specific resources and classes, as well as up-calls for application-level operations, such as launching activities, broadcasting and receiving intents, etc.

In the following picture, you can see a hierarchy of classes, where Context is the root class of this hierarchy. In particular, it's worth emphasizing that Activity is a descendant of Context.

Activity diagram

C - gettimeofday for computing time?

If you want to measure code efficiency, or in any other way measure time intervals, the following will be easier:

#include <time.h>

int main()
{
   clock_t start = clock();
   //... do work here
   clock_t end = clock();
   double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
   return 0;
}

hth

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

Empty refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty then it would return true.

IsEmpty refers to no value being initialized.

In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty. If you want to see if something is currently in its default value then use Empty.

How do I rename a file using VBScript?

Yes you can do that.
Here I am renaming a .exe file to .txt file

rename a file

Dim objFso  
Set objFso= CreateObject("Scripting.FileSystemObject")  
objFso.MoveFile "D:\testvbs\autorun.exe", "D:\testvbs\autorun.txt"

How many socket connections can a web server handle?

in case of the IPv4 protocol, the server with one IP address that listens on one port only can handle 2^32 IP addresses x 2^16 ports so 2^48 unique sockets. If you speak about a server as a physical machine, and you are able to utilize all 2^16 ports, then there could be maximum of 2^48 x 2^16 = 2^64 unique TCP/IP sockets for one IP address. Please note that some ports are reserved for the OS, so this number will be lower. To sum up:

1 IP and 1 port --> 2^48 sockets

1 IP and all ports --> 2^64 sockets

all unique IPv4 sockets in the universe --> 2^96 sockets

How to get the android Path string to a file on Assets folder?

Just to add on Jacek's perfect solution. If you're trying to do this in Kotlin, it wont work immediately. Instead, you'll want to use this:

@Throws(IOException::class)
fun getSplashVideo(context: Context): File {
    val cacheFile = File(context.cacheDir, "splash_video")
    try {
        val inputStream = context.assets.open("splash_video")
        val outputStream = FileOutputStream(cacheFile)
        try {
            inputStream.copyTo(outputStream)
        } finally {
            inputStream.close()
            outputStream.close()
        }
    } catch (e: IOException) {
        throw IOException("Could not open splash_video", e)
    }
    return cacheFile
}

How can I scale the content of an iframe?

After struggling with this for hours trying to get it to work in IE8, 9, and 10 here's what worked for me.

This stripped-down CSS works in FF 26, Chrome 32, Opera 18, and IE9 -11 as of 1/7/2014:

.wrap
{
    width: 320px;
    height: 192px;
    padding: 0;
    overflow: hidden;
}

.frame
{
    width: 1280px;
    height: 786px;
    border: 0;

    -ms-transform: scale(0.25);
    -moz-transform: scale(0.25);
    -o-transform: scale(0.25);
    -webkit-transform: scale(0.25);
    transform: scale(0.25);

    -ms-transform-origin: 0 0;
    -moz-transform-origin: 0 0;
    -o-transform-origin: 0 0;
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
}

For IE8, set the width/height to match the iframe, and add -ms-zoom to the .wrap container div:

.wrap
{
    width: 1280px; /* same size as frame */
    height: 768px;
    -ms-zoom: 0.25; /* for IE 8 ONLY */
}

Just use your favorite method for browser sniffing to conditionally include the appropriate CSS, see Is there a way to do browser specific conditional CSS inside a *.css file? for some ideas.

IE7 was a lost cause since -ms-zoom did not exist until IE8.

Here's the actual HTML I tested with:

<div class="wrap">
   <iframe class="frame" src="http://time.is"></iframe>
</div>
<div class="wrap">
    <iframe class="frame" src="http://apple.com"></iframe>
</div>

http://jsfiddle.net/esassaman/PnWFY/

Python "expected an indented block"

Your last for statement is missing a body.

Python expects an indented block to follow the line with the for, or to have content after the colon.

The first style is more common, so it says it expects some indented code to follow it. You have an elif at the same indent level.

Remove non-numeric characters (except periods and commas) from a string

You could use filter_var to remove all illegal characters except digits, dot and the comma.

  • The FILTER_SANITIZE_NUMBER_FLOAT filter is used to remove all non-numeric character from the string.
  • FILTER_FLAG_ALLOW_FRACTION is allowing fraction separator " . "
  • The purpose of FILTER_FLAG_ALLOW_THOUSAND to get comma from the string.

Code

$var1 = '12.322,11T';

echo filter_var($var1, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND);

Output

12.322,11

To read more about filter_var() and Sanitize filters

Get value (String) of ArrayList<ArrayList<String>>(); in Java

The right way to iterate on a list inside list is:

//iterate on the general list
for(int i = 0 ; i < collection.size() ; i++) {
    ArrayList<String> currentList = collection.get(i);
    //now iterate on the current list
    for (int j = 0; j < currentList.size(); j++) {
        String s = currentList.get(1);
    }
}

SQL update fields of one table from fields of another one

Try Following

Update A a, B b, SET a.column1=b.column1 where b.id=1

EDITED:- Update more than one column

Update A a, B b, SET a.column1=b.column1, a.column2=b.column2 where b.id=1

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

If you are using maven just do:

mvn eclipse:eclipse -DdownloadSources=true  -DdownloadJavadocs=true

Header and footer in CodeIgniter

You can use your config.php file, and also use the power of helpers in CodeIgniter.

$config['header_css'] = array('style.css','prettyPhoto.css','nivo-slider.css');
$config['header_js']  = array('core.js','core.js',
                              'jquery-1.4.1.min.js',
                              'jquery-slidedeck.pack.lite.js',
                              'jquery-prettyPhoto.js',
                              'jquery.nivo.slider.js');

Source: https://jamshidhashimi.com/dynamically-add-javascript-and-css-files-in-codeigniter-header-page/

How can I use jQuery to move a div across the screen

Just a quick little function I drummed up that moves DIVs from their current spot to a target spot, one pixel step at a time. I tried to comment as best as I could, but the part you're interested in, is in example 1 and example 2, right after [$(function() { // jquery document.ready]. Put your bounds checking code there, and then exit the interval if conditions are met. Requires jQuery.

First the Demo: http://jsfiddle.net/pnYWY/

First the DIVs...

<style>
  .moveDiv {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }

  .moveDivB {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }
</style>


<div class="moveDiv"></div>
<div class="moveDivB"></div>

example 1) Start

// first animation (fire right away)
var myVar = setInterval(function(){
    $(function() { // jquery document.ready

        // returns true if it just took a step
        // returns false if the div has arrived
        if( !move_div_step(55,25,'.moveDiv') )
        {
            // arrived...
            console.log('arrived'); 
            clearInterval(myVar);
        }

    });
},50); // set speed here in ms for your delay

example 2) Delayed Start

// pause and then fire an animation..
setTimeout(function(){
    var myVarB = setInterval(function(){
        $(function() { // jquery document.ready
            // returns true if it just took a step
            // returns false if the div has arrived
            if( !move_div_step(25,55,'.moveDivB') )
            {
                // arrived...
                console.log('arrived'); 
                clearInterval(myVarB);
            }
        });
    },50); // set speed here in ms for your delay
},5000);// set speed here for delay before firing

Now the Function:

function move_div_step(xx,yy,target) // takes one pixel step toward target
{
    // using a line algorithm to move a div one step toward a given coordinate.
    var div_target = $(target);

    // get current x and current y
    var x = div_target.position().left; // offset is relative to document; position() is relative to parent;
    var y = div_target.position().top;

    // if x and y are = to xx and yy (destination), then div has arrived at it's destination.
    if(x == xx && y == yy)
        return false;

    // find the distances travelled
    var dx = xx - x;
    var dy = yy - y;

    // preventing time travel
    if(dx < 0)          dx *= -1;
    if(dy < 0)          dy *= -1;

    // determine speed of pixel travel...
    var sx=1, sy=1;

    if(dx > dy)         sy = dy/dx;
    else if(dy > dx)    sx = dx/dy;

    // find our one...
    if(sx == sy) // both are one..
    {
        if(x <= xx) // are we going forwards?
        {
            x++; y++;
        }
        else  // .. we are going backwards.
        {
            x--; y--;
        }       
    }
    else if(sx > sy) // x is the 1
    {
        if(x <= xx) // are we going forwards..?
            x++;
        else  // or backwards?
            x--;

        y += sy;
    }
    else if(sy > sx) // y is the 1 (eg: for every 1 pixel step in the y dir, we take 0.xxx step in the x
    {
        if(y <= yy) // going forwards?
            y++;
        else  // .. or backwards?
            y--;

        x += sx;
    }

    // move the div
    div_target.css("left", x);
    div_target.css("top",  y);

    return true;
}  // END :: function move_div_step(xx,yy,target)

Cannot change version of project facet Dynamic Web Module to 3.0?

  1. Click on your project folder.
  2. Go to Window > Show View > Navigator
  3. Go to Navigator and expand the .settings folder
  4. Open org.eclipse.wst.common.project.facet.core.xml file

    <?xml version="1.0" encoding="UTF-8"?>
    <faceted-project>
      <fixed facet="wst.jsdt.web"/>
      <installed facet="jst.web" version="2.3"/>
      <installed facet="wst.jsdt.web" version="1.0"/>
      <installed facet="java" version="1.8"/>
    </faceted-project>
    
  5. Change the version like this <installed facet="jst.web" version="3.1"/>

  6. Save
  7. Just update your project. Right Click on The Project Folder > Maven > Update Project > Select the Project and click 'Ok'

Just this worked to me.

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

<body onLoad="self.focus();document.formname.name.focus()" >

formname is <form action="xxx.php" method="POST" name="formname" >
and name is <input type="text" tabindex="1" name="name" />

it works for me, checked using IE and mozilla.
autofocus, somehow didn't work for me.

Converting from byte to int in java

if you want to combine the 4 bytes into a single int you need to do

int i= (rno[0]<<24)&0xff000000|
       (rno[1]<<16)&0x00ff0000|
       (rno[2]<< 8)&0x0000ff00|
       (rno[3]<< 0)&0x000000ff;

I use 3 special operators | is the bitwise logical OR & is the logical AND and << is the left shift

in essence I combine the 4 8-bit bytes into a single 32 bit int by shifting the bytes in place and ORing them together

I also ensure any sign promotion won't affect the result with & 0xff

Difference between subprocess.Popen and os.system

Subprocess is based on popen2, and as such has a number of advantages - there's a full list in the PEP here, but some are:

  • using pipe in the shell
  • better newline support
  • better handling of exceptions

How do I divide so I get a decimal value?

Don't worry about it. In your code, just do the separate / and % operations as you mention, even though it might seem like it's inefficient. Let the JIT compiler worry about combining these operations to get both quotient and remainder in a single machine instruction (as far as I recall, it generally does).

Spring @Transactional - isolation, propagation

You can use like this:

@Transactional(propagation = Propagation.REQUIRES_NEW)
public EventMessage<ModificaOperativitaRapporto> activate(EventMessage<ModificaOperativitaRapporto> eventMessage) {
//here some transaction related code
}

You can use this thing also:

public interface TransactionStatus extends SavepointManager {
    boolean isNewTransaction();
    boolean hasSavepoint();
    void setRollbackOnly();
    boolean isRollbackOnly();
    void flush();
    boolean isCompleted();
}

Maven in Eclipse: step by step installation

Tried every stuff but this one worked .. 1. Eclipse -> Help -> Install New Software. 2. Type " http://download.eclipse.org/releases/indigo/ " & Hit Enter. 3. Expand " Collaboration " tag. 4. Select Maven plugin from there. 5. Click on next . 6. Accept the agreement & click finish. After installing the maven it will ask for restarting the Eclipse, So restart the eclipse again to see the changes.

Thanks Mukesh for Guiding.

'No JUnit tests found' in Eclipse

The solution was, after making a backup of the src/test folder, removing it from the filesystem, then creating it again.

That's after I did the "Remove from build path" hint and it screwed the folders when opening the project in STS 4.

MySQL Update Column +1?

update TABLENAME
set COLUMNNAME = COLUMNNAME + 1
where id = 'YOURID'

PHP Redirect to another page after form submit

Once had this issue, thought it reasonable to share how I resolved it;

I think the way to do that in php is to use the header function as:

header ("Location: exampleFile.php");

You could just enclose that header file in an if statement so that it redirects only when a certain condition is met, as in:

if (isset($_POST['submit'])){   header("Location: exampleFile.php")   }

Hope that helps.

Improving bulk insert performance in Entity framework

Better way is to skip the Entity Framework entirely for this operation and rely on SqlBulkCopy class. Other operations can continue using EF as before.

That increases the maintenance cost of the solution, but anyway helps reduce time required to insert large collections of objects into the database by one to two orders of magnitude compared to using EF.

Here is an article that compares SqlBulkCopy class with EF for objects with parent-child relationship (also describes changes in design required to implement bulk insert): How to Bulk Insert Complex Objects into SQL Server Database

Python Pandas - Find difference between two data frames

A slight variation of the nice @liangli's solution that does not require to change the index of existing dataframes:

newdf = df1.drop(df1.join(df2.set_index('Name').index))

How to deploy a war file in JBoss AS 7?

I built the following ant-task for deployment based on the jboss deployment docs:

<target name="deploy" depends="jboss.environment, buildwar">
    <!-- Build path for deployed war-file -->
    <property name="deployed.war" value="${jboss.home}/${jboss.deploy.dir}/${war.filename}" />

    <!-- remove current deployed war -->
    <delete file="${deployed.war}.deployed" failonerror="false" />
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.undeployed" />
    </waitfor>
    <delete dir="${deployed.war}" />

    <!-- copy war-file -->
    <copy file="${war.filename}" todir="${jboss.home}/${jboss.deploy.dir}" />

    <!-- start deployment -->
    <echo>start deployment ...</echo>
    <touch file="${deployed.war}.dodeploy" />

    <!-- wait for deployment to complete -->
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.deployed" />
    </waitfor>
    <echo>deployment ok!</echo>
</target>

${jboss.deploy.dir} is set to standalone/deployments

How to check if array is not empty?

An easy way is to use Boolean expressions:

if not self.table[5]:
    print('list is empty')
else:
    print('list is not empty')

Or you can use another Boolean expression :

if self.table[5] == []:
    print('list is empty')
else:
    print('list is not empty')

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

Installtion Steps

  1. Download Binary zip archive or tar.gz.
  2. Copy in the respective folder. Example - C:\apache-maven-3.3.9
  3. Add Variable (either user or system) M2_HOME = C:\apache-maven-3.3.9
  4. Add Variable (either user or system) MAVEN_HOME = C:\apache-maven-3.3.9
  5. Update Variable PATH with C:\apache-maven-3.3.9\bin
  6. Open CMD and Type mvn -v or mvn --version it should give the below response

C:\Users\XXXXXXX>mvn --version Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T22:11:4 7+05:30) Maven home: C:\apache-maven-3.3.9 Java version: 1.8.0_40, vendor: Oracle Corporation Java home: C:\Program Files\Java\jdk1.8.0_40\jre Default locale: en_US, platform encoding: Cp1252 OS name: "windows 8", version: "6.2", arch: "amd64", family: "dos"

**Make sure all variables have correct values using echo %M2_HOME% on CMD

data.frame rows to a list

Like this:

xy.list <- split(xy.df, seq(nrow(xy.df)))

And if you want the rownames of xy.df to be the names of the output list, you can do:

xy.list <- setNames(split(xy.df, seq(nrow(xy.df))), rownames(xy.df))

Deep copy of a dict in python

A simpler (in my view) solution is to create a new dictionary and update it with the contents of the old one:

my_dict={'a':1}

my_copy = {}

my_copy.update( my_dict )

my_dict['a']=2

my_dict['a']
Out[34]: 2

my_copy['a']
Out[35]: 1

The problem with this approach is it may not be 'deep enough'. i.e. is not recursively deep. good enough for simple objects but not for nested dictionaries. Here is an example where it may not be deep enough:

my_dict1={'b':2}

my_dict2={'c':3}

my_dict3={ 'b': my_dict1, 'c':my_dict2 }

my_copy = {}

my_copy.update( my_dict3 )

my_dict1['b']='z'

my_copy
Out[42]: {'b': {'b': 'z'}, 'c': {'c': 3}}

By using Deepcopy() I can eliminate the semi-shallow behavior, but I think one must decide which approach is right for your application. In most cases you may not care, but should be aware of the possible pitfalls... final example:

import copy

my_copy2 = copy.deepcopy( my_dict3 )

my_dict1['b']='99'

my_copy2
Out[46]: {'b': {'b': 'z'}, 'c': {'c': 3}}

Flatten list of lists

>>> lis=[[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
>>> [x[0] for x in lis]
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]

Javascript how to parse JSON array

You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.

There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.

By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.

new Image(), how to know if image 100% loaded or not?

Use the load event:

img = new Image();

img.onload = function(){
  // image  has been loaded
};

img.src = image_url;

Also have a look at:

Visual Studio 2015 installer hangs during install?

I've got same problem and unfortunately the accepted answer which suggests killing SecondaryInstaller.exe messed up installing the optional items. What I've done is basically opening the task manager and locate SecondaryInstaller.exe and right click and click on Open file location. Then run SecondaryInstaller.exe as an administrator.

Python: Append item to list N times

For immutable data types:

l = [0] * 100
# [0, 0, 0, 0, 0, ...]

l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]

For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):

l = [{} for x in range(100)]

(The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number> syntax, and thus if you did something like [{}]*100, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.)

If you want to add to an existing list, you can use the extend() method of that list (in conjunction with the generation of a list of things to add via the above techniques):

a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]

Is there a way to instantiate a class by name in Java?

Using newInstance() directly is deprecated as of Java 8. You need to use Class.getDeclaredConstructor(...).newInstance(...) with the corresponding exceptions.

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

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

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

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