Programs & Examples On #Python mode

How to use export with Python on Linux

Not that simple:

python -c "import os; os.putenv('MY_DATA','1233')"
$ echo $MY_DATA # <- empty

But:

python -c "import os; os.putenv('MY_DATA','123'); os.system('bash')"
$ echo $MY_DATA #<- 123

Is there more to an interface than having the correct methods

Interfaces allow statically typed languages to support polymorphism. An Object Oriented purist would insist that a language should provide inheritance, encapsulation, modularity and polymorphism in order to be a fully-featured Object Oriented language. In dynamically-typed - or duck typed - languages (like Smalltalk,) polymorphism is trivial; however, in statically typed languages (like Java or C#,) polymorphism is far from trivial (in fact, on the surface it seems to be at odds with the notion of strong typing.)

Let me demonstrate:

In a dynamically-typed (or duck typed) language (like Smalltalk), all variables are references to objects (nothing less and nothing more.) So, in Smalltalk, I can do this:

|anAnimal|    
anAnimal := Pig new.
anAnimal makeNoise.

anAnimal := Cow new.
anAnimal makeNoise.

That code:

  1. Declares a local variable called anAnimal (note that we DO NOT specify the TYPE of the variable - all variables are references to an object, no more and no less.)
  2. Creates a new instance of the class named "Pig"
  3. Assigns that new instance of Pig to the variable anAnimal.
  4. Sends the message makeNoise to the pig.
  5. Repeats the whole thing using a cow, but assigning it to the same exact variable as the Pig.

The same Java code would look something like this (making the assumption that Duck and Cow are subclasses of Animal:

Animal anAnimal = new Pig();
duck.makeNoise();

anAnimal = new Cow();
cow.makeNoise();

That's all well and good, until we introduce class Vegetable. Vegetables have some of the same behavior as Animal, but not all. For example, both Animal and Vegetable might be able to grow, but clearly vegetables don't make noise and animals cannot be harvested.

In Smalltalk, we can write this:

|aFarmObject|
aFarmObject := Cow new.
aFarmObject grow.
aFarmObject makeNoise.

aFarmObject := Corn new.
aFarmObject grow.
aFarmObject harvest.

This works perfectly well in Smalltalk because it is duck-typed (if it walks like a duck, and quacks like a duck - it is a duck.) In this case, when a message is sent to an object, a lookup is performed on the receiver's method list, and if a matching method is found, it is called. If not, some kind of NoSuchMethodError exception is thrown - but it's all done at runtime.

But in Java, a statically typed language, what type can we assign to our variable? Corn needs to inherit from Vegetable, to support grow, but cannot inherit from Animal, because it does not make noise. Cow needs to inherit from Animal to support makeNoise, but cannot inherit from Vegetable because it should not implement harvest. It looks like we need multiple inheritance - the ability to inherit from more than one class. But that turns out to be a pretty difficult language feature because of all the edge cases that pop up (what happens when more than one parallel superclass implement the same method?, etc.)

Along come interfaces...

If we make Animal and Vegetable classes, with each implementing Growable, we can declare that our Cow is Animal and our Corn is Vegetable. We can also declare that both Animal and Vegetable are Growable. That lets us write this to grow everything:

List<Growable> list = new ArrayList<Growable>();
list.add(new Cow());
list.add(new Corn());
list.add(new Pig());

for(Growable g : list) {
   g.grow();
}

And it lets us do this, to make animal noises:

List<Animal> list = new ArrayList<Animal>();
list.add(new Cow());
list.add(new Pig());
for(Animal a : list) {
  a.makeNoise();
}

The advantage to the duck-typed language is that you get really nice polymorphism: all a class has to do to provide behavior is provide the method. As long as everyone plays nice, and only sends messages that match defined methods, all is good. The downside is that the kind of error below isn't caught until runtime:

|aFarmObject|
aFarmObject := Corn new.
aFarmObject makeNoise. // No compiler error - not checked until runtime.

Statically-typed languages provide much better "programming by contract," because they will catch the two kinds of error below at compile-time:

// Compiler error: Corn cannot be cast to Animal.
Animal farmObject = new Corn();  
farmObject makeNoise();

--

// Compiler error: Animal doesn't have the harvest message.
Animal farmObject = new Cow();
farmObject.harvest(); 

So....to summarize:

  1. Interface implementation allows you to specify what kinds of things objects can do (interaction) and Class inheritance lets you specify how things should be done (implementation).

  2. Interfaces give us many of the benefits of "true" polymorphism, without sacrificing compiler type checking.

How to add colored border on cardview?

As the accepted answer requires you to add a Frame Layout, here how you can do it with material design.

Add this if you haven't already

implementation 'com.google.android.material:material:1.0.0'

Now change to Cardview to MaterialCardView

<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp"

app:strokeWidth="1dp"
app:strokeColor="@color/black">

Now you need to change the activity theme to Theme.Material. If you are using Theme.Appcompact I will suggest you to move to Theme.Material for future projects for having better material design in you app.

    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

I got the same error with vlc component when i changed the framework from 4.5 to 4. but it worked for me when I changed the platform from Any CPU to x86.

jquery : focus to div is not working

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');

JavaScript Nested function

It's perfectly normal in Javascript (and many languages) to have functions inside functions.

Take the time to learn the language, don't use it on the basis that it's similar to what you already know. I'd suggest watching Douglas Crockford's series of YUI presentations on Javascript, with special focus on Act III: Function the Ultimate (link to video download, slides, and transcript)

Maven: add a dependency to a jar by relative path

You can use eclipse to generate a runnable Jar : Export/Runable Jar file

Using ng-if as a switch inside ng-repeat?

This one is noteworthy as well

<div ng-repeat="post in posts" ng-if="post.type=='article'">
  <h1>{{post.title}}</h1>
</div>

How do I determine whether my calculation of pi is accurate?

Undoubtedly, for your purposes (which I assume is just a programming exercise), the best thing is to check your results against any of the listings of the digits of pi on the web.

And how do we know that those values are correct? Well, I could say that there are computer-science-y ways to prove that an implementation of an algorithm is correct.

More pragmatically, if different people use different algorithms, and they all agree to (pick a number) a thousand (million, whatever) decimal places, that should give you a warm fuzzy feeling that they got it right.

Historically, William Shanks published pi to 707 decimal places in 1873. Poor guy, he made a mistake starting at the 528th decimal place.

Very interestingly, in 1995 an algorithm was published that had the property that would directly calculate the nth digit (base 16) of pi without having to calculate all the previous digits!

Finally, I hope your initial algorithm wasn't pi/4 = 1 - 1/3 + 1/5 - 1/7 + ... That may be the simplest to program, but it's also one of the slowest ways to do so. Check out the pi article on Wikipedia for faster approaches.

Tesseract OCR simple example

Ok. I found the solution here tessnet2 fails to load the Ans given by Adam

Apparently i was using wrong version of tessdata. I was following the the source page instruction intuitively and that caused the problem.

it says

Quick Tessnet2 usage

  1. Download binary here, add a reference of the assembly Tessnet2.dll to your .NET project.

  2. Download language data definition file here and put it in tessdata directory. Tessdata directory and your exe must be in the same directory.

After you download the binary, when you follow the link to download the language file, there are many language files. but none of them are right version. you need to select all version and go to next page for correct version (tesseract-2.00.eng)! They should either update download binary link to version 3 or put the the version 2 language file on the first page. Or at least bold mention the fact that this version issue is a big deal!

Anyway I found it. Thanks everyone.

Import regular CSS file in SCSS file?

Looks like this is unimplemented, as of the time of this writing:

https://github.com/sass/sass/issues/193

For libsass (C/C++ implementation), import works for *.css the same way as for *.scss files - just omit the extension:

@import "path/to/file";

This will import path/to/file.css.

See this answer for further details.

See this answer for Ruby implementation (sass gem)

Getting year in moment.js

_x000D_
_x000D_
var year1 = moment().format('YYYY');_x000D_
var year2 = moment().year();_x000D_
_x000D_
console.log('using format("YYYY") : ',year1);_x000D_
console.log('using year(): ',year2);_x000D_
_x000D_
// using javascript _x000D_
_x000D_
var year3 = new Date().getFullYear();_x000D_
console.log('using javascript :',year3);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

HTML Table cellspacing or padding just top / bottom

Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top, padding-bottom, padding-left, and padding-right; or padding: [top] [right] [bottom] [left];).

How do I force my .NET application to run as administrator?

I implemented some code to do it manually:

using System.Security.Principal;
public bool IsUserAdministrator()
{
    bool isAdmin;
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
        isAdmin = false;
    }
    catch (Exception ex)
    {
        isAdmin = false;
    }
    return isAdmin;
}

What is a constant reference? (not a reference to a constant)

This code is ill-formed:

int&const icr=i;

Reference: C++17 [dcl.ref]/1:

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name or decltype-specifier, in which case the cv-qualifiers are ignored.

This rule has been present in all standardized versions of C++. Because the code is ill-formed:

  • you should not use it, and
  • there is no associated behaviour.

The compiler should reject the program; and if it doesn't, the executable's behaviour is completely undefined.

NB: Not sure how none of the other answers mentioned this yet... nobody's got access to a compiler?

How to use JQuery with ReactJS

You should try and avoid jQuery in ReactJS. But if you really want to use it, you'd put it in componentDidMount() lifecycle function of the component.

e.g.

class App extends React.Component {
  componentDidMount() {
    // Jquery here $(...)...
  }

  // ...
}

Ideally, you'd want to create a reusable Accordion component. For this you could use Jquery, or just use plain javascript + CSS.

class Accordion extends React.Component {
  constructor() {
    super();
    this._handleClick = this._handleClick.bind(this);
  }

  componentDidMount() {
    this._handleClick();
  }

  _handleClick() {
    const acc = this._acc.children;
    for (let i = 0; i < acc.length; i++) {
      let a = acc[i];
      a.onclick = () => a.classList.toggle("active");
    }
  }

  render() {
    return (
      <div 
        ref={a => this._acc = a} 
        onClick={this._handleClick}>
        {this.props.children}
      </div>
    )
  }
}

Then you can use it in any component like so:

class App extends React.Component {
  render() {
    return (
      <div>
        <Accordion>
          <div className="accor">
            <div className="head">Head 1</div>
            <div className="body"></div>
          </div>
        </Accordion>
      </div>
    );
  }
}

Codepen link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110 (I changed this link to https ^)

How do I resolve a path relative to an ASP.NET MVC 4 application root?

In the action you can call:

this.Request.PhysicalPath

that returns the physical path in reference to the current controller. If you only need the root path call:

this.Request.PhysicalApplicationPath

Could not reserve enough space for object heap

here is how to fix it:

  • Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System

    Variables->New: Variable name: _JAVA_OPTIONS Variable value: -Xmx512M Variable name: Path
    Variable value: %PATH%;C:\Program Files\Java\jre6\bin;F:\JDK\bin;

Change this to your appropriate path.

Write a number with two decimal places SQL Server

Use Str() Function. It takes three arguments(the number, the number total characters to display, and the number of decimal places to display

  Select Str(12345.6789, 12, 3)

displays: ' 12345.679' ( 3 spaces, 5 digits 12345, a decimal point, and three decimal digits (679). - it rounds if it has to truncate, (unless the integer part is too large for the total size, in which case asterisks are displayed instead.)

for a Total of 12 characters, with 3 to the right of decimal point.

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

Reading app/config/mailphp

Supported : "smtp", "mail", "sendmail"

Depending on your mail utilities installed on your machine, fill in the value of the driver key. I would do

'driver' => 'sendmail',

JavaScript: how to change form action attribute value based on selection?

Is required that you have a form?
If not, then you could use this:

<div>
    <input type="hidden" value="ServletParameter" />
    <input type="button" id="callJavaScriptServlet" onclick="callJavaScriptServlet()" />
</div>

with the following JavaScript:

function callJavaScriptServlet() {
    this.form.action = "MyServlet";
    this.form.submit();
}

How do I list all the columns in a table?

I know it's late but I use this command for Oracle:

select column_name,data_type,data_length from all_tab_columns where TABLE_NAME = 'xxxx' AND OWNER ='xxxxxxxxxx'

How to do a SOAP Web Service call from Java class?

I found a much simpler alternative way to generating soap message. Given a Person Object:

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
  private String name;
  private int age;
  private String address; //setter and getters below
}

Below is a simple Soap Message Generator:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

@Slf4j
public class SoapGenerator {

  protected static final ObjectMapper XML_MAPPER = new XmlMapper()
      .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .registerModule(new JavaTimeModule());

  private static final String SOAP_BODY_OPEN = "<soap:Body>";
  private static final String SOAP_BODY_CLOSE = "</soap:Body>";
  private static final String SOAP_ENVELOPE_OPEN = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
  private static final String SOAP_ENVELOPE_CLOSE = "</soap:Envelope>";

  public static String soapWrap(String xml) {
    return SOAP_ENVELOPE_OPEN + SOAP_BODY_OPEN + xml + SOAP_BODY_CLOSE + SOAP_ENVELOPE_CLOSE;
  }

  public static String soapUnwrap(String xml) {
    return StringUtils.substringBetween(xml, SOAP_BODY_OPEN, SOAP_BODY_CLOSE);
  }
}

You can use by:

 public static void main(String[] args) throws Exception{
        Person p = new Person();
        p.setName("Test");
        p.setAge(12);

        String xml = SoapGenerator.soapWrap(XML_MAPPER.writeValueAsString(p));
        log.info("Generated String");
        log.info(xml);
      }

How to push to History in React Router v4?

Create a custom Router with its own browserHistory:

import React from 'react';
import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

const ExtBrowserRouter = ({children}) => (
  <Router history={history} >
  { children }
  </Router>
);

export default ExtBrowserRouter

Next, on your Root where you define your Router, use the following:

import React from 'react';       
import { /*BrowserRouter,*/ Route, Switch, Redirect } from 'react-router-dom';

//Use 'ExtBrowserRouter' instead of 'BrowserRouter'
import ExtBrowserRouter from './ExtBrowserRouter'; 
...

export default class Root extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <ExtBrowserRouter>
          <Switch>
            ...
            <Route path="/login" component={Login}  />
            ...
          </Switch>
        </ExtBrowserRouter>
      </Provider>
    )
  }
}

Finally, import history where you need it and use it:

import { history } from '../routers/ExtBrowserRouter';
...

export function logout(){
  clearTokens();      
  history.push('/login'); //WORKS AS EXPECTED!
  return Promise.reject('Refresh token has expired');
}

Set TextView text from html-formatted string resource in XML

Escape your HTML tags ...

<resources>
    <string name="somestring">
        &lt;B&gt;Title&lt;/B&gt;&lt;BR/&gt;
        Content
    </string>
</resources>

Getting activity from context in android

  1. No
  2. You can't

There are two different contexts in Android. One for your application (Let's call it the BIG one) and one for each view (let's call it the activity context).

A linearLayout is a view, so you have to call the activity context. To call it from an activity, simply call "this". So easy isn't it?

When you use

this.getApplicationContext();

You call the BIG context, the one that describes your application and cannot manage your view.

A big problem with Android is that a context cannot call your activity. That's a big deal to avoid this when someone begins with the Android development. You have to find a better way to code your class (or replace "Context context" by "Activity activity" and cast it to "Context" when needed).

Regards.


Just to update my answer. The easiest way to get your Activity context is to define a static instance in your Activity. For example

public class DummyActivity extends Activity
{
    public static DummyActivity instance = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // Do some operations here
    }

    @Override
    public void onResume()
    {
        super.onResume();
        instance = this;
    }

    @Override
    public void onPause()
    {
        super.onPause();
        instance = null;
    }
}

And then, in your Task, Dialog, View, you could use that kind of code to get your Activity context:

if (DummyActivity.instance != null)
{
    // Do your operations with DummyActivity.instance
}

Error: Cannot find module 'gulp-sass'

I had the same problem, and I resolve doing this npm update. But I receive the message about permission, so I run:

sudo chwon -R myuser /home/myUserFolder/.config

This set permissions for my user run npm comands like administrator. Then I run this again:

npm update 

and this:

npm install gulp-sass

Then my problem with this was solved.

How to clear Flutter's Build cache?

Same issue with mine.

New to Flutter. I'm using VS build-in terminal to do flutter run, to run the app in iPhone. It gives me error Error when reading 'lib/student_model.dart': No such file..., which is an old code version in my code. I have changed it to lib/model/student_model.dart.

And I search this line 'lib/student_model.dart'in the project, it appears filekernel_snapshot.d` containing it. So, it build the project with old code version.

For me, Flutter clean is not working. Restart VS fix the issue, not sure the problem is due to Flutter or VS?

And I'm wondering if there is some command to just build flutter project without run?

How to force child div to be 100% of parent div's height without specifying parent's height?

using jQuery:

$(function() {
    function unifyHeights() {
        var maxHeight = 0;
        $('#container').children('#navigation, #content').each(function() {
            var height = $(this).outerHeight();
            // alert(height);
            if ( height > maxHeight ) {
                maxHeight = height;
            }
        });
        $('#navigation, #content').css('height', maxHeight);
    }
    unifyHeights();
});

Java - creating a new thread

You need to do two things:

  • Start the thread
  • Wait for the thread to finish (die) before proceeding

ie

one.start();
one.join();

If you don't start() it, nothing will happen - creating a Thread doesn't execute it.

If you don't join) it, your main thread may finish and exit and the whole program exit before the other thread has been scheduled to execute. It's indeterminate whether it runs or not if you don't join it. The new thread may usually run, but may sometimes not run. Better to be certain.

How to remove Left property when position: absolute?

left:auto;

This will default the left back to the browser default.


So if you have your Markup/CSS as:

<div class="myClass"></div>

.myClass
{
  position:absolute;
  left:0;
}

When setting RTL, you could change to:

<div class="myClass rtl"></div>

.myClass
{
  position:absolute;
  left:0;
}
.myClass.rtl
{
  left:auto;
  right:0;
}

How do I read text from the clipboard?

If you don't want to install extra packages, ctypes can get the job done as well.

import ctypes

CF_TEXT = 1

kernel32 = ctypes.windll.kernel32
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
kernel32.GlobalLock.restype = ctypes.c_void_p
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
user32 = ctypes.windll.user32
user32.GetClipboardData.restype = ctypes.c_void_p

def get_clipboard_text():
    user32.OpenClipboard(0)
    try:
        if user32.IsClipboardFormatAvailable(CF_TEXT):
            data = user32.GetClipboardData(CF_TEXT)
            data_locked = kernel32.GlobalLock(data)
            text = ctypes.c_char_p(data_locked)
            value = text.value
            kernel32.GlobalUnlock(data_locked)
            return value
    finally:
        user32.CloseClipboard()

print(get_clipboard_text())

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

public class LmsEmpWfhUtils {    
    private LmsEmpWfhUtils() 
    { 
    // prevents access default paramater-less constructor
    }
}

This prevents the default parameter-less constructor from being used elsewhere in your code.

Exception : AAPT2 error: check logs for details

Seeing your logs :

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ... 1 more Caused by: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details at com.android.builder.png.AaptProcess$NotifierProcessOutput.handleOutput(AaptProcess.java:454) at com.android.builder.png.AaptProcess$NotifierProcessOutput.err(AaptProcess.java:411) at com.android.builder.png.AaptProcess$ProcessOutputFacade.err(AaptProcess.java:332) at com.android.utils.GrabProcessOutput$1.run(GrabProcessOutput.java:104)

I feel some PNG files are corrupted and were not parsed. Sometimes the images have an extension but are not real PNG.

You can check if the images in your project are real PNGs with the below command :

find . -type f -name "*.png" | xargs -L 1 -I{} file  -I {} | grep -v 'image/png; charset=binary$'

After getting the list use this site to convert them to PNG. Then check your build again.

How do I create delegates in Objective-C?

Delegate :- Create

@protocol addToCartDelegate <NSObject>

-(void)addToCartAction:(ItemsModel *)itemsModel isAdded:(BOOL)added;

@end

Send and please assign delegate to view you are sending data

[self.delegate addToCartAction:itemsModel isAdded:YES];

Get raw POST body in Python Flask regardless of Content-Type header

request.stream is the stream of raw data passed to the application by the WSGI server. No parsing is done when reading it, although you usually want request.get_data() instead.

data = request.stream.read()

The stream will be empty if it was previously read by request.data or another attribute.

Difference between static memory allocation and dynamic memory allocation

This is a standard interview question:

Dynamic memory allocation

Is memory allocated at runtime using calloc(), malloc() and friends. It is sometimes also referred to as 'heap' memory, although it has nothing to do with the heap data-structure ref.

int * a = malloc(sizeof(int));

Heap memory is persistent until free() is called. In other words, you control the lifetime of the variable.

Automatic memory allocation

This is what is commonly known as 'stack' memory, and is allocated when you enter a new scope (usually when a new function is pushed on the call stack). Once you move out of the scope, the values of automatic memory addresses are undefined, and it is an error to access them.

int a = 43;

Note that scope does not necessarily mean function. Scopes can nest within a function, and the variable will be in-scope only within the block in which it was declared. Note also that where this memory is allocated is not specified. (On a sane system it will be on the stack, or registers for optimisation)

Static memory allocation

Is allocated at compile time*, and the lifetime of a variable in static memory is the lifetime of the program.

In C, static memory can be allocated using the static keyword. The scope is the compilation unit only.

Things get more interesting when the extern keyword is considered. When an extern variable is defined the compiler allocates memory for it. When an extern variable is declared, the compiler requires that the variable be defined elsewhere. Failure to declare/define extern variables will cause linking problems, while failure to declare/define static variables will cause compilation problems.

in file scope, the static keyword is optional (outside of a function):

int a = 32;

But not in function scope (inside of a function):

static int a = 32;

Technically, extern and static are two separate classes of variables in C.

extern int a; /* Declaration */
int a; /* Definition */

*Notes on static memory allocation

It's somewhat confusing to say that static memory is allocated at compile time, especially if we start considering that the compilation machine and the host machine might not be the same or might not even be on the same architecture.

It may be better to think that the allocation of static memory is handled by the compiler rather than allocated at compile time.

For example the compiler may create a large data section in the compiled binary and when the program is loaded in memory, the address within the data segment of the program will be used as the location of the allocated memory. This has the marked disadvantage of making the compiled binary very large if uses a lot of static memory. It's possible to write a multi-gigabytes binary generated from less than half a dozen lines of code. Another option is for the compiler to inject initialisation code that will allocate memory in some other way before the program is executed. This code will vary according to the target platform and OS. In practice, modern compilers use heuristics to decide which of these options to use. You can try this out yourself by writing a small C program that allocates a large static array of either 10k, 1m, 10m, 100m, 1G or 10G items. For many compilers, the binary size will keep growing linearly with the size of the array, and past a certain point, it will shrink again as the compiler uses another allocation strategy.

Register Memory

The last memory class are 'register' variables. As expected, register variables should be allocated on a CPU's register, but the decision is actually left to the compiler. You may not turn a register variable into a reference by using address-of.

register int meaning = 42;
printf("%p\n",&meaning); /* this is wrong and will fail at compile time. */

Most modern compilers are smarter than you at picking which variables should be put in registers :)

References:

Python memory usage of numpy arrays

The field nbytes will give you the size in bytes of all the elements of the array in a numpy.array:

size_in_bytes = my_numpy_array.nbytes

Notice that this does not measures "non-element attributes of the array object" so the actual size in bytes can be a few bytes larger than this.

Reading a binary file with python

To read a binary file to a bytes object:

from pathlib import Path
data = Path('/path/to/file').read_bytes()  # Python 3.5+

To create an int from bytes 0-3 of the data:

i = int.from_bytes(data[:4], byteorder='little', signed=False)

To unpack multiple ints from the data:

import struct
ints = struct.unpack('iiii', data[:16])

When do you use Java's @Override annotation and why?

Using the @Override annotation acts as a compile-time safeguard against a common programming mistake. It will throw a compilation error if you have the annotation on a method you're not actually overriding the superclass method.

The most common case where this is useful is when you are changing a method in the base class to have a different parameter list. A method in a subclass that used to override the superclass method will no longer do so due the changed method signature. This can sometimes cause strange and unexpected behavior, especially when dealing with complex inheritance structures. The @Override annotation safeguards against this.

How to implement the factory method pattern in C++ correctly

Have you thought about not using a factory at all, and instead making nice use of the type system? I can think of two different approaches which do this sort of thing:

Option 1:

struct linear {
    linear(float x, float y) : x_(x), y_(y){}
    float x_;
    float y_;
};

struct polar {
    polar(float angle, float magnitude) : angle_(angle),  magnitude_(magnitude) {}
    float angle_;
    float magnitude_;
};


struct Vec2 {
    explicit Vec2(const linear &l) { /* ... */ }
    explicit Vec2(const polar &p) { /* ... */ }
};

Which lets you write things like:

Vec2 v(linear(1.0, 2.0));

Option 2:

you can use "tags" like the STL does with iterators and such. For example:

struct linear_coord_tag linear_coord {}; // declare type and a global
struct polar_coord_tag polar_coord {};

struct Vec2 {
    Vec2(float x, float y, const linear_coord_tag &) { /* ... */ }
    Vec2(float angle, float magnitude, const polar_coord_tag &) { /* ... */ }
};

This second approach lets you write code which looks like this:

Vec2 v(1.0, 2.0, linear_coord);

which is also nice and expressive while allowing you to have unique prototypes for each constructor.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

NEW WAY SINCE VERSION 0.7.7

Since Version 0.7.7 there is a new way to create an aggregated report:

You create a separate 'report' project which collects all the necessary reports (Any goal in the aggregator project is executed before its modules therefore it can't be used).

aggregator pom
  |- parent pom
  |- module a
  |- module b
  |- report module 

The root pom looks like this (don't forget to add the new report module under modules):

<build>
<plugins>
  <plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.7.8</version>
    <executions>
      <execution>
        <id>prepare-agent</id>
        <goals>
          <goal>prepare-agent</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>

The poms from each sub module doesn't need to be changed at all. The pom from the report module looks like this:

<!-- Add all sub modules as dependencies here -->
<dependencies>
  <dependency>
    <module a>
  </dependency>
  <dependency>
    <module b>
  </dependency>
 ...

  <build>
    <plugins>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.7.8</version>
        <executions>
          <execution>
            <id>report-aggregate</id>
            <phase>verify</phase>
            <goals>
              <goal>report-aggregate</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

A full exmple can be found here.

Given final block not properly padded

If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

So, if you get this exception, catch it and treat it as "wrong key".

This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

Of course, bad padding can also happen if your data is corrupted in transport.

That said, there are some security remarks about your scheme:

  • For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).

  • Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.

    Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.

  • You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).

  • DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).

Unexpected character encountered while parsing value

I have also encountered this error for a Web API (.Net Core 3.0) action that was binding to a string instead to an object or a JObject. The JSON was correct, but the binder tried to get a string from the JSON structure and failed.

So, instead of:

[HttpPost("[action]")]
public object Search([FromBody] string data)

I had to use the more specific:

[HttpPost("[action]")]
public object Search([FromBody] JObject data)

How to get only the last part of a path in Python?

Here is my approach:

>>> import os
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD/test.py'))
folderD
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD/'))
folderD
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD'))
folderC

Where is Python language used?

Your categorization is not correct:

php, asp and ColdFusion are mostly used for websites, that is correct, but .net is definetly much more than asp you can build desktop applications, too (Paint.NET). I don't know about ColdFusion, but PHP can also be used to write desktop applications.

On the other hand C,C++ are not really often used for web programming, But it can be used for web programming (cgit). Java is definetly a language to develop web applications (spring and much more).

Python is a scripting language like PHP, Perl, Ruby and so much more. It can be used for web programming (django, Zope, Google App Engine, and much more). But it also can be used for desktop applications (Blender 3D, or even for games pygame).

Python can also be translated into binary code like java.

How to change Visual Studio 2012,2013 or 2015 License Key?

The ISO is probably pre-pidded. You'll need to delete the key from the setup files. It should then ask you for a key during installation.

Finding all positions of substring in a larger string in C#

I found this example and incorporated it into a function:

    public static int solution1(int A, int B)
    {
        // Check if A and B are in [0...999,999,999]
        if ( (A >= 0 && A <= 999999999) && (B >= 0 && B <= 999999999))
        {
            if (A == 0 && B == 0)
            {
                return 0;
            }
            // Make sure A < B
            if (A < B)
            {                    
                // Convert A and B to strings
                string a = A.ToString();
                string b = B.ToString();
                int index = 0;

                // See if A is a substring of B
                if (b.Contains(a))
                {
                    // Find index where A is
                    if (b.IndexOf(a) != -1)
                    {                            
                        while ((index = b.IndexOf(a, index)) != -1)
                        {
                            Console.WriteLine(A + " found at position " + index);
                            index++;
                        }
                        Console.ReadLine();
                        return b.IndexOf(a);
                    }
                    else
                        return -1;
                }
                else
                {
                    Console.WriteLine(A + " is not in " + B + ".");
                    Console.ReadLine();

                    return -1;
                }
            }
            else
            {
                Console.WriteLine(A + " must be less than " + B + ".");
               // Console.ReadLine();

                return -1;
            }                
        }
        else
        {
            Console.WriteLine("A or B is out of range.");
            //Console.ReadLine();

            return -1;
        }
    }

    static void Main(string[] args)
    {
        int A = 53, B = 1953786;
        int C = 78, D = 195378678;
        int E = 57, F = 153786;

        solution1(A, B);
        solution1(C, D);
        solution1(E, F);

        Console.WriteLine();
    }

Returns:

53 found at position 2

78 found at position 4
78 found at position 7

57 is not in 153786

android asynctask sending callbacks to ui

IN completion to above answers, you can also customize your fallbacks for each async call you do, so that each call to the generic ASYNC method will populate different data, depending on the onTaskDone stuff you put there.

  Main.FragmentCallback FC= new  Main.FragmentCallback(){
            @Override
            public void onTaskDone(String results) {

                localText.setText(results); //example TextView
            }
        };

new API_CALL(this.getApplicationContext(), "GET",FC).execute("&Books=" + Main.Books + "&args=" + profile_id);

Remind: I used interface on the main activity thats where "Main" comes, like this:

public interface FragmentCallback {
    public void onTaskDone(String results);


}

My API post execute looks like this:

  @Override
    protected void onPostExecute(String results) {

        Log.i("TASK Result", results);
        mFragmentCallback.onTaskDone(results);

    }

The API constructor looks like this:

 class  API_CALL extends AsyncTask<String,Void,String>  {

    private Main.FragmentCallback mFragmentCallback;
    private Context act;
    private String method;


    public API_CALL(Context ctx, String api_method,Main.FragmentCallback fragmentCallback) {
        act=ctx;
        method=api_method;
        mFragmentCallback = fragmentCallback;


    }

Create dataframe from a matrix

melt() from the reshape2 package gets you close ...

library(reshape2)
(res <- melt(as.data.frame(mat), id="time"))
#   time variable value
# 1  0.0      C_0   0.1
# 2  0.5      C_0   0.2
# 3  1.0      C_0   0.3
# 4  0.0      C_1   0.3
# 5  0.5      C_1   0.4
# 6  1.0      C_1   0.5

... although you may want to post-process its results to get your preferred column names and ordering.

setNames(res[c("variable", "time", "value")], c("name", "time", "val"))
#   name time val
# 1  C_0  0.0 0.1
# 2  C_0  0.5 0.2
# 3  C_0  1.0 0.3
# 4  C_1  0.0 0.3
# 5  C_1  0.5 0.4
# 6  C_1  1.0 0.5

How to set the margin or padding as percentage of height of parent container?

An answer to a slightly different question: You can use vh units to pad elements to the center of the viewport:

.centerme {
    margin-top: 50vh;
    background: red;
}

<div class="centerme">middle</div>

How do I programmatically get the GUID of an application in .NET 2.0

For an out-of-the-box working example, this is what I ended up using based on the previous answers.

using System.Reflection;
using System.Runtime.InteropServices;

label1.Text = "GUID: " + ((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute), false)).Value.ToUpper();

Alternatively, this way allows you to use it from a static class:

    /// <summary>
    /// public GUID property for use in static class </summary>
    /// <returns>
    /// Returns the application GUID or "" if unable to get it. </returns>
    static public string AssemblyGuid
    {
        get
        {
            object[] attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(GuidAttribute), false);
            if (attributes.Length == 0) { return String.Empty; }
            return ((System.Runtime.InteropServices.GuidAttribute)attributes[0]).Value.ToUpper();
        }
    }

Check if a String contains numbers Java

Pattern p = Pattern.compile("(([A-Z].*[0-9])");
Matcher m = p.matcher("TEST 123");
boolean b = m.find();
System.out.println(b);

How to get Time from DateTime format in SQL?

You can use this:

SELECT CONVERT(VARCHAR(5), GETDATE(),8)  

Output:

08:24

strdup() - what does it do in C?

The most valuable thing it does is give you another string identical to the first, without requiring you to allocate memory (location and size) yourself. But, as noted, you still need to free it (but which doesn't require a quantity calculation, either.)

How to get video duration, dimension and size in PHP?

If you use Wordpress you can just use the wordpress build in function with the video id provided wp_get_attachment_metadata($videoID):

wp_get_attachment_metadata($videoID);

helped me a lot. thats why i'm posting it, although its just for wordpress users.

How do I sort a table in Excel if it has cell references in it?

Append the sheet name to the formula which makes the reference absolute. For example, if the cell reference is =T7 make it =Sheet1!T7. Paste-link would have done the same thing except only when pasting to another sheet. Paste-link does not work as expected if you are pasting in to the same sheet.

SQL distinct for 2 fields in a database

If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

how concatenate two variables in batch script?

The way is correct, but can be improved a bit with the extended set-syntax.

set "var=xyz"

Sets the var to the content until the last quotation mark, this ensures that no "hidden" spaces are appended.

Your code would look like

set "var1=A"
set "var2=B"
set "AB=hi"
set "newvar=%var1%%var2%"
echo %newvar% is the concat of var1 and var2
echo !%newvar%! is the indirect content of newvar

CSS "and" and "or"

To select properties a AND b of a X element:

X[a][b]

To select properties a OR b of a X element:

X[a],X[b]

Create a remote branch on GitHub

Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.

To create a new branch with a copy of your current state

git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server

Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

Check if image exists on server using JavaScript?

A better and modern approach is to use ES6 Fetch API to check if an image exists or not:

fetch('https://via.placeholder.com/150', { method: 'HEAD' })
    .then(res => {
        if (res.ok) {
            console.log('Image exists.');
        } else {
            console.log('Image does not exist.');
        }
    }).catch(err => console.log('Error:', err));

Make sure you are either making the same-origin requests or CORS is enabled on the server.

Android Camera : data intent returns null

Probably because you had something like this?

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                        
Uri fileUri =  CommonUtilities.getTBCameraOutputMediaFileUri();                  
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);                        
startActivityForResult(takePictureIntent, 2);

However you must not put the extra output into the intent, because then the data goes into the URI instead of the data variable. For that reason, you have to take the two lines in the middle out, so that you have

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, 2);

That´s what caused the problem for me, hope that helped.

location.host vs location.hostname and cross-browser compatibility?

Your primary question has been answered above. I just wanted to point out that the regex you're using has a bug. It will also succeed on foo-domain.com which is not a subdomain of domain.com

What you really want is this:

/(^|\.)domain\.com$/

Installing Java 7 on Ubuntu

flup's answer is the best but it did not work for me completely. I had to do the following as well to get it working:

  1. export JAVA_HOME=/usr/lib/jvm/java-7-oracle/jre/
  2. chmod 777 on the folder
  3. ./gradlew build - Building Hibernate

How to avoid soft keyboard pushing up my layout?

I had the same problem, but setting windowSoftInputMode did not help, and I did not want to change the upper view to have isScrollContainer="false" because I wanted it to scroll.

My solution was to define the top location of the navigation tools instead of the bottom. I'm using Titanium, so I'm not sure exactly how this would translate to android. Defining the top location of the navigation tools view prevented the soft keyboard from pushing it up, and instead covered the nav controls like I wanted.

How to solve a pair of nonlinear equations using Python?

for numerical solution, you can use fsolve:

http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html#scipy.optimize.fsolve

from scipy.optimize import fsolve
import math

def equations(p):
    x, y = p
    return (x+y**2-4, math.exp(x) + x*y - 3)

x, y =  fsolve(equations, (1, 1))

print equations((x, y))

remove empty lines from text file with PowerShell

This will remove empty lines or lines with only whitespace characters (tabs/spaces).

[IO.File]::ReadAllText("FileWithEmptyLines.txt") -replace '\s+\r\n+', "`r`n" | Out-File "c:\FileWithNoEmptyLines.txt"

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

Try using anaconda. I had the same error. One lone option was to build tensorflow from source which took long time. I tried using conda and it worked.

  1. Create a new environment in anaconda.
  2. conda -c conda-forge tensorflow

Then, it worked.

How often should you use git-gc?

I use when I do a big commit, above all when I remove more files from the repository.. after, the commits are faster

How to convert the background to transparent?

If you want a command-line solution, you can use the ImageMagick convert utility:

convert input.png -transparent red output.png

Can Selenium interact with an existing browser session?

This is pretty easy using the JavaScript selenium-webdriver client:

First, make sure you have a WebDriver server running. For example, download ChromeDriver, then run chromedriver --port=9515.

Second, create the driver like this:

var driver = new webdriver.Builder()
   .withCapabilities(webdriver.Capabilities.chrome())
   .usingServer('http://localhost:9515')  // <- this
   .build();

Here's a complete example:

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder()
   .withCapabilities(webdriver.Capabilities.chrome())
   .usingServer('http://localhost:9515')
   .build();

driver.get('http://www.google.com');
driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');
driver.findElement(webdriver.By.name('btnG')).click();
driver.getTitle().then(function(title) {
   console.log(title);
 });

driver.quit();

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Try changing Tools > Options > Database Tools > Data Connections > SQL Server Instance Name.

The default for VS2013 is (LocalDB)\v11.0.

Changing to (LocalDB)\MSSQLLocalDB, for example, seems to work - no more version 782 error.

Find the maximum value in a list of tuples in Python

Use max():

 
Using itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361

using lambda:

In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361

timeit comparison:

In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

For me it was as simple as

  1. Delete Microsoft.AspNet.WebApi.Client from the packages folder in Windows Explorer
  2. Open Tools > NuGet Package Manager > Package Manager Console
  3. Click the "Restore" button

Android EditText view Floating Hint in Material Design

No it doesn't. I would expect this in a future api release, but for now we are stuck with EditText. Another option is this library:
https://github.com/marvinlabs/android-floatinglabel-widgets

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"}

AngularJS is rendering <br> as text not as a newline

You can use \n to concatenate words and then apply this style to container div.

style="white-space: pre;"

More info can be found at https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

_x000D_
_x000D_
<p style="white-space: pre;">_x000D_
    This is normal text._x000D_
</p>_x000D_
<p style="white-space: pre;">_x000D_
    This _x000D_
  text _x000D_
  contains _x000D_
  new lines._x000D_
</p>
_x000D_
_x000D_
_x000D_

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

Install the ASP.NET AJAX Control Toolkit

  1. Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the ASP.NET AJAX Control Toolkit Releases page of the CodePlex web site.

  2. Copy the contents of this zip file directly into the bin directory of your web site.

Update web.config

  1. Put this in your web.config under the <controls> section:

    <?xml version="1.0"?>
    <configuration>
        ...
        <system.web>
            ...
            <pages>
                ...
                <controls>
                    ...
                    <add tagPrefix="ajaxtoolkit"
                        namespace="AjaxControlToolkit"
                        assembly="AjaxControlToolKit"/>
                </controls>
            </pages>
            ...
        </system.web>
        ...
    </configuration>
    

Setup Visual Studio

  1. Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"

  2. Inside that tab, right-click on the Toolbox and select "Choose Items..."

  3. When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.

You can now use the controls in your web sites!

Get day of week in SQL Server 2005/2008

this is a working copy of my code check it, how to retrive day name from date in sql

CREATE Procedure [dbo].[proc_GetProjectDeploymentTimeSheetData] 
@FromDate date,
@ToDate date

As 
Begin
select p.ProjectName + ' ( ' + st.Time +' '+'-'+' '+et.Time +' )' as ProjectDeatils,
datename(dw,pts.StartDate) as 'Day'
from 
ProjectTimeSheet pts 
join Projects p on pts.ProjectID=p.ID 
join Timing st on pts.StartTimingId=st.Id
join Timing et on pts.EndTimingId=et.Id
where pts.StartDate >= @FromDate
and pts.StartDate <= @ToDate
END

Find kth smallest element in a binary search tree in Optimum way

Here's just an outline of the idea:

In a BST, the left subtree of node T contains only elements smaller than the value stored in T. If k is smaller than the number of elements in the left subtree, the kth smallest element must belong to the left subtree. Otherwise, if k is larger, then the kth smallest element is in the right subtree.

We can augment the BST to have each node in it store the number of elements in its left subtree (assume that the left subtree of a given node includes that node). With this piece of information, it is simple to traverse the tree by repeatedly asking for the number of elements in the left subtree, to decide whether to do recurse into the left or right subtree.

Now, suppose we are at node T:

  1. If k == num_elements(left subtree of T), then the answer we're looking for is the value in node T.
  2. If k > num_elements(left subtree of T), then obviously we can ignore the left subtree, because those elements will also be smaller than the kth smallest. So, we reduce the problem to finding the k - num_elements(left subtree of T) smallest element of the right subtree.
  3. If k < num_elements(left subtree of T), then the kth smallest is somewhere in the left subtree, so we reduce the problem to finding the kth smallest element in the left subtree.

Complexity analysis:

This takes O(depth of node) time, which is O(log n) in the worst case on a balanced BST, or O(log n) on average for a random BST.

A BST requires O(n) storage, and it takes another O(n) to store the information about the number of elements. All BST operations take O(depth of node) time, and it takes O(depth of node) extra time to maintain the "number of elements" information for insertion, deletion or rotation of nodes. Therefore, storing information about the number of elements in the left subtree keeps the space and time complexity of a BST.

How to get the PYTHONPATH in shell?

Just write:

just write which python in your terminal and you will see the python path you are using.

LINQ query to select top five

The solution:

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

What is the difference between task and thread?

A task is something you want done.

A thread is one of the many possible workers which performs that task.

In .NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.

Use underscore inside Angular controllers

you can use this module -> https://github.com/jiahut/ng.lodash

this is for lodash so does underscore

Sending email through Gmail SMTP server with C#

I was getting the same error and none of the above solutions helped.

My problem was that I was running the code from a remote server, which had never been used to log into the gmail account.

I opened a browser on the remote server and logged into gmail from there. It asked a security question to verify it was me since this was a new location. After doing the security check I was able to authenticate through code.

Flutter: how to make a TextField with HintText but no Underline?

            Container(
         height: 50,
          // margin: EdgeInsets.only(top: 20),
          decoration: BoxDecoration(
              color: Colors.tealAccent,
              borderRadius: BorderRadius.circular(32)),
          child: TextFormField(
            cursorColor: Colors.black,
            // keyboardType: TextInputType.,
            decoration: InputDecoration(
              hintStyle: TextStyle(fontSize: 17),
              hintText: 'Search your trips',
              suffixIcon: Icon(Icons.search),
              border: InputBorder.none,
              contentPadding: EdgeInsets.all(18),
            ),
          ),
        ),

@RequestBody and @ResponseBody annotations in Spring

There is a whole Section in the docs called 16.3.3.4 Mapping the request body with the @RequestBody annotation. And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation. I suggest you consult those sections. Also relevant: @RequestBody javadocs, @ResponseBody javadocs

Usage examples would be something like this:

Using a JavaScript-library like JQuery, you would post a JSON-Object like this:

{ "firstName" : "Elmer", "lastName" : "Fudd" }

Your controller method would look like this:

// controller
@ResponseBody @RequestMapping("/description")
public Description getDescription(@RequestBody UserStats stats){
    return new Description(stats.getFirstName() + " " + stats.getLastname() + " hates wacky wabbits");
}

// domain / value objects
public class UserStats{
    private String firstName;
    private String lastName;
    // + getters, setters
}
public class Description{
    private String description;
    // + getters, setters, constructor
}

Now if you have Jackson on your classpath (and have an <mvc:annotation-driven> setup), Spring would convert the incoming JSON to a UserStats object from the post body (because you added the @RequestBody annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody annotation). So the Browser / Client would see this JSON result:

{ "description" : "Elmer Fudd hates wacky wabbits" }

See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852

Note: RequestBody / ResponseBody is of course not limited to JSON, both can handle multiple formats, including plain text and XML, but JSON is probably the most used format.


Update

Ever since Spring 4.x, you usually won't use @ResponseBody on method level, but rather @RestController on class level, with the same effect.

Here is a quote from the official Spring MVC documentation:

@RestController is a composed annotation that is itself meta-annotated with @Controller and @ResponseBody to indicate a controller whose every method inherits the type-level @ResponseBody annotation and, therefore, writes directly to the response body versus view resolution and rendering with an HTML template.

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

Looks like problem of configuration for maven compiler in your pom file. Default version java source and target is 1.5, even used JDK has higher version.

To fix, add maven compiler plugin configuration section with higher java version, example:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.6.1</version>
  <configuration>
    <source>1.6</source>
    <target>1.6</target>
  </configuration>
</plugin>

For more info check these links:

maven compiler

bug report

Shuffle DataFrame rows

You can simply use sklearn for this

from sklearn.utils import shuffle
df = shuffle(df)

Import Excel Spreadsheet Data to an EXISTING sql table?

Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into the existing table. You can add a line to drop the temp table created by the import wizard as the last step upon successful completion of the script.

I believe your original issue is in fact related to Sql Server 64 bit and is due to your having a 32 bit Excel and these drivers don't play well together. I did run into a very similar issue when first using 64 bit excel.

How to customize the back button on ActionBar

I had the same issue of Action-bar Home button icon direction,because of miss managing of Icon in Gradle Resource directory icon

like in Arabic Gradle resource directory you put icon in x-hdpi and in English Gradle resource same icon name you put in different density folder like xx-hdpi ,so that in APK there will be two same icon names in different directories,so your device will pick density dependent icon may be RTL or LTR

How to get the list of files in a directory in a shell script?

for entry in "$search_dir"/* "$work_dir"/*
do
  if [ -f "$entry" ];then
    echo "$entry"
  fi
done

Docker official registry (Docker Hub) URL

I came across this post in search for the dockerhub repo URL when creating a dockerhub kubernetes secret.. figured id share the URL is used with success, hope that's ok.

Live Current: https://index.docker.io/v2/

Dead Orginal: https://index.docker.io/v1/

To check if string contains particular word

Using contains

String sentence = "Check this answer and you can find the keyword with this code";
String search = "keyword";

if (sentence.toLowerCase().contains(search.toLowerCase())) {

  System.out.println("I found the keyword..!");

} else {

  System.out.println("not found..!");

}

How to create a service running a .exe file on Windows 2012 Server?

You can just do that too, it seems to work well too. sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"

You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.

Python datetime strptime() and strftime(): how to preserve the timezone information

Here is my answer in Python 2.7

Print current time with timezone

from datetime import datetime
import tzlocal  # pip install tzlocal

print datetime.now(tzlocal.get_localzone()).strftime("%Y-%m-%d %H:%M:%S %z")

Print current time with specific timezone

from datetime import datetime
import pytz # pip install pytz

print datetime.now(pytz.timezone('Asia/Taipei')).strftime("%Y-%m-%d %H:%M:%S %z")

It will print something like

2017-08-10 20:46:24 +0800

Image library for Python 3

Qt works very well with graphics. In my opinion it is more versatile than PIL.

You get all the features you want for graphics manipulation, but there's also vector graphics and even support for real printers. And all of that in one uniform API, QPainter.

To use Qt you need a Python binding for it: PySide or PyQt4.
They both support Python 3.

Here is a simple example that loads a JPG image, draws an antialiased circle of radius 10 at coordinates (20, 20) with the color of the pixel that was at those coordinates and saves the modified image as a PNG file:

from PySide.QtCore import *
from PySide.QtGui import *

app = QCoreApplication([])

img = QImage('input.jpg')

g = QPainter(img)
g.setRenderHint(QPainter.Antialiasing)
g.setBrush(QColor(img.pixel(20, 20)))
g.drawEllipse(QPoint(20, 20), 10, 10)
g.end()

img.save('output.png')

But please note that this solution is quite 'heavyweight', because Qt is a large framework for making GUI applications.

writing integer values to a file using out.write()

write() only takes a single string argument, so you could do this:

outf.write(str(num))

or

outf.write('{}'.format(num))  # more "modern"
outf.write('%d' % num)        # deprecated mostly

Also note that write will not append a newline to your output so if you need it you'll have to supply it yourself.

Aside:

Using string formatting would give you more control over your output, so for instance you could write (both of these are equivalent):

num = 7
outf.write('{:03d}\n'.format(num))

num = 12
outf.write('%03d\n' % num)          

to get three spaces, with leading zeros for your integer value followed by a newline:

007
012

format() will be around for a long while, so it's worth learning/knowing.

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

BLOB primarily intended to hold non-traditional data, such as images,videos,voice or mixed media. CLOB intended to retain character-based data.

Write to custom log file from a Bash script

@chepner make a good point that logger is dedicated to logging messages.

I do need to mention that @Thomas Haratyk simply inquired why I didn't simply use echo.

At the time, I didn't know about echo, as I'm learning shell-scripting, but he was right.

My simple solution is now this:

#!/bin/bash
echo "This logs to where I want, but using echo" > /var/log/mycustomlog

The example above will overwrite the file after the >

So, I can append to that file with this:

#!/bin/bash
echo "I will just append to my custom log file" >> /var/log/customlog

Thanks guys!

  • on a side note, it's simply my personal preference to keep my personal logs in /var/log/, but I'm sure there are other good ideas out there. And since I didn't create a daemon, /var/log/ probably isn't the best place for my custom log file. (just saying)

Kill a postgresql session/connection

Just wanted to point out that Haris's Answer might not work if some other background process is using the database, in my case it was delayed jobs, I did:

script/delayed_job stop

And only then I was able to drop/reset the database.

manage.py runserver

I was struggling with the same problem and found one solution. I guess it can help you. when you run python manage.py runserver, it will take 127.0.0.1 as default ip address and 8000. 127.0.0.0 is the same as localhost which can be accessed locally. to access it from cross origin you need to run it on your system ip or 0.0.0.0. 0.0.0.0 can be accessed from any origin in the network. for port number, you need to set inbound and outbound policy of your system if you want to use your own port number not the default one.

To do this you need to run server with command python manage.py runserver 0.0.0.0:<your port> as mentioned above

or, set a default ip and port in your python environment. For this see my answer on django change default runserver port

Enjoy coding .....

Prevent Android activity dialog from closing on outside touch

This is the perfect answer to all your questions.... Hope you enjoy coding in Android

new AlertDialog.Builder(this)
            .setTitle("Akshat Rastogi Is Great")
            .setCancelable(false)
            .setMessage("I am the best Android Programmer")
            .setPositiveButton("I agree", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                }
            })
            .create().show();

Good MapReduce examples

From time to time I present MR concepts to people. I find processing tasks familiar to people and then map them to the MR paradigm.

Usually I take two things:

  1. Group By / Aggregations. Here the advantage of the shuffling stage is clear. An explanation that shuffling is also distributed sort + an explanation of distributed sort algorithm also helps.

  2. Join of two tables. People working with DB are familiar with the concept and its scalability problem. Show how it can be done in MR.

How to return JSON with ASP.NET & jQuery

You're not far; you need to do something like this:

[WebMethod]
public static string GetProducts()
{
  // instantiate a serializer
  JavaScriptSerializer TheSerializer = new JavaScriptSerializer();

  //optional: you can create your own custom converter
  TheSerializer.RegisterConverters(new JavaScriptConverter[] {new MyCustomJson()});

  var products = context.GetProducts().ToList();   

  var TheJson = TheSerializer.Serialize(products);

  return TheJson;
}

You can reduce this code further but I left it like that for clarity. In fact, you could even write this:

return context.GetProducts().ToList();

and this would return a json string. I prefer to be more explicit because I use custom converters. There's also Json.net but the framework's JavaScriptSerializer works just fine out of the box.

How to remove all the punctuation in a string? (Python)

import string

asking = "".join(l for l in asking if l not in string.punctuation)

filter with string.punctuation.

How to reset Jenkins security settings from the command line?

For one who is using macOS, the new version just can be installed by homebrew. so for resting, this command line must be using:

brew services restart jenkins-lts

HSL to RGB color conversion

With H, S,and L in [0,1] range:

ConvertHslToRgb: function (iHsl)
{
    var min, sv, sextant, fract, vsf;

    var v = (iHsl.l <= 0.5) ? (iHsl.l * (1 + iHsl.s)) : (iHsl.l + iHsl.s - iHsl.l * iHsl.s);
    if (v === 0)
        return { Red: 0, Green: 0, Blue: 0 };

    min = 2 * iHsl.l - v;
    sv = (v - min) / v;
    var h = (6 * iHsl.h) % 6;
    sextant = Math.floor(h);
    fract = h - sextant;
    vsf = v * sv * fract;

    switch (sextant)
    {
        case 0: return { r: v, g: min + vsf, b: min };
        case 1: return { r: v - vsf, g: v, b: min };
        case 2: return { r: min, g: v, b: min + vsf };
        case 3: return { r: min, g: v - vsf, b: v };
        case 4: return { r: min + vsf, g: min, b: v };
        case 5: return { r: v, g: min, b: v - vsf };
    }
}

Removing display of row names from data frame

Recently I had the same problem when using htmlTable() (‘htmlTable’ package) and I found a simpler solution: convert the data frame to a matrix with as.matrix():

htmlTable(as.matrix(df))

And be sure that the rownames are just indices. as.matrix() conservs the same columnames. That's it.

UPDATE

Following the comment of @DMR, I did't notice that htmlTable() has the parameter rnames = FALSE for cases like this. So a better answer would be:

htmlTable(df, rnames = FALSE)

How to change status bar color in Flutter?

This is by far is the best way, it requires no extra plugins.

Widget emptyAppBar(){
  return PreferredSize(
      preferredSize: Size.fromHeight(0.0), 
      child: AppBar(
        backgroundColor: Color(0xFFf7f7f7),
        brightness: Brightness.light,
      )
  );
}

and call it in your scaffold like this

return Scaffold(
      appBar: emptyAppBar(),
     .
     .
     .

Xcode 'CodeSign error: code signing is required'

  • I love Stack Overflow:

  • I realized that some time being too specific is not enough that is because we may have different Xcode version, I have 2 xcode version on the same Mac Pro myself. So here I would like to provide a general instruction that i hope it will work for all Xcode version:

  • My 2 versions are xcode 3.2.6 and 4.0. You need to find (even google for the settings) your xcode BUILD SETTINGS and its CODE SIGNING under CODE SIGNING you have CODE SIGN IDENTITY this provide you a list of IDENTIFIERS (if you do not have IDENTIFIERS go here to get one and registration is required https://developer.apple.com/ios/manage/overview/index.action - follow this instruction of Apple "Get your application on an iOS with the Development Provisioning Assistant") If you have a list of identifiers just select a valid one and run your Xcode again. It will work!

  • 3.2.6 specific: On your scode window - click on Project -> Project settings -> Build (tab) -> there is a scroll down because the list is long MAKING SURE you scroll down to find your CODE SIGNING section

  • 4.0 specific: On your xcode window - click on your project file left most colum -> then next colum click on your target app -> find CODE SIGNING and assign an IDENTIFIER. It should work for you.

Done!

Equivalent of Math.Min & Math.Max for Dates?

There is no overload for DateTime values, but you can get the long value Ticks that is what the values contain, compare them and then create a new DateTime value from the result:

new DateTime(Math.Min(Date1.Ticks, Date2.Ticks))

(Note that the DateTime structure also contains a Kind property, that is not retained in the new value. This is normally not a problem; if you compare DateTime values of different kinds the comparison doesn't make sense anyway.)

How to change the status bar background color and text color on iOS 7?

In the case of swift 2.0 on iOS 9

Place the following in the app delegate, under didFinishLaunchingWithOptions:

    let view: UIView = UIView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 20))

    view.backgroundColor = UIColor.blackColor()  //The colour you want to set

    view.alpha = 0.1   //This and the line above is set like this just if you want 
                          the status bar a darker shade of 
                          the colour you already have behind it.

    self.window!.rootViewController!.view.addSubview(view)

Can Android Studio be used to run standard Java projects?

With Android Studio 0.6.1+ (and possibly earlier) you can easily develop standard Java (non-Android) apps.

This method has been tested on 0.8.2:

Start by creating a vanilla Android Phone app, using File > New Project. Then add a Java Library module to hold your Java Application code. (Choose 'Java Library' even if you're building an application). You'll find you can build and run Java apps with main() methods, Swing apps etc.

You'll want to delete the auto-generated Android "app" module, which you're not using. Go to File -> Project Structure, and delete it (select the "app" module in the box on the left, and click the 'minus' icon above the box). Now when you reopen File -> Project Structure -> Project, you'll see options for selecting the project SDK and language level, plus a bunch of other options that were previously hidden. You can go ahead and delete the "app" module from the disk.

In 0.6.1 you could avoid creating the android module in the first place:

Go to File > New Project. Fill in your application name. On the "form factors" selection page, where you state your minimum Android SDK, deselect the Mobile checkbox, and proceed with creating your project.

Once the project is created, go to File -> Project Structure -> Project, and set your JDK as the "Project SDK". Add a Java Library module to hold your application code as above.

Error message "Linter pylint is not installed"

I also had this problem. If you also have Visual Studio installed with the Python extension, the system will want to use Studio's version of Python. Set the Environment Path to the version in Studio's Shared folder. For me, that was:

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\

After that, run

python -m pip install pylint

from a command prompt with Administrator rights.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

How to track down access violation "at address 00000000"

You start looking near that code that you know ran, and you stop looking when you reach the code you know didn't run.

What you're looking for is probably some place where your program calls a function through a function pointer, but that pointer is null.

It's also possible you have stack corruption. You might have overwritten a function's return address with zero, and the exception occurs at the end of the function. Check for possible buffer overflows, and if you are calling any DLL functions, make sure you used the right calling convention and parameter count.

This isn't an ordinary case of using a null pointer, like an unassigned object reference or PChar. In those cases, you'll have a non-zero "at address x" value. Since the instruction occurred at address zero, you know the CPU's instruction pointer was not pointing at any valid instruction. That's why the debugger can't show you which line of code caused the problem — there is no line of code. You need to find it by finding the code that lead up to the place where the CPU jumped to the invalid address.

The call stack might still be intact, which should at least get you pretty close to your goal. If you have stack corruption, though, you might not be able to trust the call stack.

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

the difference of the numbers put in system.exit() is explained in other answers. but the REAL DIFFERENCE is that System.exit() is a code that gets returned to the invoking process. If the program is being invoked by the Operating system then the return code will tell the OS that if system.exit() returned 0 than everything was ok but if not something went wrong, then there could be some handlers for that in the parent process

Set the layout weight of a TextView programmatically

You can also give weight separately like this ,

LayoutParams lp1 = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);

 lp1.weight=1;

How to convert ZonedDateTime to Date?

If you are using the ThreeTen backport for Android and can't use the newer Date.from(Instant instant) (which requires minimum of API 26) you can use:

ZonedDateTime zdt = ZonedDateTime.now();
Date date = new Date(zdt.toInstant().toEpochMilli());

or:

Date date = DateTimeUtils.toDate(zdt.toInstant());

Please also read the advice in Basil Bourque's answer

Read a file in Node.js

Run this code, it will fetch data from file and display in console

function fileread(filename)
{            
   var contents= fs.readFileSync(filename);
   return contents;
}        
var fs =require("fs");  // file system        
var data= fileread("abc.txt");
//module.exports.say =say;
//data.say();
console.log(data.toString());

Why do you need to put #!/bin/bash at the beginning of a script file?

Every distribution has a default shell. Bash is the default on the majority of the systems. If you happen to work on a system that has a different default shell, then the scripts might not work as intended if they are written specific for Bash.

Bash has evolved over the years taking code from ksh and sh.

Adding #!/bin/bash as the first line of your script, tells the OS to invoke the specified shell to execute the commands that follow in the script.

#! is often referred to as a "hash-bang", "she-bang" or "sha-bang".

How to right-align and justify-align in Markdown?

As mentioned here, markdown do not support right aligned text or blocks. But the HTML result does it, via Cascading Style Sheets (CSS).

On my Jekyll Blog is use a syntax which works in markdown as well. To "terminate" a block use two spaces at the end or two times new line.

Of course you can also add a css-class with {: .right } instead of {: style="text-align: right" }.

Text to right

{: style="text-align: right" }
This text is on the right

Text as block

{: style="text-align: justify" }
This text is a block

Difference between static, auto, global and local variable in the context of c and c++

First of all i say that you should google this as it is defined in detail in many places

Local
These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.

Global
These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.

/* Demonstrating Global variables  */
    #include <stdio.h>
    int add_numbers( void );                /* ANSI function prototype */

    /* These are global variables and can be accessed by functions from this point on */
    int  value1, value2, value3;

    int add_numbers( void )
    {
        auto int result;
        result = value1 + value2 + value3;
        return result;
    }

    main()
    {
        auto int result;
        value1 = 10;
        value2 = 20;
        value3 = 30;        
        result = add_numbers();
        printf("The sum of %d + %d + %d is %d\n",
            value1, value2, value3, final_result);
    }


    Sample Program Output
    The sum of 10 + 20 + 30 is 60

The scope of global variables can be restricted by carefully placing the declaration. They are visible from the declaration until the end of the current source file.

#include <stdio.h>
void no_access( void ); /* ANSI function prototype */
void all_access( void );

static int n2;      /* n2 is known from this point onwards */

void no_access( void )
{
    n1 = 10;        /* illegal, n1 not yet known */
    n2 = 5;         /* valid */
}

static int n1;      /* n1 is known from this point onwards */

void all_access( void )
{
    n1 = 10;        /* valid */
    n2 = 3;         /* valid */
}

Static:
Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects. Static objects are destroyed when the program stops running.
I suggest you to see this tutorial list

AUTO:
C, C++

(Called automatic variables.)

All variables declared within a block of code are automatic by default, but this can be made explicit with the auto keyword.[note 1] An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type.[1]

Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.

In C++, the constructor of automatic variables is called when the execution reaches the place of declaration. The destructor is called when it reaches the end of the given program block (program blocks are surrounded by curly brackets). This feature is often used to manage resource allocation and deallocation, like opening and then automatically closing files or freeing up memory.SEE WIKIPEDIA

Is there a MessageBox equivalent in WPF?

If you want to have your own nice looking wpf MessageBox: Create new Wpf Windows

here is xaml :

<Window x:Class="popup.MessageboxNew"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:popup"
        mc:Ignorable="d"
        Title="" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" WindowStyle="None" ResizeMode="NoResize" AllowsTransparency="True" Background="Transparent" Opacity="1"
        >
    <Window.Resources>

    </Window.Resources>
    <Border x:Name="MainBorder" Margin="10" CornerRadius="8" BorderThickness="0" BorderBrush="Black" Padding="0" >
        <Border.Effect>
            <DropShadowEffect x:Name="DSE" Color="Black" Direction="270" BlurRadius="20" ShadowDepth="3" Opacity="0.6" />
        </Border.Effect>
        <Border.Triggers>
            <EventTrigger RoutedEvent="Window.Loaded">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="ShadowDepth" From="0" To="3" Duration="0:0:1" AutoReverse="False" />
                        <DoubleAnimation Storyboard.TargetName="DSE" Storyboard.TargetProperty="BlurRadius" From="0" To="20" Duration="0:0:1" AutoReverse="False" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Border.Triggers>
        <Grid Loaded="FrameworkElement_OnLoaded">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Border Name="Mask" CornerRadius="8" Background="White" />
            <Grid x:Name="Grid" Background="White">
                <Grid.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=Mask}"/>
                </Grid.OpacityMask>
                <StackPanel Name="StackPanel" >
                    <TextBox Style="{DynamicResource MaterialDesignTextBox}" Name="TitleBar" IsReadOnly="True" IsHitTestVisible="False" Padding="10" FontFamily="Segui" FontSize="14" 
                             Foreground="Black" FontWeight="Normal"
                             Background="Yellow" HorizontalAlignment="Stretch" VerticalAlignment="Center" Width="Auto" HorizontalContentAlignment="Center" BorderThickness="0"/>
                    <DockPanel Name="ContentHost" Margin="0,10,0,10" >
                        <TextBlock Margin="10" Name="Textbar"></TextBlock>
                    </DockPanel>
                    <DockPanel Name="ButtonHost" LastChildFill="False" HorizontalAlignment="Center" >
                        <Button Margin="10" Click="ButtonBase_OnClick" Width="70">Yes</Button>
                        <Button Name="noBtn" Margin="10" Click="cancel_Click" Width="70">No</Button>
                    </DockPanel>
                </StackPanel>
            </Grid>
        </Grid>
    </Border>
</Window>

for cs of this file :

public partial class MessageboxNew : Window
    {
        public MessageboxNew()
        {
            InitializeComponent();
            //second time show error solved
            if (Application.Current == null) new Application();
                    Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }

        private void cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)
        {
            this.MouseDown += delegate { DragMove(); };
        }
    }

then create a class to use this :

public class Mk_MessageBox
{
    public static bool? Show(string title, string text)
    {
        MessageboxNew msg = new MessageboxNew
        {
            TitleBar = {Text = title},
            Textbar = {Text = text}
        };
        msg.noBtn.Focus();
        return msg.ShowDialog();
    }
}

now you can create your message box like this:

var result = Mk_MessageBox.Show("Remove Alert", "This is gonna remove directory from host! Are you sure?");
            if (result == true)
            {
                // whatever
            }

copy this to App.xaml inside

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- MahApps.Metro resource dictionaries. Make sure that all file names are Case Sensitive! -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />
            <!-- Accent and AppTheme setting -->
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />

            <!--two new guys-->
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.LightBlue.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Green.xaml" />

            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

--------------IMAGE of Result-----------------

My Refrence : https://www.red-gate.com/simple-talk/dotnet/net-development/using-c-to-create-powershell-cmdlets-the-basics/

for logic how can i make my own messagebox

Decompile .smali files on an APK

dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/

Can't connect to local MySQL server through socket '/tmp/mysql.sock

For me, the mysql server was not running. So, i started the mysql server through

mysql.server start

then

mysql_secure_installation

to secure the server and now I can visit the MySQL server through

mysql -u root -p

or

sudo mysql -u root -p

depending on your installation.

How to download a folder from github?

There is a button Download ZIP. If you want to do a sparse checkout there are many solutions on the site. For example here.

How can I show data using a modal when clicking a table row (using bootstrap)?

One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.

I am just going to show as a static example which you can accommodate in your real world.

On each of your <tr>'s add a data attribute for id (i.e. data-id) with the corresponding id value and specify a data-target, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal to make this a trigger for modal.

  <tr data-toggle="modal" data-id="1" data-target="#orderModal">
            <td>1</td>
            <td>24234234</td>
            <td>A</td>
  </tr>
  <tr data-toggle="modal" data-id="2" data-target="#orderModal">
            <td>2</td>
            <td>24234234</td>
            <td>A</td>
        </tr>
  <tr data-toggle="modal" data-id="3" data-target="#orderModal">
            <td>3</td>
            <td>24234234</td>
            <td>A</td>
  </tr>

And now in the javascript just set up the modal just once and event listen to its events so you can do your work.

$(function(){
    $('#orderModal').modal({
        keyboard: true,
        backdrop: "static",
        show:false,

    }).on('show', function(){ //subscribe to show method
          var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow  + '</b>'))
    });
});

Demo

Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.

Alternative ways here:

Demo2 or Demo3

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

Setting Django up to use MySQL

Actually, there are many issues with different environments, python versions, so on. You might also need to install python dev files, so to 'brute-force' the installation I would run all of these:

sudo apt-get install python-dev python3-dev
sudo apt-get install libmysqlclient-dev
pip install MySQL-python
pip install pymysql
pip install mysqlclient

You should be good to go with the accepted answer. And can remove the unnecessary packages if that's important to you.

How to tell if JRE or JDK is installed

A generic, pure Java solution..

For Windows and MacOS, the following can be inferred (most of the time)...

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null && path.contains("jdk")) {
        return true;
    }
    return false;
}

However... on Linux this isn't as reliable... For example...

  • Many JREs on Linux contain openjdk the path
  • There's no guarantee that the JRE doesn't also contain a JDK.

So a more fail-safe approach is to check for the existence of the javac executable.

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null) {
        String javacPath = "";
        if(path.endsWith(File.separator + "bin")) {
            javacPath = path;
        } else {
            int libIndex = path.lastIndexOf(File.separator + "lib");
            if(libIndex > 0) {
                javacPath = path.substring(0, libIndex) + File.separator + "bin";
            }
        }
        if(!javacPath.isEmpty()) {
            return new File(javacPath, "javac").exists() || new File(javacPath, "javac.exe").exists();
        }
    }
    return false;
}

Warning: This will still fail for JRE + JDK combos which report the JRE's sun.boot.library.path identically between the JRE and the JDK. For example, Fedora's JDK will fail (or pass depending on how you look at it) when the above code is run. See unit tests below for more info...

Unit tests:

# Unix
java -XshowSettings:properties -version 2>&1|grep "sun.boot.library.path"
# Windows
java -XshowSettings:properties -version 2>&1|find "sun.boot.library.path"
    # PASS: MacOS AdoptOpenJDK JDK11
    /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home/lib

    # PASS: Windows Oracle JDK12
    c:\Program Files\Java\jdk-12.0.2\bin

    # PASS: Windows Oracle JRE8
    C:\Program Files\Java\jre1.8.0_181\bin

    # PASS: Windows Oracle JDK8
    C:\Program Files\Java\jdk1.8.0_181\bin

    # PASS: Ubuntu AdoptOpenJDK JDK11
    /usr/lib/jvm/adoptopenjdk-11-hotspot-amd64/lib

    # PASS: Ubuntu Oracle JDK11
    /usr/lib/jvm/java-11-oracle/lib

    # PASS: Fedora OpenJDK JDK8
    /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.fc24.x86_64/jre/lib/amd64

    #### FAIL: Fedora OpenJDK JDK8
    /usr/java/jdk1.8.0_231-amd64/jre/lib/amd64

Incrementing a date in JavaScript

Via native JS, to add one day you may do following:

let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow

Another option is to use moment library:

const date = moment().add(14, "days").toDate()

How to print a number with commas as thousands separators in JavaScript

Below are two different browser APIs that can transform Numbers into structured Strings. Keep in mind that not all users' machines have a locale that uses commas in numbers. To enforce commas to the output, any "western" locale may be used, such as en-US

var number = 1234567890; // Example number to be converted

?? Mind that javascript has a maximum integer value of 9007199254740991


toLocaleString

// default behaviour on a machine with a local that uses commas for numbers
number.toLocaleString(); // "1,234,567,890"

// With custom settings, forcing a "US" locale to guarantee commas in output
var number2 = 1234.56789; // floating point example
number2.toLocaleString('en-US', {maximumFractionDigits:2}) // "1,234.57"

NumberFormat

var nf = new Intl.NumberFormat();
nf.format(number); // "1,234,567,890"

From what I checked (Firefox at least) they are both more or less same regarding performance.

Live demo: https://codepen.io/vsync/pen/MWjdbgL?editors=1000

Where to place and how to read configuration resource files in servlet based application?

Ex: In web.xml file the tag

<context-param>
        <param-name>chatpropertyfile</param-name>
        <!--  Name of the chat properties file. It contains the name and description                   of rooms.-->     
        <param-value>chat.properties</param-value>
    </context-param>

And chat.properties you can declare your properties like this

For Ex :

Jsp = Discussion about JSP can be made here.
Java = Talk about java and related technologies like J2EE.
ASP = Discuss about Active Server Pages related technologies like VBScript and JScript etc.
Web_Designing = Any discussion related to HTML, JavaScript, DHTML etc.
StartUp = Startup chat room. Chatter is added to this after he logs in.

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

Cannot add a project to a Tomcat server in Eclipse

In my case:

Project properties ? Project Facets. Make sure "Dynamic Web Module" is checked. Finally, I enter the version number "2.3" instead of "3.0". After that, the Apache Tomcat 5.5 runtime is listed in the "Runtimes" tab.

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

You can always add the "!" into your float-options. This way, latex tries really hard to place the figure where you want it (I mostly use [h!tb]), stretching the normal rules of type-setting.

I have found another solution:
Use the float-package. This way you can place the figures where you want them to be.

Pagination response payload from a RESTful API

generally, I make by simple way, whatever, I create a restAPI endpoint for example "localhost/api/method/:lastIdObtained/:countDateToReturn" with theses parameters, you can do it a simple request. in the service, eg. .net

jsonData function(lastIdObtained,countDatetoReturn){
'... write your code as you wish..'
and into select query make a filter
select top countDatetoreturn tt.id,tt.desc
 from tbANyThing tt
where id > lastIdObtained
order by id
}

In Ionic, when I scroll from bottom to top, I pass the zero value, when I get the answer, I set the value of the last id obtained, and when I slide from top to bottom, I pass the last registration id I got

Java String split removed empty values

String[] split = data.split("\\|",-1);

This is not the actual requirement in all the time. The Drawback of above is show below:

Scenerio 1:
When all data are present:
    String data = "5|6|7||8|9|10|";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 7
    System.out.println(splt.length); //output: 8

When data is missing:

Scenerio 2: Data Missing
    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output: 8

Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.

    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output:7

What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.

How to identify and switch to the frame in selenium webdriver when frame does not have id

1) goto html view

2) type iframe and find your required frame and count the value and switch to it using

oASelFW.driver.switchTo().frame(2); 

if it is first frame then use oASelFW.driver.switchTo().frame(0);

if it is second frame then use oASelFW.driver.switchTo().frame(1); respectively

How do I install Python OpenCV through Conda?

I tried following command and it works fine

conda install -c conda-forge opencv

once you hit the command it will ask for yes or no

enter image description here

If you select yes it will proceed and install all the required packages

Assign result of dynamic sql to variable

Most of these answers use sp_executesql as the solution to this problem. I have found that there are some limitations when using sp_executesql, which I will not go into, but I wanted to offer an alternative using EXEC(). I am using SQL Server 2008 and I know that some of the objects I am using in this script are not available in earlier versions of SQL Server so be wary.

DECLARE @CountResults TABLE (CountReturned INT)
DECLARE 
    @SqlStatement VARCHAR(8000) = 'SELECT COUNT(*) FROM table'
    , @Count INT

INSERT @CountResults
EXEC(@SqlStatement)

SET @Count = (SELECT CountReturned FROM @CountResults)
SELECT @Count

Postgresql: error "must be owner of relation" when changing a owner object

This solved my problem : Sample alter table statement to change the ownership.

ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

I had this issue on arch linux as well. The issue was pacman installed the package in a different location than MySQL was expecting. I was able to fix the issue with this:

sudo mysql_install_db --user=mysql --basedir=/usr/ --ldata=/var/lib/mysql/

Hope this helps someone!

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

The commercial solution, SpreadsheetGear for .NET will do it.

You can see live ASP.NET (C# and VB) samples here and download an evaluation version here.

Disclaimer: I own SpreadsheetGear LLC

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

Count number of lines in a git repository

: | git mktree | git diff --shortstat --stdin

Or:

git ls-tree @ | sed '1i\\' | git mktree --batch | xargs | git diff-tree --shortstat --stdin

Converting dd/mm/yyyy formatted string to Datetime

use DateTime.ParseExact

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)

null will use the current culture, which is somewhat dangerous. Try to supply a specific culture

DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)

How to change the color of an svg element?

For Example, in your HTML:

<body>
  <svg viewBox="" width="" height="">
    <path id="struct1" fill="#xxxxxx" d="M203.3,71.6c-.........."></path>
  </svg>
</body>

Use jQuery:

$("#struct1").css("fill","<desired colour>");

Use the auto keyword in C++ STL

It's additional information, and isn't an answer.

In C++11 you can write:

for (auto& it : s) {
    cout << it << endl;
}

instead of

for (auto it = s.begin(); it != s.end(); it++) {
    cout << *it << endl;
}

It has the same meaning.

Update: See the @Alnitak's comment also.

Razor/CSHTML - Any Benefit over what we have?

The biggest benefit is that the code is more succinct. The VS editor will also have the IntelliSense support that some of the other view engines don't have.

Declarative HTML Helpers also look pretty cool as doing HTML helpers within C# code reminds me of custom controls in ASP.NET. I think they took a page from partials but with the inline code.

So some definite benefits over the asp.net view engine.

With contrast to a view engine like spark though:

Spark is still more succinct, you can keep the if's and loops within a html tag itself. The markup still just feels more natural to me.

You can code partials exactly how you would do a declarative helper, you'd just pass along the variables to the partial and you have the same thing. This has been around with spark for quite awhile.

Display XML content in HTML page

If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:

$('#container').text(xmlString);

Here's how you'd do it with standard DOM methods:

document.getElementById('container')
        .appendChild(document.createTextNode(xmlString));

If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).

How to set $_GET variable

$_GET contains the keys / values that are passed to your script in the URL.

If you have the following URL :

http://www.example.com/test.php?a=10&b=plop

Then $_GET will contain :

array
  'a' => string '10' (length=2)
  'b' => string 'plop' (length=4)


Of course, as $_GET is not read-only, you could also set some values from your PHP code, if needed :

$_GET['my_value'] = 'test';

But this doesn't seem like good practice, as $_GET is supposed to contain data from the URL requested by the client.

how to use Spring Boot profiles

Working with Intellij, because I don't know how to set keyboard shortcut to mvn spring-boot:run -Dspring.profiles.active=dev, I have to do this:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <jvmArguments>
            -Dspring.profiles.active=dev
        </jvmArguments>
    </configuration>
</plugin>

Android Studio: Where is the Compiler Error Output Window?

If you are in android studio 3.1, Verify if file->Project Structure -> Source compatibility is empty. it should not have 1.8 set.

then press ok, the project will sync and error will disappear.

SQL using sp_HelpText to view a stored procedure on a linked server

It's the correct way to access linked DB:

EXEC  [ServerName].[DatabaseName].dbo.sp_HelpText 'storedProcName'

But make sure to mention dbo as it owns the sp_helptext.

Simple http post example in Objective-C?

Thanks a lot it worked , please note I did a typo in php as it should be mysqli_query( $con2, $sql )

How to count rows with SELECT COUNT(*) with SQLAlchemy?

Query for just a single known column:

session.query(MyTable.col1).count()

Clone() vs Copy constructor- which is recommended in java

Keep in mind that the copy constructor limits the class type to that of the copy constructor. Consider the example:

// Need to clone person, which is type Person
Person clone = new Person(person);

This doesn't work if person could be a subclass of Person (or if Person is an interface). This is the whole point of clone, is that it can can clone the proper type dynamically at runtime (assuming clone is properly implemented).

Person clone = (Person)person.clone();

or

Person clone = (Person)SomeCloneUtil.clone(person); // See Bozho's answer

Now person can be any type of Person assuming that clone is properly implemented.

Remove pattern from string with gsub

Just to point out that there is an approach using functions from the tidyverse, which I find more readable than gsub:

a %>% stringr::str_remove(pattern = ".*_")

Check if Internet Connection Exists with jQuery?

5 years later-version:

Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.

On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.

How to query a MS-Access Table from MS-Excel (2010) using VBA

Sub Button1_Click()
Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Documents and Settings\XXXXXX\My Documents\my_access_table.accdb"
    strSql = "SELECT Count(*) FROM mytable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.Fields(0) & " rows in MyTable"

    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

End Sub

How to enable external request in IIS Express?

If you're working with Visual Studio then follow these steps to access the IIS-Express over IP-Adress:

  1. Get your host IP-Adress: ipconfig in Windows Command Line
  2. GoTo

    $(SolutionDir)\.vs\config\applicationHost.config
    
  3. Find

    <site name="WebApplication3" id="2">
       <application path="/" applicationPool="Clr4IntegratedAppPool">
          <virtualDirectory path="/" physicalPath="C:\Users\user.name\Source\Repos\protoype-one\WebApplication3" />
       </application>
       <bindings>
         <binding protocol="http" bindingInformation="*:62549:localhost" />
       </bindings>
    </site>
    
  4. Add: <binding protocol="http" bindingInformation="*:62549:192.168.178.108"/>
    with your IP-Adress

  5. Run your Visual Studio with Administrator rights and everything should work
  6. Maybe look for some firewall issues if you try to connect from remote

jquery to validate phone number

I tried the below solution and it work fine for me.

/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

Tried below phone format:

  • +(123) 456 7899
  • (123) 456 7899
  • (123).456.7899
  • (123)-456-7899
  • 123-456-7899
  • 123 456 7899
  • 1234567899

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Unfortunately, modules aren't supported by many browsers right now.

This feature is only just beginning to be implemented in browsers natively at this time. It is implemented in many transpilers, such as TypeScript and Babel, and bundlers such as Rollup and Webpack.

Found on MDN

Should I use encodeURI or encodeURIComponent for encoding URLs?

Here is a summary.

  1. escape() will not encode @ * _ + - . /

    Do not use it.

  2. encodeURI() will not encode A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #

    Use it when your input is a complete URL like 'https://searchexample.com/search?q=wiki'

  3. encodeURIComponent() will not encode A-Z a-z 0-9 - _ . ! ~ * ' ( ) Use it when your input is part of a complete URL e.g const queryStr = encodeURIComponent(someString)

Compare two files report difference in python

The difflib library is useful for this, and comes in the standard library. I like the unified diff format.

http://docs.python.org/2/library/difflib.html#difflib.unified_diff

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
        )
        for line in diff:
            sys.stdout.write(line)

Outputs:

--- hosts0
+++ hosts1
@@ -1,5 +1,4 @@
 one
 two
-dogs
 three

And here is a dodgy version that ignores certain lines. There might be edge cases that don't work, and there are surely better ways to do this, but maybe it will be good enough for your purposes.

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
            n=0,
        )
        for line in diff:
            for prefix in ('---', '+++', '@@'):
                if line.startswith(prefix):
                    break
            else:
                sys.stdout.write(line[1:])

Good tool to visualise database schema?

How about the SQuirreL SQL Client? As mentioned in another SO question, this programs has the capability to generate a simple ER diagram.

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

After some googling, I found the advice to do the following, and it worked:

SQL> startup mount

ORACLE Instance started

SQL> recover database 

Media recovery complete

SQL> alter database open;

Database altered

Specific Time Range Query in SQL Server

I (using PostgrSQL on PGadmin4) queried for results that are after or on 21st Nov 2017 at noon, like this (considering the display format of hours on my database):

select * from Table1 where FIELD >='2017-11-21 12:00:00' 

How to remove a column from an existing table?

This can also be done through the SSMS GUI. The nice thing about this method is it warns you if there are any relationships on that column and can also automatically delete those as well.

  1. Put table in Design view (right click on table) like so:

enter image description here

  1. Right click on column in table's Design view and click "Delete Column"

enter image description here

As I stated before, if there are any relationships that would also need to be deleted, it will ask you at this point if you would like to delete those as well. You will likely need to do so to delete the column.

How do I uninstall a Windows service if the files do not exist anymore?

If the original Service .InstallLog and .InstallState files are still in the folder, you can try reinstalling the executable to replace the files, then use InstallUtil /u, then uninstall the program. It's a bit convoluted, but worked in a particular instance for me.

Deadly CORS when http://localhost is the origin

I decided not to touch headers and make a redirect on the server side instead and it woks like a charm.

The example below is for the current version of Angular (currently 9) and probably any other framework using webpacks DevServer. But I think the same principle will work on other backends.

So I use the following configuration in the file proxy.conf.json:

{
  "/api": {
    "target": "http://localhost:3000",
    "pathRewrite": {"^/api" : ""},
   "secure": false
 }
}

In case of Angular I serve with that configuration:

$ ng serve -o --proxy-config=proxy.conf.json

I prefer to use the proxy in the serve command, but you may also put this configuration to angular.json like this:

"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"
    },

See also:

https://www.techiediaries.com/fix-cors-with-angular-cli-proxy-configuration/

https://webpack.js.org/configuration/dev-server/#devserverproxy

dpi value of default "large", "medium" and "small" text views android

See in the android sdk directory.

In \platforms\android-X\data\res\values\themes.xml:

    <item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
    <item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
    <item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>

In \platforms\android-X\data\res\values\styles.xml:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
</style>

<style name="TextAppearance.Medium">
    <item name="android:textSize">18sp</item>
</style>

<style name="TextAppearance.Small">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?textColorSecondary</item>
</style>

TextAppearance.Large means style is inheriting from TextAppearance style, you have to trace it also if you want to see full definition of a style.

Link: http://developer.android.com/design/style/typography.html

How to start a stopped Docker container with a different command?

I took @Dmitriusan's answer and made it into an alias:

alias docker-run-prev-container='prev_container_id="$(docker ps -aq | head -n1)" && docker commit "$prev_container_id" "prev_container/$prev_container_id" && docker run -it --entrypoint=bash "prev_container/$prev_container_id"'

Add this into your ~/.bashrc aliases file, and you'll have a nifty new docker-run-prev-container alias which'll drop you into a shell in the previous container.

Helpful for debugging failed docker builds.

How to fit in an image inside span tag?

Try using a div tag and block for span!

<div>
  <span style="padding-right:3px; padding-top: 3px; display:block;">
    <img class="manImg" src="images/ico_mandatory.gif"></img>
  </span>
</div>

Pass request headers in a jQuery AJAX GET call

As of jQuery 1.5, there is a headers hash you can pass in as follows:

$.ajax({
    url: "/test",
    headers: {"X-Test-Header": "test-value"}
});

From http://api.jquery.com/jQuery.ajax:

headers (added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

Freeing up a TCP/IP port?

Kill the process that is listening to the port in question. I believe netstat shows you process ids.

Javascript for "Add to Home Screen" on iPhone?

This is also another good Home Screen script that support iphone/ipad, Mobile Safari, Android, Blackberry touch smartphones and Playbook .

https://github.com/h5bp/mobile-boilerplate/wiki/Mobile-Bookmark-Bubble

How to print the current Stack Trace in .NET without any exception?

You can also do this in the Visual Studio debugger without modifying the code.

  1. Create a breakpoint where you want to see the stack trace.
  2. Right-click the breakpoint and select "Actions..." in VS2015. In VS2010, select "When Hit...", then enable "Print a message".
  3. Make sure "Continue execution" is selected.
  4. Type in some text you would like to print out.
  5. Add $CALLSTACK wherever you want to see the stack trace.
  6. Run the program in the debugger.

Of course, this doesn't help if you're running the code on a different machine, but it can be quite handy to be able to spit out a stack trace automatically without affecting release code or without even needing to restart the program.

How do I get the HTTP status code with jQuery?

The third argument is the XMLHttpRequest object, so you can do whatever you want.

$.ajax({
  url  : 'http://example.com',
  type : 'post',
  data : 'a=b'
}).done(function(data, statusText, xhr){
  var status = xhr.status;                //200
  var head = xhr.getAllResponseHeaders(); //Detail header info
});

Can't stop rails server

I generally use:

killall ruby

OR

pkill -9 ruby

which will kill all ruby related processes that are running like rails server, rails console, etc.

How many threads can a Java VM support?

You can process any number of threads; there is no limit. I ran the following code while watching a movie and using NetBeans, and it worked properly/without halting the machine. I think you can keep even more threads than this program does.

class A extends Thread {
    public void run() {
        System.out.println("**************started***************");
        for(double i = 0.0; i < 500000000000000000.0; i++) {
            System.gc();
            System.out.println(Thread.currentThread().getName());
        }
        System.out.println("************************finished********************************");
    }
}

public class Manager {
    public static void main(String[] args) {
        for(double j = 0.0; j < 50000000000.0; j++) {
            A a = new A();
            a.start();
        }
    }
}

Custom exception type

Use the throw statement.

JavaScript doesn't care what the exception type is (as Java does). JavaScript just notices, there's an exception and when you catch it, you can "look" what the exception "says".

If you have different exception types you have to throw, I'd suggest to use variables which contain the string/object of the exception i.e. message. Where you need it use "throw myException" and in the catch, compare the caught exception to myException.

Get a timestamp in C in microseconds?

use an unsigned long long (i.e. a 64 bit unit) to represent the system time:

typedef unsigned long long u64;

u64 u64useconds;
struct timeval tv;

gettimeofday(&tv,NULL);
u64useconds = (1000000*tv.tv_sec) + tv.tv_usec;

How can I disable selected attribute from select2() dropdown Jquery?

As per select2 documentation: Click Here

If you wants to disable select2 then use this approach:

$(".js-example-disabled").prop("disabled", true);

If you wants to enable a disabled select2 box use this approach:

$(".js-example-disabled").prop("disabled", false);

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

java.util.zip.ZipException: error in opening zip file

Liquibase was getting this error for me. I resolved this after I debugged and watched liquibase try to load the libraries and found that it was erroring on the manifest files for commons-codec-1.6.jar. Essentially, there is either a corrupt zip file somewhere in your path or there is a incompatible version being used. When I did an explore on Maven repository for this library, I found there were newer versions and added the newer version to the pom.xml. I was able to proceed at this point.

Why doesn't Java offer operator overloading?

Groovy has operator overloading, and runs in the JVM. If you don't mind the performance hit (which gets smaller everyday). It's automatic based on method names. e.g., '+' calls the 'plus(argument)' method.

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

Pandas percentage of total with groupby

You need to make a second groupby object that groups by the states, and then use the div method:

import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': list(range(1, 7)) * 2,
               'sales': [np.random.randint(100000, 999999) for _ in range(12)]})

state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum'})
state = df.groupby(['state']).agg({'sales': 'sum'})
state_office.div(state, level='state') * 100


                     sales
state office_id           
AZ    2          16.981365
      4          19.250033
      6          63.768601
CA    1          19.331879
      3          33.858747
      5          46.809373
CO    1          36.851857
      3          19.874290
      5          43.273852
WA    2          34.707233
      4          35.511259
      6          29.781508

the level='state' kwarg in div tells pandas to broadcast/join the dataframes base on the values in the state level of the index.

How do I set a Windows scheduled task to run in the background?

As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.


It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.

enter image description here

enter image description here

enter image description here

Find PHP version on windows command line

Easy Method is: Just copy the file cmd.exe from c:/windows/system32/ and paste it to C:\xampp\php\ and run it, when the cmd opens type " php -v " without quotes and hit enter... you will get your php version.. thank you

Share data between AngularJS controllers

There are multiple ways to do this.

  1. Events - already explained well.

  2. ui router - explained above.

  3. Service - with update method displayed above
  4. BAD - Watching for changes.
  5. Another parent child approach rather than emit and brodcast -

*

<superhero flight speed strength> Superman is here! </superhero>
<superhero speed> Flash is here! </superhero>

*

app.directive('superhero', function(){
    return {
        restrict: 'E',
        scope:{}, // IMPORTANT - to make the scope isolated else we will pollute it in case of a multiple components.
        controller: function($scope){
            $scope.abilities = [];
            this.addStrength = function(){
                $scope.abilities.push("strength");
            }
            this.addSpeed = function(){
                $scope.abilities.push("speed");
            }
            this.addFlight = function(){
                $scope.abilities.push("flight");
            }
        },
        link: function(scope, element, attrs){
            element.addClass('button');
            element.on('mouseenter', function(){
               console.log(scope.abilities);
            })
        }
    }
});
app.directive('strength', function(){
    return{
        require:'superhero',
        link: function(scope, element, attrs, superHeroCtrl){
            superHeroCtrl.addStrength();
        }
    }
});
app.directive('speed', function(){
    return{
        require:'superhero',
        link: function(scope, element, attrs, superHeroCtrl){
            superHeroCtrl.addSpeed();
        }
    }
});
app.directive('flight', function(){
    return{
        require:'superhero',
        link: function(scope, element, attrs, superHeroCtrl){
            superHeroCtrl.addFlight();
        }
    }
});

keycode 13 is for which key

It's the Return or Enter key on keyboard.