Programs & Examples On #Rml

RML is the Report Markup Language - a member of the XML family of languages, and the XML dialect used by rml2pdf to produce documents in Adobe's Portable Document Format (PDF).

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Flutter: RenderBox was not laid out

I had a simmilar problem, but in my case I was put a row in the leading of the Listview, and it was consumming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recomend to check if the problem is a widget larger than its containner can have.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.

Example python implementation:

import sys

inner_loop = 0

def collatz_sequence(N, cache):
    global inner_loop

    l = [ ]
    stop = False
    n = N

    tails = [ ]

    while not stop:
        inner_loop += 1
        tmp = n
        l.append(n)
        if n <= 1:
            stop = True  
        elif n in cache:
            stop = True
        elif n % 2:
            n = 3*n + 1
        else:
            n = n // 2
        tails.append((tmp, len(l)))

    for key, offset in tails:
        if not key in cache:
            cache[key] = l[offset:]

    return l

def gen_sequence(l, cache):
    for elem in l:
        yield elem
        if elem in cache:
            yield from gen_sequence(cache[elem], cache)
            raise StopIteration

if __name__ == "__main__":
    le_cache = {}

    for n in range(1, 4711, 5):
        l = collatz_sequence(n, le_cache)
        print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))

    print("inner_loop = {}".format(inner_loop))

Angular 2 Unit Tests: Cannot find name 'describe'

With [email protected] or later you can install types with:

npm install -D @types/jasmine

Then import the types automatically using the types option in tsconfig.json:

"types": ["jasmine"],

This solution does not require import {} from 'jasmine'; in each spec file.

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

disabling spring security in spring boot app

just add

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)

Updating state on props change in React Form

You Probably Don't Need Derived State

1. Set a key from the parent

When a key changes, React will create a new component instance rather than update the current one. Keys are usually used for dynamic lists but are also useful here.

2. Use getDerivedStateFromProps / componentWillReceiveProps

If key doesn’t work for some reason (perhaps the component is very expensive to initialize)

By using getDerivedStateFromProps you can reset any part of state but it seems a little buggy at this time (v16.7)!, see the link above for the usage

CORS with spring-boot and angularjs not working

Step 1

By annotating the controller with @CrossOrigin annotation will allow the CORS configurations.

@CrossOrigin
@RestController
public class SampleController { 
  .....
}

Step 2

Spring already has a CorsFilter even though You can just register your own CorsFilter as a bean to provide your own configuration as follows.

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); // Provide list of origins if you want multiple origins
    config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
    config.setAllowCredentials(true);
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

This should work

 BitmapFactory.Options options = new BitmapFactory.Options();
 options.inSampleSize = 8;

 mBitmapSampled = BitmapFactory.decodeFile(mCurrentPhotoPath,options);

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

index.html should be inside templates, as I know. So, your second attempt looks correct.

But, as the error message says, index.html looks like having some errors. E.g. the in the third line, the meta tag should be actually head tag, I think.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

This problem is caused by RecyclerView Data modified in different thread. The best way is checking all data access. And a workaround is wrapping LinearLayoutManager.

Previous answer

There was actually a bug in RecyclerView and the support 23.1.1 still not fixed.

For a workaround, notice that backtrace stacks, if we can catch this Exception in one of some class it may skip this crash. For me, I create a LinearLayoutManagerWrapper and override the onLayoutChildren:

public class WrapContentLinearLayoutManager extends LinearLayoutManager {
    //... constructor
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
            super.onLayoutChildren(recycler, state);
        } catch (IndexOutOfBoundsException e) {
            Log.e("TAG", "meet a IOOBE in RecyclerView");
        }
    }
}

Then set it to RecyclerView:

RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view);

recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));

Actually catch this exception, and seems no any side-effect yet.

Also, if you use GridLayoutManager or StaggeredGridLayoutManager you must create a wrapper for it.

Notice: The RecyclerView may be in a wrong internal state.

RecyclerView: Inconsistency detected. Invalid item position

In my case, I was updating the items and calling notifyDataSetChanged in a non-UI thread. Most of the time it worked, but when a lot of changes happened quickly, it'd crash. When I did, instead, basically

activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        changeData();
        notifyDataSetChanged();
    }
});

then it stopped crashing.

"Series objects are mutable and cannot be hashed" error

Shortly: gene_name[x] is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.

Further explanation:

Mutable objects are objects which value can be changed. For example, list is a mutable object, since you can append to it. int is an immutable object, because you can't change it. When you do:

a = 5;
a = 3;

You don't change the value of a, you create a new object and make a point to its value.

Mutable objects cannot be hashed. See this answer.

To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple, string, int.

How to open a different activity on recyclerView item onclick

you can implement your adapter's onClickListener:

  public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>implements View.OnClickListener

and use interface with method in it

public interface mClickListener {
    public void mClick(View v, int position);
}

and in your onClick method call the method in the interface and pass it the view and position

in your main activity implement that interface

public class MainActivity extends ActionBarActivity implements AdapterClass.mClickListener

and override that method

@Override
public void onCommentsClick(View v, int position) {
    final Intent intent = new Intent(this, OtherActivity.class);
}

as its better to manage your activity transition by the activity not other classes

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

in your baseadapter class constructor try to initialize LayoutInflater, normally i preferred this way,

public ClassBaseAdapter(Context context,ArrayList<Integer> listLoanAmount) {
    this.context = context;
    this.listLoanAmount = listLoanAmount;
    this.layoutInflater = LayoutInflater.from(context);
}

at the top of the class create LayoutInflater variable, hope this will help you

Base64: java.lang.IllegalArgumentException: Illegal character

The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.

For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.

static String getBase64EncodedCipherText(String cipherText) {
    byte[] cText = cipherText.getBytes();
    // return an ISO-8859-1 encoded String
    return Base64.getEncoder().encodeToString(cText);
}

static String getBase64DecodedCipherText(String encodedCipherText) throws IOException {
    return new String((Base64.getDecoder().decode(encodedCipherText)));
}

public static void main(String[] args) {
    try {
        String cText = getRawCipherText(null, "Hello World of Encryption...");

        System.out.println("Text to encrypt/encode: Hello World of Encryption...");
        // This output is a simple sanity check to display that the text
        // has indeed been converted to a cipher text which 
        // is unreadable by all but the most intelligent of programmers.
        // It is absolutely inhuman of me to do such a thing, but I am a
        // rebel and cannot be trusted in any way.  Please look away.
        System.out.println("RAW CIPHER TEXT: " + cText);
        cText = getBase64EncodedCipherText(cText);
        System.out.println("BASE64 ENCODED: " + cText);
        // There he goes again!!
        System.out.println("BASE64 DECODED:  " + getBase64DecodedCipherText(cText));
        System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

The output looks like:

Text to encrypt/encode: Hello World of Encryption...
RAW CIPHER TEXT: q$;?C?l??<8??U???X[7l
BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
BASE64 DECODED:  q$;?C?l??<8??U???X[7l``
DECODED CIPHER TEXT: Hello World of Encryption...

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

The Up Button is usually activated for Low-level Activities. In your manifest I only see the MainActivity. I don't think it makes sense to activate the up button for the main activity. Create an activity, then in the manifest add the parentActivityName attribute. Then activate the up button on the activity's onCreate method.
This should help.
https://developer.android.com/training/appbar/up-action.html

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

This is the error line:

if (called_from.equalsIgnoreCase("add")) {  --->38th error line

This means that called_from is null. Simple check if it is null above:

String called_from = getIntent().getStringExtra("called");

if(called_from == null) {
    called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
    // do whatever
} else {
    // do whatever
}

That way, if called_from is null, it'll execute the else part of your if statement.

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

Change

 mAdapter = new RecordingsListAdapter(this, recordings);

to

 mAdapter = new RecordingsListAdapter(getActivity(), recordings);

and also make sure that recordings!=null at mAdapter = new RecordingsListAdapter(this, recordings);

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

In a previous answer, it was suggested to use this line of code for .Net 4.5:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5

I would encourage you to OR that value in to whatever the existing values are like this:

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; // .NET 4.5

If you look at the list of values, you notice that they are a power of two. This way, in the future when things shift to TLS 2.0 for example, your code will still work.

Error inflating class android.support.v7.widget.Toolbar?

I was able to solve this problem by replacing the following:

In the Toolbar layout, replace everything which is like this:

android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"

with

android:minHeight="@dimen/abc_action_bar_default_height_material"
android:background="@color/myColor"

Android: making a fullscreen application

Update Answer I added android:windowIsTranslucent in case you have white screen in start of activity

just create new Style in values/styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <!-- to hide white screen in start of window -->
    <item name="android:windowIsTranslucent">true</item>
    </style>

</resources>

from your AndroidManifest.xml add style to your activity

android:theme="@style/AppTheme"

to be like this

<activity android:name=".Splash"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

This Activity already has an action bar supplied by the window decor

If you get the error on this line:

setSupportActionBar(...);

You need to check if your activity is referring to a theme that contains a toolbar. Your application's AppTheme might already contain a toolbar, such as

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

and you are trying to add a second one. If you want to use your application's AppTheme, you need to remove the theme from your activity, in the manifest.xml file.

For example:

<activity
    android:name=".ui.activities.SettingsActivity"
    android:theme="@style/AppTheme1" /> --> remove this theme

Serving static web resources in Spring Boot & Spring Security application

This may be an answer (for spring boot 2) and a question at the same time. It seems that in spring boot 2 combined with spring security everything (means every route/antmatcher) is protected by default if you use an individual security mechanism extended from

WebSecurityConfigurerAdapter

If you don´t use an individual security mechanism, everything is as it was?

In older spring boot versions (1.5 and below) as Andy Wilkinson states in his above answer places like public/** or static/** are permitted by default.

So to sum this question/answer up - if you are using spring boot 2 with spring security and have an individual security mechanism you have to exclusivley permit access to static contents placed on any route. Like so:

@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

private final ThdAuthenticationProvider thdAuthenticationProvider;

private final ThdAuthenticationDetails thdAuthenticationDetails;

/**
 * Overloaded constructor.
 * Builds up the needed dependencies.
 *
 * @param thdAuthenticationProvider a given authentication provider
 * @param thdAuthenticationDetails  given authentication details
 */
@Autowired
public SpringSecurityConfiguration(@NonNull ThdAuthenticationProvider thdAuthenticationProvider,
                                   @NonNull ThdAuthenticationDetails thdAuthenticationDetails) {
    this.thdAuthenticationProvider = thdAuthenticationProvider;
    this.thdAuthenticationDetails = thdAuthenticationDetails;
}

/**
 * Creates the AuthenticationManager with the given values.
 *
 * @param auth the AuthenticationManagerBuilder
 */
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {

    auth.authenticationProvider(thdAuthenticationProvider);
}

/**
 * Configures the http Security.
 *
 * @param http HttpSecurity
 * @throws Exception a given exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            .antMatchers("/management/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
            Role.Role_Admin.getValue())
            .antMatchers("/settings/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
            Role.Role_Admin.getValue())

            .anyRequest()
            .fullyAuthenticated()
            .and()
            .formLogin()
            .authenticationDetailsSource(thdAuthenticationDetails)
            .loginPage("/login").permitAll()
            .defaultSuccessUrl("/bundle/index", true)
            .failureUrl("/denied")
            .and()
            .logout()
            .invalidateHttpSession(true)
            .logoutSuccessUrl("/login")
            .logoutUrl("/logout")
            .and()
            .exceptionHandling()
            .accessDeniedHandler(new CustomAccessDeniedHandler());
}

}

Please mind this line of code, which is new:

.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

If you use spring boot 1.5 and below you don´t need to permit these locations (static/public/webjars etc.) explicitly.

Here is the official note, what has changed in the new security framework as to old versions of itself:

Security changes in Spring Boot 2.0 M4

I hope this helps someone. Thank you! Have a nice day!

Swift Beta performance: sorting arrays

TL;DR: Yes, the only Swift language implementation is slow, right now. If you need fast, numeric (and other types of code, presumably) code, just go with another one. In the future, you should re-evaluate your choice. It might be good enough for most application code that is written at a higher level, though.

From what I'm seeing in SIL and LLVM IR, it seems like they need a bunch of optimizations for removing retains and releases, which might be implemented in Clang (for Objective-C), but they haven't ported them yet. That's the theory I'm going with (for now… I still need to confirm that Clang does something about it), since a profiler run on the last test-case of this question yields this “pretty” result:

Time profiling on -O3 Time profiling on -Ofast

As was said by many others, -Ofast is totally unsafe and changes language semantics. For me, it's at the “If you're going to use that, just use another language” stage. I'll re-evaluate that choice later, if it changes.

-O3 gets us a bunch of swift_retain and swift_release calls that, honestly, don't look like they should be there for this example. The optimizer should have elided (most of) them AFAICT, since it knows most of the information about the array, and knows that it has (at least) a strong reference to it.

It shouldn't emit more retains when it's not even calling functions which might release the objects. I don't think an array constructor can return an array which is smaller than what was asked for, which means that a lot of checks that were emitted are useless. It also knows that the integer will never be above 10k, so the overflow checks can be optimized (not because of -Ofast weirdness, but because of the semantics of the language (nothing else is changing that var nor can access it, and adding up to 10k is safe for the type Int).

The compiler might not be able to unbox the array or the array elements, though, since they're getting passed to sort(), which is an external function and has to get the arguments it's expecting. This will make us have to use the Int values indirectly, which would make it go a bit slower. This could change if the sort() generic function (not in the multi-method way) was available to the compiler and got inlined.

This is a very new (publicly) language, and it is going through what I assume are lots of changes, since there are people (heavily) involved with the Swift language asking for feedback and they all say the language isn't finished and will change.

Code used:

import Cocoa

let swift_start = NSDate.timeIntervalSinceReferenceDate();
let n: Int = 10000
let x = Int[](count: n, repeatedValue: 1)
for i in 0..n {
    for j in 0..n {
        let tmp: Int = x[j]
        x[i] = tmp
    }
}
let y: Int[] = sort(x)
let swift_stop = NSDate.timeIntervalSinceReferenceDate();

println("\(swift_stop - swift_start)s")

P.S: I'm not an expert on Objective-C nor all the facilities from Cocoa, Objective-C, or the Swift runtimes. I might also be assuming some things that I didn't write.

Saving binary data as file using JavaScript from a browser

Use FileSaver.js. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it:
     https://github.com/eligrey/FileSaver.js

Minified version is really small at < 2.5KB, gzipped < 1.2KB.

Usage:

/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);

You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
     https://github.com/eligrey/Blob.js

Consider StreamSaver.js if you have files larger than blob's size limitations.

Complete example:

_x000D_
_x000D_
/* Two options_x000D_
 * 1. Get FileSaver.js from here_x000D_
 *     https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
 *     <script src="FileSaver.min.js" />_x000D_
 *_x000D_
 * Or_x000D_
 *_x000D_
 * 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
 *    then a simple implementation of saveAs function can be:_x000D_
 */_x000D_
function saveAs(blob, fileName) {_x000D_
    var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
    var anchorElem = document.createElement("a");_x000D_
    anchorElem.style = "display: none";_x000D_
    anchorElem.href = url;_x000D_
    anchorElem.download = fileName;_x000D_
_x000D_
    document.body.appendChild(anchorElem);_x000D_
    anchorElem.click();_x000D_
_x000D_
    document.body.removeChild(anchorElem);_x000D_
_x000D_
    // On Edge, revokeObjectURL should be called only after_x000D_
    // a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
    setTimeout(function() {_x000D_
        window.URL.revokeObjectURL(url);_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
    // convert base64 string to byte array_x000D_
    var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
    var byteNumbers = new Array(byteCharacters.length);_x000D_
    for (var i = 0; i < byteCharacters.length; i++) {_x000D_
        byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
    }_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
    _x000D_
    // now that we have the byte array, construct the blob from it_x000D_
    var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
    var fileName1 = "cool.gif";_x000D_
    saveAs(blob1, fileName1);_x000D_
_x000D_
    // saving text file_x000D_
    var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
    var fileName2 = "cool.txt";_x000D_
    saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_


Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js for supporting IE 11).
You can also save from a canvas element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.

Demos: https://eligrey.com/demos/FileSaver.js/

Blog post by author of FileSaver.js: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers

Note 2: Failed to execute 'atob' on 'Window'

Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
                See http://caniuse.com/#search=blob

Note 4: IE < 10 support (I've not tested this part):
                https://github.com/eligrey/FileSaver.js#ie--10
                https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476

Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html

Note 5: Creating a BLOB from a Base64 string in JavaScript

Note 6: FileSaver.js examples: https://github.com/eligrey/FileSaver.js#examples

Generate random array of floats between a range

np.random.random_sample(size) will generate random floats in the half-open interval [0.0, 1.0).

Intent from Fragment to Activity

public class OneWayFragment extends Fragment {

    ImageView img_search;


public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.one_way_fragment, container, false);
        img_search = (ImageView) view.findViewById(R.id.search);


        img_search.setOnClickListener(new View.OnClickListener() {
            @Override`enter code here`
            public void onClick(View v) {
                Intent displayFlights = new Intent(getActivity(), SelectFlight.class);
                startActivity(displayFlights);
            }
        });

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

Important to know in what file it comes to this error (in you example it is META-INF/LICENSE.txt) , in my case it was in META-INF/LICENSE [without ".txt"], and then in the file META-INF/ASL2.0 so I added to my build.gradle this lines:

android {
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/ASL2.0'
    }
}

Very important (!) -> add the name of the file in the same style, that you see it in the error message: the text is case sensitive, and there is a difference between *.txt and *(without "txt").

Read line with Scanner

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

import java.io.File;
import java.util.Scanner;

/**
 *
 * @author zsagga
 */
class openFile {
        private Scanner x ; 
        int count = 0 ; 
        String path = "C:\\Users\\zsagga\\Documents\\NetBeansProjects\\JavaApplication1\\src\\javaapplication1\\Readthis.txt"; 


    public void openFile() {
//                System.out.println("I'm Here");
        try {
            x = new Scanner(new File(path)); 

        } 
        catch (Exception e) {
            System.out.println("Could not find a file");
        }
    }

    public void readFile() {

        while (x.hasNextLine()){
            count ++ ;
            x.nextLine();     
        }
        System.out.println(count);
    }

    public void closeFile() {
        x.close();
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication1;

/**
 *
 * @author zsagga
 */
public class JavaApplication1 {

    public static void main(String[] args) {
        // TODO code application logic here
        openFile r =  new openFile(); 
        r.openFile(); 
        r.readFile();
        r.closeFile(); 

    }
}

How can I parse a local JSON file from assets folder into a ListView?

{ // json object node
    "formules": [ // json array formules
    { // json object 
      "formule": "Linear Motion", // string
      "url": "qp1"
    }

What you are doing

  Context context = null; // context is null 
    try {
        String jsonLocation = AssetJSONFile("formules.json", context);

So change to

   try {
        String jsonLocation = AssetJSONFile("formules.json", CatList.this);

To parse

I believe you get the string from the assests folder.

try
{
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject jsonobject = new JSONObject(jsonLocation);
JSONArray jarray = (JSONArray) jsonobject.getJSONArray("formules");
for(int i=0;i<jarray.length();i++)
{
JSONObject jb =(JSONObject) jarray.get(i);
String formula = jb.getString("formule");
String url = jb.getString("url");
}
} catch (IOException e) {
        e.printStackTrace();
} catch (JSONException e) {
        e.printStackTrace();
}

android.view.InflateException: Binary XML file: Error inflating class fragment

I had the same problem, issue, tried all the answers in this thread to no avail. My solution was, I hadn't added an ID in the Activity XML. I didn't think it would matter, but it did.

So in the Activity XML I had:

<fragment
    android:name="com.covle.hellocarson.SomeFragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

But should've had:

<fragment
    android:id="@+id/some_fragment"
    android:name="com.covle.hellocarson.SomeFragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

If someone would be happy to comment on why this is, I'm all ears, to other, I hope this helps.

Android ClassNotFoundException: Didn't find class on path

I had this issue recently and I am using Android Studio 0.8.4

The problem was the fact that I decided to rename an XML menu layout file that was called main.xml.

Right click on it and chose Refactor --> Rename. Before renaming it, be sure uncheck "Search in comments and strings" and pressed Refactor.

Because my file was originally named 'main', it renamed critical paths in the app.iml and build.gradle, mainly the java.srcDirs in the build.gradle, since the path is defined as 'src/main/java'.

I hope this helps anyone that may be experiencing this issue.

The specified child already has a parent. You must call removeView() on the child's parent first

frameLayout.addView(yourView); <----- if you are getting error on this line remove view from it's parent first

if (yourView.getParent() != null)

((ViewGroup) yourView.getParent()).removeView(yourView); frameLayout.addView(yourView); (Add view to layout)

Integrate ZXing in Android Studio

Anybody facing the same issues, follow the simple steps:

Import the project android from downloaded zxing-master zip file using option Import project (Eclipse ADT, Gradle, etc.) and add the dollowing 2 lines of codes in your app level build.gradle file and and you are ready to run.

So simple, yahh...

dependencies {
        // https://mvnrepository.com/artifact/com.google.zxing/core
        compile group: 'com.google.zxing', name: 'core', version: '3.2.1'
        // https://mvnrepository.com/artifact/com.google.zxing/android-core
        compile group: 'com.google.zxing', name: 'android-core', version: '3.2.0'

    }

You can always find latest version core and android core from below links:

https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1 https://mvnrepository.com/artifact/com.google.zxing/android-core/3.2.0

UPDATE (29.05.2019)

Add these dependencies instead:

dependencies {
    implementation 'com.google.zxing:core:3.4.0'
    implementation 'com.google.zxing:android-core:3.3.0'
}

Safely limiting Ansible playbooks to a single machine?

AWS users using the EC2 External Inventory Script can simply filter by instance id:

ansible-playbook sample-playbook.yml --limit i-c98d5a71 --list-hosts

This works because the inventory script creates default groups.

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

For my list view am using custom Adapter which extends ArrayAdapter. in listiview i have 2 buttons one of the buttons as Custom AlertDialogBox. Ex: Activity parentActivity; Constructor for Adapter `

public CustomAdapter(ArrayList<Contact> data, Activity parentActivity,Context context) {
        super(context,R.layout.listdummy,data);
        this.mContext   =   context;
        this.parentActivity  =   parentActivity;
    }

` calling Adapter from MainActivty

_x000D_
_x000D_
adapter = new CustomAdapter(dataModels,MainActivity.this,this);
_x000D_
_x000D_
_x000D_

now write ur alertdialog inside ur button which is in the Adapter class

_x000D_
_x000D_
viewHolder.update.setOnClickListener(new View.OnClickListener() {_x000D_
            @Override_x000D_
            public void onClick(final View view) {_x000D_
            _x000D_
_x000D_
                AlertDialog.Builder alertDialog =   new AlertDialog.Builder(parentActivity);_x000D_
                alertDialog.setTitle("Updating");_x000D_
                alertDialog.setCancelable(false);_x000D_
_x000D_
                LayoutInflater layoutInflater   = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);_x000D_
                 @SuppressLint("InflateParams") final View view1   =   layoutInflater.inflate(R.layout.dialog,null);_x000D_
                alertDialog.setView(view1);_x000D_
                alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {_x000D_
                    @Override_x000D_
                    public void onClick(DialogInterface dialogInterface, int i) {_x000D_
                        dialogInterface.cancel();_x000D_
                    }_x000D_
                });_x000D_
                alertDialog.setPositiveButton("Update", new DialogInterface.OnClickListener() {_x000D_
                    @Override_x000D_
                    public void onClick(DialogInterface dialogInterface, int i) {_x000D_
_x000D_
                    //ur logic_x000D_
                            }_x000D_
                    }_x000D_
                });_x000D_
                  alertDialog.create().show();_x000D_
_x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

As a Library Project

You should add the resources in a library project as per http://developer.android.com/tools/support-library/setup.html

Section > Adding libraries with resources

You then add the android-support-v7-appcompat library in your workspace and then add it as a reference to your app project.

Defining all the resources in your app project will also work (but there are a lot of definitions to add and you have missed some of them), and it is not the recommended approach.

"Specified argument was out of the range of valid values"

I was also getting same issue as i tried using value 0 in non-based indexing,i.e starting with 1, not with zero

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

Add before OpenDatabase this lines:

File outFile = new File(Environment.getDataDirectory(), outFileName);
outFile.setWritable(true);
SQLiteDatabase.openDatabase(outFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);

$location / switching between html5 and hashbang mode / link rewriting

Fur future readers, if you are using Angular 1.6, you also need to change the hashPrefix:

appModule.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('');
}]);

Don't forget to set the base in your HTML <head>:

<head>
    <base href="/">
    ...
</head>

More info about the changelog here.

How to pass values between Fragments

step 1.to send data from fragment to activity

Intent intent = new Intent(getActivity().getBaseContext(),
                        TargetActivity.class);
                intent.putExtra("message", message);
                getActivity().startActivity(intent);

step 2.to receive this data in Activity:

Intent intent = getIntent();
String message = intent.getStringExtra("message");

step 3. to send data from activity to another activity follow normal approach

Intent intent = new Intent(MainActivity.this,
                        TargetActivity.class);
                intent.putExtra("message", message);
                startActivity(intent);

step 4 to receive this data in activity

     Intent intent = getIntent();
  String message = intent.getStringExtra("message");

Step 5. From Activity you can send data to Fragment with intent as:

Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
  //set Fragmentclass Arguments
Fragmentclass fragobj=new Fragmentclass();
fragobj.setArguments(bundle);

and to receive in fragment in Fragment onCreateView method:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
          String strtext=getArguments().getString("message");

    return inflater.inflate(R.layout.fragment, container, false);
    }

Android - How to download a file from a webserver

use AsyncTask and

put your download file code in doinbackground of it..

android don't allow anymore to do heavy tasks on main thread to avoid ANR(Application not responding) error

Import Python Script Into Another?

It depends on how the code in the first file is structured.

If it's just a bunch of functions, like:

# first.py
def foo(): print("foo")
def bar(): print("bar")

Then you could import it and use the functions as follows:

# second.py
import first

first.foo()    # prints "foo"
first.bar()    # prints "bar"

or

# second.py
from first import foo, bar

foo()          # prints "foo"
bar()          # prints "bar"

or, to import all the names defined in first.py:

# second.py
from first import *

foo()          # prints "foo"
bar()          # prints "bar"

Note: This assumes the two files are in the same directory.

It gets a bit more complicated when you want to import names (functions, classes, etc) from modules in other directories or packages.

When should an IllegalArgumentException be thrown?

The API doc for IllegalArgumentException:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

From looking at how it is used in the JDK libraries, I would say:

  • It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.

  • It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).

I would use IllegalArgumentException to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.

Setting DEBUG = False causes 500 Error

I had one view that threw a 500 error in debug=false but worked in debug=true. For anyone who is getting this kind of thing and Allowed Hosts is not the problem, I fixed my view by updating a template's static tag that was pointing to the wrong location.

So I'd suggest just checking links and tags are airtight in any templates used, maybe certain things slip through the net in debug but give errors in production.

Unable instantiate android.gms.maps.MapFragment

I faced this issue while using Android SDK for x86 in a Windows 7 64-bit machine. I downloaded the Android SDK 64-bit version, made Eclipse see it in Window > Preferences > Android > SDK location and the issue stopped occurring.

Google Maps Android API v2 Authorization failure

I am migrating from V1 to V2 of Google Maps. I was getting this failure trying to run the app via Eclipse. The root cause for me was using my release certificate keystore rather than the Android debug keystore which is what gets used when you run it via Eclipse. The following command (OSX/Linux) will get you the SHA1 key of the debug keystore:

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

If you are using Windows 7 instead, you would use this command:

keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

It is probably best to uninstall your app completely from your device before trying with a new key as Android caches the security credentials.

Convert UNIX epoch to Date object

With library(lubridate), numeric representations of date and time saved as the number of seconds since 1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime():

lubridate::as_datetime(1352068320)

[1] "2012-11-04 22:32:00 UTC"

Separation of business logic and data access in django

First of all, Don't repeat yourself.

Then, please be careful not to overengineer, sometimes it is just a waste of time, and makes someone lose focus on what is important. Review the zen of python from time to time.

Take a look at active projects

  • more people = more need to organize properly
  • the django repository they have a straightforward structure.
  • the pip repository they have a straigtforward directory structure.
  • the fabric repository is also a good one to look at.

    • you can place all your models under yourapp/models/logicalgroup.py
  • e.g User, Group and related models can go under yourapp/models/users.py
  • e.g Poll, Question, Answer ... could go under yourapp/models/polls.py
  • load what you need in __all__ inside of yourapp/models/__init__.py

More about MVC

  • model is your data
    • this includes your actual data
    • this also includes your session / cookie / cache / fs / index data
  • user interacts with controller to manipulate the model
    • this could be an API, or a view that saves/updates your data
    • this can be tuned with request.GET / request.POST ...etc
    • think paging or filtering too.
  • the data updates the view
    • the templates take the data and format it accordingly
    • APIs even w/o templates are part of the view; e.g. tastypie or piston
    • this should also account for the middleware.

Take advantage of middleware / templatetags

  • If you need some work to be done for each request, middleware is one way to go.
    • e.g. adding timestamps
    • e.g. updating metrics about page hits
    • e.g. populating a cache
  • If you have snippets of code that always reoccur for formatting objects, templatetags are good.
    • e.g. active tab / url breadcrumbs

Take advantage of model managers

  • creating User can go in a UserManager(models.Manager).
  • gory details for instances should go on the models.Model.
  • gory details for queryset could go in a models.Manager.
  • you might want to create a User one at a time, so you may think that it should live on the model itself, but when creating the object, you probably don't have all the details:

Example:

class UserManager(models.Manager):
   def create_user(self, username, ...):
      # plain create
   def create_superuser(self, username, ...):
      # may set is_superuser field.
   def activate(self, username):
      # may use save() and send_mail()
   def activate_in_bulk(self, queryset):
      # may use queryset.update() instead of save()
      # may use send_mass_mail() instead of send_mail()

Make use of forms where possible

A lot of boilerplate code can be eliminated if you have forms that map to a model. The ModelForm documentation is pretty good. Separating code for forms from model code can be good if you have a lot of customization (or sometimes avoid cyclic import errors for more advanced uses).

Use management commands when possible

  • e.g. yourapp/management/commands/createsuperuser.py
  • e.g. yourapp/management/commands/activateinbulk.py

if you have business logic, you can separate it out

  • django.contrib.auth uses backends, just like db has a backend...etc.
  • add a setting for your business logic (e.g. AUTHENTICATION_BACKENDS)
  • you could use django.contrib.auth.backends.RemoteUserBackend
  • you could use yourapp.backends.remote_api.RemoteUserBackend
  • you could use yourapp.backends.memcached.RemoteUserBackend
  • delegate the difficult business logic to the backend
  • make sure to set the expectation right on the input/output.
  • changing business logic is as simple as changing a setting :)

backend example:

class User(db.Models):
    def get_present_name(self): 
        # property became not deterministic in terms of database
        # data is taken from another service by api
        return remote_api.request_user_name(self.uid) or 'Anonymous' 

could become:

class User(db.Models):
   def get_present_name(self):
      for backend in get_backends():
         try:
            return backend.get_present_name(self)
         except: # make pylint happy.
            pass
      return None

more about design patterns

more about interface boundaries

  • Is the code you want to use really part of the models? -> yourapp.models
  • Is the code part of business logic? -> yourapp.vendor
  • Is the code part of generic tools / libs? -> yourapp.libs
  • Is the code part of business logic libs? -> yourapp.libs.vendor or yourapp.vendor.libs
  • Here is a good one: can you test your code independently?
    • yes, good :)
    • no, you may have an interface problem
    • when there is clear separation, unittest should be a breeze with the use of mocking
  • Is the separation logical?
    • yes, good :)
    • no, you may have trouble testing those logical concepts separately.
  • Do you think you will need to refactor when you get 10x more code?
    • yes, no good, no bueno, refactor could be a lot of work
    • no, that's just awesome!

In short, you could have

  • yourapp/core/backends.py
  • yourapp/core/models/__init__.py
  • yourapp/core/models/users.py
  • yourapp/core/models/questions.py
  • yourapp/core/backends.py
  • yourapp/core/forms.py
  • yourapp/core/handlers.py
  • yourapp/core/management/commands/__init__.py
  • yourapp/core/management/commands/closepolls.py
  • yourapp/core/management/commands/removeduplicates.py
  • yourapp/core/middleware.py
  • yourapp/core/signals.py
  • yourapp/core/templatetags/__init__.py
  • yourapp/core/templatetags/polls_extras.py
  • yourapp/core/views/__init__.py
  • yourapp/core/views/users.py
  • yourapp/core/views/questions.py
  • yourapp/core/signals.py
  • yourapp/lib/utils.py
  • yourapp/lib/textanalysis.py
  • yourapp/lib/ratings.py
  • yourapp/vendor/backends.py
  • yourapp/vendor/morebusinesslogic.py
  • yourapp/vendor/handlers.py
  • yourapp/vendor/middleware.py
  • yourapp/vendor/signals.py
  • yourapp/tests/test_polls.py
  • yourapp/tests/test_questions.py
  • yourapp/tests/test_duplicates.py
  • yourapp/tests/test_ratings.py

or anything else that helps you; finding the interfaces you need and the boundaries will help you.

Set View Width Programmatically

The first parameter to LayoutParams is the width and the second is the height. So if you want the width to be FILL_PARENT, but the width to be, say, 20px, then use something new LayoutParams(FILL_PARENT, 20). Of course you should never use actual pixels in your code; you'll need to conver that to density-independent pixels, but you get the idea. Also, you need to make sure your parent LinearLayout has the right width and height that you're looking for. Seems to be you want the LinearLayout to fill the parent width-wise and then have the adview fill that linearlayout witdh-wise as well, so you probably need to specify android:layout_width:"fill_parent" and android:layout_height:"wrap_content" in your linear layout's xml.

how to console.log result of this ajax call?

Why not handle the error within the call?

i.e.

$.ajax({
    type: 'POST',
    url: 'loginCheck',
    data: $(formLogin).serialize(),
    dataType: 'json',
    error: function(req, err){ console.log('my message' + err); }
});

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

 @Override
    protected void onPostExecute(final Boolean success) {
        mProgressDialog.dismiss();
        mProgressDialog = null;

setting the value null works for me

java.lang.RuntimeException: Unable to start activity ComponentInfo

After trying few answers they are either not related to my project or , I have tried cleaning and rebuilding (https://stackoverflow.com/a/48760966/8463813). But it didn't work for me directly. I have compared it with older version of code, in which i observed some library files(jars and aars in External Libraries directory) are missing. Tried Invalidate Cache and Restart worked, which created all the libraries and working fine.

Android java.lang.NoClassDefFoundError

I've run into this problem a few times opening old projects that include other Android libraries. What works for me is to:

move Android to the top in the Order and Export tab and deselecting it.

Yes, this really makes the difference. Maybe it's time for me to ditch ADT for Android Studio!

Convert RGBA PNG to RGB with PIL

By using Image.alpha_composite, the solution by Yuji 'Tomita' Tomita become simpler. This code can avoid a tuple index out of range error if png has no alpha channel.

from PIL import Image

png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255,255,255))

alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save('foo.jpg', 'JPEG', quality=80)

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

Since you are setting the layout explicitly you might want to try and put it in the default /layout folder not in the /layout-land since that is if you want Android to automatically handle rotation for you.

glm rotate usage in Opengl

You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).

All you need to do is (see here)

Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

Note that to convert from degrees to radians, use glm::radians(degrees)

That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.

note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6

Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

NoClassDefFoundError for code in an Java library on Android

In my case, I was trying to add a normal java class (from a normal java project) compiled with jre 1.7 to an android app project compiled with jre 1.7.

The solution was to recompile that normal java class with jre 1.6 and add references to the android app project (compiled with jre 1.6 also) as usual (in tab order and export be sure to check the class, project, etc).

The same process, when using an android library to reference external normal java classes.

Don't know what's wrong with jre 1.7, when compiling normal java classes from a normal java project and try to reference them in android app or android library projects.

If you don't use normal java classes (from a normal java project) you don't need to downgrade to jre 1.6.

Random number c++ in some range

You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:

25 + ( std::rand() % ( 63 - 25 + 1 ) )

How to unload a package without restarting R

I would like to add an alternative solution. This solution does not directly answer your question on unloading a package but, IMHO, provides a cleaner alternative to achieve your desired goal, which I understand, is broadly concerned with avoiding name conflicts and trying different functions, as stated:

mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use

Solution

Function with_package offered via the withr package offers the possibility to:

attache a package to the search path, executes the code, then removes the package from the search path. The package namespace is not unloaded, however.

Example

library(withr)
with_package("ggplot2", {
  ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context 
exists("geom_point")
# [1] FALSE

geom_point used in the example is not accessible from the global namespace. I reckon it may be a cleaner way of handling conflicts than loading and unloading packages.

Android app unable to start activity componentinfo

The question is answered already, but I want add more information about the causes.

Android app unable to start activity componentinfo

This error often comes with appropriate logs. You can read logs and can solve this issue easily.

Here is a sample log. In which you can see clearly ClassCastException. So this issue came because TextView cannot be cast to EditText.

Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText

11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050):     ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109):     ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167):     ... 11 more

Some Common Mistakes.

1.findViewById() of non existing view

Like when you use findViewById(R.id.button) when button id does not exist in layout XML.

2. Wrong cast.

If you wrong cast some class, then you get this error. Like you cast RelativeLayout to LinearLayout or EditText to TextView.

3. Activity not registered in manifest.xml

If you did not register Activity in manifest.xml then this error comes.

4. findViewById() with declaration at top level

Below code is incorrect. This will create error. Because you should do findViewById() after calling setContentView(). Because an View can be there after it is created.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way

  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
    //...
  }
}

5. Starting abstract Activity class.

When you try to start an Activity which is abstract, you will will get this error. So just remove abstract keyword before activity class name.

6. Using kotlin but kotlin not configured.

If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.

More information

Read about Downcast and Upcast

Read about findViewById() method of Activity class

Super keyword in Java

How to register activity in manifest

How can I select the row with the highest ID in MySQL?

SELECT *
FROM permlog
WHERE id = ( SELECT MAX(id) FROM permlog ) ;

This would return all rows with highest id, in case id column is not constrained to be unique.

Error inflating class fragment

None of the solutions mentioned above helped me. In the log I could find the detail of the exception as mentioned below:

06-19 16:20:37.885: E/AndroidRuntime(23973): Caused by: java.lang.RuntimeException: API key not found.  Check that /meta-data/ android:name="com.google.android.maps.v2.API_KEY" android:value="your API key"/ is in the application element of AndroidManifest.xml.

I did this and my code was working!

<meta-data  android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyCl1yGPZ3mpxxxxxxxAz2R-t7zcWVzrHUL9k"/>
</application>

How to make a Qt Widget grow with the window size?

In Designer, activate the centralWidget and assign a layout, e.g. horizontal or vertical layout. Then your QFormLayout will automatically resize.

Image of Designer

Always make sure, that all widgets have a layout! Otherwise, automatic resizing will break with that widget!

See also

Controls insist on being too large, and won't resize, in QtDesigner

Generate a random point within a circle (uniformly)

I am still not sure about the exact '(2/R2)×r' but what is apparent is the number of points required to be distributed in given unit 'dr' i.e. increase in r will be proportional to r2 and not r.

check this way...number of points at some angle theta and between r (0.1r to 0.2r) i.e. fraction of the r and number of points between r (0.6r to 0.7r) would be equal if you use standard generation, since the difference is only 0.1r between two intervals. but since area covered between points (0.6r to 0.7r) will be much larger than area covered between 0.1r to 0.2r, the equal number of points will be sparsely spaced in larger area, this I assume you already know, So the function to generate the random points must not be linear but quadratic, (since number of points required to be distributed in given unit 'dr' i.e. increase in r will be proportional to r2 and not r), so in this case it will be inverse of quadratic, since the delta we have (0.1r) in both intervals must be square of some function so it can act as seed value for linear generation of points (since afterwords, this seed is used linearly in sin and cos function), so we know, dr must be quadratic value and to make this seed quadratic, we need to originate this values from square root of r not r itself, I hope this makes it little more clear.

How to set space between listView Items in Android

you just need to make background transparent of list divider and make height according to your needed gap.

<ListView 
         android:id="@+id/custom_list"
         android:layout_height="match_parent"
         android:layout_width="match_parent"
         android:divider="#00ffffff"
         android:dividerHeight="20dp"/>

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

This might not be relevant to the actual question, but in my instance, I tried to implement Kotlin and left out apply plugin: 'kotlin-android'. The error happened because it could not recognize the MainActivity in as a .kt file.

Hope it helps someone.

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I solved this by updating my app theme to inherit from material components.

<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight">
    <!-- ... -->
</style>

Rotating videos with FFmpeg

I came across this page while searching for the same answer. It is now six months since this was originally asked and the builds have been updated many times since then. However, I wanted to add an answer for anyone else that comes across here looking for this information.

I am using Debian Squeeze and FFmpeg version from those repositories.

The MAN page for ffmpeg states the following use

ffmpeg -i inputfile.mpg -vf "transpose=1" outputfile.mpg

The key being that you are not to use a degree variable, but a predefined setting variable from the MAN page.

0=90CounterCLockwise and Vertical Flip  (default) 
1=90Clockwise 
2=90CounterClockwise 
3=90Clockwise and Vertical Flip

Activity has leaked window that was originally added

I have the same kind of problem. the error was not in the Dialog but in a EditText. I was trying to change the value of the Edittext inside of a Assynctask. the only away i could solve was creating a new runnable.

runOnUiThread(new Runnable(){
      @Override
      public void run() {
       ...        
      }
    });  

INNER JOIN vs LEFT JOIN performance in SQL Server

Outer joins can offer superior performance when used in views.

Say you have a query that involves a view, and that view is comprised of 10 tables joined together. Say your query only happens to use columns from 3 out of those 10 tables.

If those 10 tables had been inner-joined together, then the query optimizer would have to join them all even though your query itself doesn't need 7 out of 10 of the tables. That's because the inner joins themselves might filter down the data, making them essential to compute.

If those 10 tables had been outer-joined together instead, then the query optimizer would only actually join the ones that were necessary: 3 out of 10 of them in this case. That's because the joins themselves are no longer filtering the data, and thus unused joins can be skipped.

Source: http://www.sqlservercentral.com/blogs/sql_coach/2010/07/29/poor-little-misunderstood-views/

Android: ProgressDialog.show() crashes with getApplicationContext

I have implemented Alert Dialog for exception throwing on to the current activitty view.Whenever I had given like this

AlertDialog.Builder builder = new AlertDialog.Builder(context);

Given same Window Exception.I write code for alert out of onCreate().So simple I used context = this; after setContentView() statement in onCreate() method.Taken context variable as global like Context context;

Code sample is

static Context context;

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


        setContentView(R.layout.network); 
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        context = this;
.......

Alert Method Sample is

private void alertException(String execMsg){
        Log.i(TAG,"in alertException()..."+context);
        Log.e(TAG,"Exception :"+execMsg);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
.......

It works fine for me.Actually I searched for this error on StackOverflow I found this query.After reading all responses of this post, I tried this way so It works .I thought this is a simple solution for overcome the exception.

Thanks, Rajendar

SET NOCOUNT ON usage

if (set no count== off)

{ then it will keep data of how many records affected so reduce performance } else { it will not track the record of changes hence improve perfomace } }

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Adam Luter gave me the idea for this, but it actually turned out to be really simple:

img {
  width:  75px;
  height: auto;
}

IE6 now scales the image fine and this seems to be what all the other browsers use by default.

Thanks for both the answers though!

Generate random numbers uniformly over an entire range

The solution given by man 3 rand for a number between 1 and 10 inclusive is:

j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

In your case, it would be:

j = min + (int) ((max-min+1) * (rand() / (RAND_MAX + 1.0)));

Of course, this is not perfect randomness or uniformity as some other messages are pointing out, but this is enough for most cases.

Examples of good gotos in C or C++

Very common.

do_stuff(thingy) {
    lock(thingy);

    foo;
    if (foo failed) {
        status = -EFOO;
        goto OUT;
    }

    bar;
    if (bar failed) {
        status = -EBAR;
        goto OUT;
    }

    do_stuff_to(thingy);

OUT:
    unlock(thingy);
    return status;
}

The only case I ever use goto is for jumping forwards, usually out of blocks, and never into blocks. This avoids abuse of do{}while(0) and other constructs which increase nesting, while still maintaining readable, structured code.

How to get the public IP address of a user in C#

This is what I use:

protected void GetUser_IP()
{
    string VisitorsIPAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
        VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
    {
        VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
    }
    uip.Text = "Your IP is: " + VisitorsIPAddr;
}

"uip" is the name of the label in the aspx page that shows the user IP.

Converting byte array to string in javascript

The simplest solution I've found is:

var text = atob(byteArray);

Limit Get-ChildItem recursion depth

@scanlegentil I like this.
A little improvement would be:

$Depth = 2
$Path = "."

$Levels = "\*" * $Depth
$Folder = Get-Item $Path
$FolderFullName = $Folder.FullName
Resolve-Path $FolderFullName$Levels | Get-Item | ? {$_.PsIsContainer} | Write-Host

As mentioned, this would only scan the specified depth, so this modification is an improvement:

$StartLevel = 1 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 2      # How many levels deep to scan
$Path = "."     # starting path

For ($i=$StartLevel; $i -le $Depth; $i++) {
    $Levels = "\*" * $i
    (Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
    Select FullName
}

Index inside map() function

You will be able to get the current iteration's index for the map method through its 2nd parameter.

Example:

const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return currElement; //equivalent to list[index]
});

Output:

The current iteration is: 0 <br>The current element is: h

The current iteration is: 1 <br>The current element is: e

The current iteration is: 2 <br>The current element is: l

The current iteration is: 3 <br>The current element is: l 

The current iteration is: 4 <br>The current element is: o

See also: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Parameters

callback - Function that produces an element of the new Array, taking three arguments:

1) currentValue
The current element being processed in the array.

2) index
The index of the current element being processed in the array.

3) array
The array map was called upon.

How to solve a timeout error in Laravel 5

The Maximum execution time of 30 seconds exceeded error is not related to Laravel but rather your PHP configuration.

Here is how you can fix it. The setting you will need to change is max_execution_time.

;;;;;;;;;;;;;;;;;;;
; Resource Limits ;
;;;;;;;;;;;;;;;;;;;

max_execution_time = 30     ; Maximum execution time of each script, in seconds
max_input_time = 60 ; Maximum amount of time each script may spend parsing request data
memory_limit = 8M      ; Maximum amount of memory a script may consume (8MB)

You can change the max_execution_time to 300 seconds like max_execution_time = 300

You can find the path of your PHP configuration file in the output of the phpinfo function in the Loaded Configuration File section.

Example for boost shared_mutex (multiple reads/one write)?

Great response by Jim Morris, I stumbled upon this and it took me a while to figure. Here is some simple code that shows that after submitting a "request" for a unique_lock boost (version 1.54) blocks all shared_lock requests. This is very interesting as it seems to me that choosing between unique_lock and upgradeable_lock allows if we want write priority or no priority.

Also (1) in Jim Morris's post seems to contradict this: Boost shared_lock. Read preferred?

#include <iostream>
#include <boost/thread.hpp>

using namespace std;

typedef boost::shared_mutex Lock;
typedef boost::unique_lock< Lock > UniqueLock;
typedef boost::shared_lock< Lock > SharedLock;

Lock tempLock;

void main2() {
    cout << "10" << endl;
    UniqueLock lock2(tempLock); // (2) queue for a unique lock
    cout << "11" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(1));
    lock2.unlock();
}

void main() {
    cout << "1" << endl;
    SharedLock lock1(tempLock); // (1) aquire a shared lock
    cout << "2" << endl;
    boost::thread tempThread(main2);
    cout << "3" << endl;
    boost::this_thread::sleep(boost::posix_time::seconds(3));
    cout << "4" << endl;
    SharedLock lock3(tempLock); // (3) try getting antoher shared lock, deadlock here
    cout << "5" << endl;
    lock1.unlock();
    lock3.unlock();
}

Java Replace Character At Specific Position Of String?

To replace a character at a specified position :

public static String replaceCharAt(String s, int pos, char c) {
   return s.substring(0,pos) + c + s.substring(pos+1);
}

Can I get image from canvas element and use it in img src tag?

Corrected the Fiddle - updated shows the Image duplicated into the Canvas...

And right click can be saved as a .PNG

http://jsfiddle.net/gfyWK/67/

<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>

Plus the JS on the fiddle page...

Cheers Si

Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

How to get a thread and heap dump of a Java process on Windows that's not running in a console

Visualvm followup:

If you "can't connect" to your running JVM from jvisualvm because you didn't start it with the right JVM arguments (and it's on remote box), run jstatd on the remote box, then, assuming you have a direct connection, add it as a "remote host" in visualvm, double click the host name, and all other JVM's on that box will magically show up in visualvm.

If you don't have "direct connection" to ports on that box, you can also do this through a proxy.

Once you can see the process you want, drill into it in jvisualvm and use monitor tab -> "heapdump" button.

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

How do I use 'git reset --hard HEAD' to revert to a previous commit?

WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


Try this and see git clean -f.

git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

  • git clean -df
  • git clean -xdf CAUTION! This will also delete ignored files

jQuery Call to WebService returns "No Transport" error

I had the same error on a page, and I added these lines:

<!--[if lte IE 9]>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.3/jquery.xdomainrequest.min.js'></script>
<![endif]-->

and it finally works for me ;) no more error in IE9.

Java: Date from unix timestamp

This is the right way:

Date date = new Date ();
date.setTime((long)unix_time*1000);

Checkout subdirectories in Git?

There is no real way to do that in git. And if you won’t be making changes that affect both trees at once as a single work unit, there is no good reason to use a single repository for both. I thought I would miss this Subversion feature, but I found that creating repositories has so little administrative mental overhead (simply due to the fact that repositories are stored right next to their working copy, rather than requiring me to explicitly pick some place outside of the working copy) that I got used to just making lots of small single-purpose repositories.

If you insist (or really need it), though, you could make a git repository with just mytheme and myplugins directories and symlink those from within the WordPress install.


MDCore wrote:

making a commit to, e.g., mytheme will increment the revision number for myplugin

Note that this is not a concern for git, if you do decide to put both directories in a single repository, because git does away entirely with the concept of monotonically increasing revision numbers of any form.

The sole criterion for what things to put together in a single repository in git is whether it constitutes a single unit, ie. in your case whether there are changes where it does not make sense to look at the edits in each directory in isolation. If you have changes where you need to edit files in both directories at once and the edits belong together, they should be one repository. If not, then don’t glom them together.

Git really really wants you to use separate repositories for separate entities.

submodules

Submodules do not address the desire to keep both directories in one repository, because they would actually enforce having a separate repository for each directory, which are then brought together in another repository using submodules. Worse, since the directories inside the WordPress install are not direct subdirectories of the same directory and are also part of a hierarchy with many other files, using the per-directory repositories as submodules in a unified repository would offer no benefit whatsoever, because the unified repository would not reflect any use case/need.

Android app unable to start activity componentinfo

The question is answered already, but I want add more information about the causes.

Android app unable to start activity componentinfo

This error often comes with appropriate logs. You can read logs and can solve this issue easily.

Here is a sample log. In which you can see clearly ClassCastException. So this issue came because TextView cannot be cast to EditText.

Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText

11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050):     ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109):     ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167):     ... 11 more

Some Common Mistakes.

1.findViewById() of non existing view

Like when you use findViewById(R.id.button) when button id does not exist in layout XML.

2. Wrong cast.

If you wrong cast some class, then you get this error. Like you cast RelativeLayout to LinearLayout or EditText to TextView.

3. Activity not registered in manifest.xml

If you did not register Activity in manifest.xml then this error comes.

4. findViewById() with declaration at top level

Below code is incorrect. This will create error. Because you should do findViewById() after calling setContentView(). Because an View can be there after it is created.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way

  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
    //...
  }
}

5. Starting abstract Activity class.

When you try to start an Activity which is abstract, you will will get this error. So just remove abstract keyword before activity class name.

6. Using kotlin but kotlin not configured.

If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.

More information

Read about Downcast and Upcast

Read about findViewById() method of Activity class

Super keyword in Java

How to register activity in manifest

Should import statements always be at the top of a module?

It's interesting that not a single answer mentioned parallel processing so far, where it might be REQUIRED that the imports are in the function, when the serialized function code is what is being pushed around to other cores, e.g. like in the case of ipyparallel.

How to use makefiles in Visual Studio?

If you are asking about actual command line makefiles then you can export a makefile, or you can call MSBuild on a solution file from the command line. What exactly do you want to do with the makefile?

You can do a search on SO for MSBuild for more details.

Something better than .NET Reflector?

JetBrains is going to add a decompiler to its ReSharper, and release a stand-alone decompiler too.

The good news is that we’re preparing a standalone binary-as-a-source application, i.e. a decompiler + assembly browser to explore whatever .NET compiled code is legal to explore. We don’t have any specific date for release, but it’s going to be released this year, and it’s going to be free of charge. And by saying “free”, we actually mean “free”.

Here is more information.

UPDATE: JetBrains has now released the product called dotPeek and it can be found here.

How to change icon on Google map marker

var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  icon: 'your-icon.png'
});

Using sed, how do you print the first 'N' characters of a line?

don't have to use grep either

an example:

sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file

Adding days to $Date in PHP

All you have to do is use days instead of day like this:

<?php
$Date = "2010-09-17";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo date('Y-m-d', strtotime($Date. ' + 2 days'));
?>

And it outputs correctly:

2010-09-18
2010-09-19

Search a whole table in mySQL for a string

In addition to pattern matching with 'like' keyword. You can also perform search by using fulltext feature as below;

SELECT * FROM clients WHERE MATCH (shipping_name, billing_name, email) AGAINST ('mary')

Run a script in Dockerfile

RUN and ENTRYPOINT are two different ways to execute a script.

RUN means it creates an intermediate container, runs the script and freeze the new state of that container in a new intermediate image. The script won't be run after that: your final image is supposed to reflect the result of that script.

ENTRYPOINT means your image (which has not executed the script yet) will create a container, and runs that script.

In both cases, the script needs to be added, and a RUN chmod +x /bootstrap.sh is a good idea.

It should also start with a shebang (like #!/bin/sh)

Considering your script (bootstrap.sh: a couple of git config --global commands), it would be best to RUN that script once in your Dockerfile, but making sure to use the right user (the global git config file is %HOME%/.gitconfig, which by default is the /root one)

Add to your Dockerfile:

RUN /bootstrap.sh

Then, when running a container, check the content of /root/.gitconfig to confirm the script was run.

How to validate IP address in Python?

I have to give a great deal of credit to Markus Jarderot for his post - the majority of my post is inspired from his.

I found that Markus' answer still fails some of the IPv6 examples in the Perl script referenced by his answer.

Here is my regex that passes all of the examples in that Perl script:

r"""^
     \s* # Leading whitespace
     # Zero-width lookaheads to reject too many quartets
     (?:
        # 6 quartets, ending IPv4 address; no wildcards
        (?:[0-9a-f]{1,4}(?::(?!:))){6}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-5 quartets, wildcard, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
        (?:::(?!:))
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-4 quartets, wildcard, 0-1 quartets, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:)))?
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-3 quartets, wildcard, 0-2 quartets, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,2}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-2 quartets, wildcard, 0-3 quartets, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,3}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-1 quartets, wildcard, 0-4 quartets, ending IPv4 address
        (?:[0-9a-f]{1,4}){0,1}
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,4}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # wildcard, 0-5 quartets, ending IPv4 address
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,5}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 8 quartets; no wildcards
        (?:[0-9a-f]{1,4}(?::(?!:))){7}[0-9a-f]{1,4}
      |
        # 0-7 quartets, wildcard
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
        (?:::(?!:))
      |
        # 0-6 quartets, wildcard, 0-1 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4})?
      |
        # 0-5 quartets, wildcard, 0-2 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
      |
        # 0-4 quartets, wildcard, 0-3 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
      |
        # 0-3 quartets, wildcard, 0-4 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
      |
        # 0-2 quartets, wildcard, 0-5 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
      |
        # 0-1 quartets, wildcard, 0-6 quartets
        (?:[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
      |
        # wildcard, 0-7 quartets
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
     )
     (?:/(?:1(?:2[0-7]|[01]\d)|\d\d?))? # With an optional CIDR routing prefix (0-128)
     \s* # Trailing whitespace
    $"""

I also put together a Python script to test all of those IPv6 examples; it's here on Pastebin because it was too large to post here.

You can run the script with test result and example arguments in the form of "[result]=[example]", so like:

python script.py Fail=::1.2.3.4: pass=::127.0.0.1 false=::: True=::1

or you can simply run all of the tests by specifying no arguments, so like:

python script.py

Anyway, I hope this helps somebody else!

Why aren't Xcode breakpoints functioning?

I believe that a project can also become corrupted in regards to breakpoints. I have a project, for example, that WILL NOT break on any breakpoints that it remembers from the previous session. I first wrote about this here

How do I pretty-print existing JSON data with Java?

I think for pretty-printing something, it's very helpful to know its structure.

To get the structure you have to parse it. Because of this, I don't think it gets much easier than first parsing the JSON string you have and then using the pretty-printing method toString mentioned in the comments above.

Of course you can do similar with any JSON library you like.

Postgresql query between date ranges

Just in case somebody land here... since 8.1 you can simply use:

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'

From the docs:

BETWEEN SYMMETRIC is the same as BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right. If it is not, those two arguments are automatically swapped, so that a nonempty range is always implied.

Best way to parse command-line parameters?

I like sliding over arguments for relatively simple configurations.

var name = ""
var port = 0
var ip = ""
args.sliding(2, 2).toList.collect {
  case Array("--ip", argIP: String) => ip = argIP
  case Array("--port", argPort: String) => port = argPort.toInt
  case Array("--name", argName: String) => name = argName
}

How to add "required" attribute to mvc razor viewmodel text input editor

You can use the required html attribute if you want:

@Html.TextBoxFor(m => m.ShortName, 
new { @class = "form-control", placeholder = "short name", required="required"})

or you can use the RequiredAttribute class in .Net. With jQuery the RequiredAttribute can Validate on the front end and server side. If you want to go the MVC route, I'd suggest reading Data annotations MVC3 Required attribute.

OR

You can get really advanced:

@{
  // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
  var attributes = new Dictionary<string, object>(
    Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));

 attributes.Add("class", "form-control");
 attributes.Add("placeholder", "short name");

  if (ViewData.ModelMetadata.ContainerType
      .GetProperty(ViewData.ModelMetadata.PropertyName)
      .GetCustomAttributes(typeof(RequiredAttribute), true)
      .Select(a => a as RequiredAttribute)
      .Any(a => a != null))
  {
   attributes.Add("required", "required");
  }

  @Html.TextBoxFor(m => m.ShortName, attributes)

}

or if you need it for multiple editor templates:

public static class ViewPageExtensions
{
  public static IDictionary<string, object> GetAttributes(this WebViewPage instance)
  {
    // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
    var attributes = new Dictionary<string, object>(
      instance.Html.GetUnobtrusiveValidationAttributes(
         instance.ViewData.TemplateInfo.HtmlFieldPrefix));

    if (ViewData.ModelMetadata.ContainerType
      .GetProperty(ViewData.ModelMetadata.PropertyName)
      .GetCustomAttributes(typeof(RequiredAttribute), true)
      .Select(a => a as RequiredAttribute)
      .Any(a => a != null))
    {
      attributes.Add("required", "required");
    }
  }
}

then in your templates:

@{
  // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
  var attributes = this.GetAttributes();

  attributes.Add("class", "form-control");
  attributes.Add("placeholder", "short name");

  @Html.TextBoxFor(m => m.ShortName, attributes)

}

Update 1 (for Tomas who is unfamilar with ViewData).

What's the difference between ViewData and ViewBag?

Excerpt:

So basically it (ViewBag) replaces magic strings:

ViewData["Foo"]

with magic properties:

ViewBag.Foo

How can I exclude directories from grep -R?

Frequently use this:

grep can be used in conjunction with -r (recursive), i (ignore case) and -o (prints only matching part of lines). To exclude files use --exclude and to exclude directories use --exclude-dir.

Putting it together you end up with something like:

grep -rio --exclude={filenames comma separated} \
--exclude-dir={directory names comma separated} <search term> <location>

Describing it makes it sound far more complicated than it actually is. Easier to illustrate with a simple example.

Example:

Suppose I am searching for current project for all places where I explicitly set the string value debugger during a debugging session, and now wish to review / remove.

I write a script called findDebugger.sh and use grep to find all occurrences. However:

For file exclusions - I wish to ensure that .eslintrc is ignored (this actually has a linting rule about debugger so should be excluded). Likewise, I don't want my own script to be referenced in any results.

For directory exclusions - I wish to exclude node_modules as it contains lots of libraries that do reference debugger and I am not interested in those results. Also I just wish to omit .idea and .git hidden directories because I don't care about those search locations either, and wish to keep the search performant.

So here is the result - I create a script called findDebugger.sh with:

#!/usr/bin/env bash
grep -rio --exclude={.eslintrc,findDebugger.sh} \
--exclude-dir={node_modules,.idea,.git} debugger .

Should I use "camel case" or underscores in python?

Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style

Check out its already been answered, click here

Html table tr inside td

Full Example:

_x000D_
_x000D_
<table border="1" style="width:100%;">
  <tr>
    <td>ABC</td>
    <td>ABC</td>
    <td>ABC</td>
    <td>ABC</td>
  </tr>
  <tr>
    <td>Item 1</td>
    <td>Item 1</td>
    <td>
      <table border="1" style="width: 100%;">
        <tr>
          <td>Name 1</td>
          <td>Price 1</td>
        </tr>
        <tr>
          <td>Name 2</td>
          <td>Price 2</td>
        </tr>
        <tr>
          <td>Name 3</td>
          <td>Price 3</td>
        </tr>
      </table>
    </td>
    <td>Item 1</td>
  </tr>
  <tr>
    <td>Item 2</td>
    <td>Item 2</td>
    <td>Item 2</td>
    <td>Item 2</td>
  </tr>
  <tr>
    <td>Item 3</td>
    <td>Item 3</td>
    <td>Item 3</td>
    <td>Item 3</td>
  </tr>
</table>
_x000D_
_x000D_
_x000D_

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

I just got exactly this error when doing "git pull" when my disk was full. Created some space and it all started working fine again.

IP to Location using Javascript

A rather inexpensive option would be to use the ipdata.co API, it's free upto 1500 requests a day.

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

_x000D_
_x000D_
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
    $("#ip").html("IP: " + response.ip);_x000D_
    $("#city").html(response.city + ", " + response.region);_x000D_
    $("#response").html(JSON.stringify(response, null, 4));_x000D_
}, "jsonp");
_x000D_
<h1><a href="https://ipdata.co">ipdata.co</a> - IP geolocation API</h1>_x000D_
_x000D_
<div id="ip"></div>_x000D_
<div id="city"></div>_x000D_
<pre id="response"></pre>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

View the Fiddle at https://jsfiddle.net/ipdata/6wtf0q4g/922/

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

afxwin.h file is missing in VC++ Express Edition

I encountered the same problem. The easiest thing is to install the free Visual Studio Community 2015 as answered in this question Is MFC only available with Visual Studio, and not Visual C++ Express?

no suitable HttpMessageConverter found for response type

Or you can use

public void setSupportedMediaTypes(List supportedMediaTypes)

method which belongs to AbstractHttpMessageConverter<T>, to add some ContentTypes you like. This way can let the MappingJackson2HttpMessageConverter canRead() your response, and transform it to your desired Class, which on this case,is ProductList Class.

and I think this step should hooked up with the Spring Context initializing. for example, by using

implements ApplicationListener { ... }

Do I need to close() both FileReader and BufferedReader?

Starting from Java 7 you can use try-with-resources Statement

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
}

Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly. So you don't need to close it yourself in the finally statement. (This is also the case with nested resource statements)

This is the recomanded way to work with resources, see the documentation for more detailed information

How to verify that a specific method was not called using Mockito?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):

import static org.mockito.Mockito.*;

There are actually many ways to achieve this, however it's (arguably) cleaner to use the

verify(yourMock, times(0)).someMethod();

method all over your tests, when on other Tests you use it to assert a certain amount of executions like this:

verify(yourMock, times(5)).someMethod();

Alternatives are:

verify(yourMock, never()).someMethod();

Alternatively - when you really want to make sure a certain mocked Object is actually NOT called at all - you can use:

verifyZeroInteractions(yourMock)

JSON.net: how to deserialize without using the default constructor?

The default behaviour of Newtonsoft.Json is going to find the public constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected or internal so that Newtonsoft.Json will pick your desired public constructor.

Admittedly, this solution is rather very limited to specific cases.

internal Result() { }

public Result(int? code, string format, Dictionary<string, string> details = null)
{
    Code = code ?? ERROR_CODE;
    Format = format;

    if (details == null)
        Details = new Dictionary<string, string>();
    else
        Details = details;
}

Preloading CSS Images

If the page elements and their background images are already in the DOM (i.e. you are not creating/changing them dynamically), then their background images will already be loaded. At that point, you may want to look at compression methods :)

How to increase editor font size?

Temporarily adjust the font size

Go to Settings (or Preferences in Mac) > Editor > General > Change font size (Zoom) with Ctrl+Mouse Wheel OR Press "Cmd+Shift+A" for mac.

enter image description here

This will allow you to quickly modify the font size whenever you want. However, the font will get reset to the default size the next time you start Android Studio. (The Control+Mouse Wheel functionality will not get reset, though. You only need to do this once.)

Permanently change the default font size

Go to Settings > Editor > Colors & Fonts > Font. Click "Save As..." and choose a new scheme name. Then change the font size and say OK. This will be the default size every time you open Android Studio now.

enter image description here

Add column in dataframe from list

You can also use df.assign:

In [1559]: df
Out[1559]: 
   A   B   C
0  0 NaN NaN
1  4 NaN NaN
2  5 NaN NaN
3  6 NaN NaN
4  7 NaN NaN
5  7 NaN NaN
6  6 NaN NaN
7  5 NaN NaN

In [1560]: mylist = [2,5,6,8,12,16,26,32]

In [1567]: df = df.assign(D=mylist)

In [1568]: df
Out[1568]: 
   A   B   C   D
0  0 NaN NaN   2
1  4 NaN NaN   5
2  5 NaN NaN   6
3  6 NaN NaN   8
4  7 NaN NaN  12
5  7 NaN NaN  16
6  6 NaN NaN  26
7  5 NaN NaN  32

Find index of last occurrence of a substring in a string

You can use rfind() or rindex()
Python2 links: rfind() rindex()

>>> s = 'Hello StackOverflow Hi everybody'

>>> print( s.rfind('H') )
20

>>> print( s.rindex('H') )
20

>>> print( s.rfind('other') )
-1

>>> print( s.rindex('other') )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

The difference is when the substring is not found, rfind() returns -1 while rindex() raises an exception ValueError (Python2 link: ValueError).

If you do not want to check the rfind() return code -1, you may prefer rindex() that will provide an understandable error message. Else you may search for minutes where the unexpected value -1 is coming from within your code...


Example: Search of last newline character

>>> txt = '''first line
... second line
... third line'''

>>> txt.rfind('\n')
22

>>> txt.rindex('\n')
22

Is there a pure CSS way to make an input transparent?

input[type="text"]
{
    background: transparent;
    border: none;
}

Nobody will even know it's there.

How to create a simple proxy in C#?

Things have become really easy with OWIN and WebAPI. In my search for a C# Proxy server, I also came across this post http://blog.kloud.com.au/2013/11/24/do-it-yourself-web-api-proxy/ . This will be the road I'm taking.

Determine whether an array contains a value

function setFound(){   
 var l = arr.length, textBox1 = document.getElementById("text1");
    for(var i=0; i<l;i++)
    {
     if(arr[i]==searchele){
      textBox1 .value = "Found";
      return;
     }
    }
    textBox1 .value = "Not Found";
return;
}

This program checks whether the given element is found or not. Id text1 represents id of textbox and searchele represents element to be searched (got fron user); if you want index, use i value

How to retrieve records for last 30 minutes in MS SQL?

Change this (CURRENT_TIMESTAMP-30)

To This: DateADD(mi, -30, Current_TimeStamp)

To get the current date use GetDate().

MSDN Link to DateAdd Function
MSDN Link to Get Date Function

Convert python datetime to timestamp in milliseconds

In Python 3 this can be done in 2 steps:

  1. Convert timestring to datetime object
  2. Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.

For example like this:

from datetime import datetime

dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
                           '%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000

print(millisec)

Output:

1482223122760.0

strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.

Here is the explanation of the format specifiers from the official documentation:

  • %d - Day of the month as a zero-padded decimal number.
  • %m - Month as a zero-padded decimal number.
  • %Y - Year with century as a decimal number
  • %H - Hour (24-hour clock) as a zero-padded decimal number.
  • %M - Minute as a zero-padded decimal number.
  • %S - Second as a zero-padded decimal number.
  • %f - Microsecond as a decimal number, zero-padded on the left.

wp-admin shows blank page, how to fix it?

I also had a blank screen for my blog. The solution was to copy up a backup copy of wp-config,php somehow the 'live' wp-config.php had been replaced with a file size of zero.

In my case I had the same problem. Helped remove the wp-config.php file. Wordpress created new wp-config.php file and wp-admin is working flawlessly now. Rename plugins, themes folder does not help.

How to SUM two fields within an SQL query

Due to my reputation points being less than 50 I could not comment on or vote for E Coder's answer above. This is the best way to do it so you don't have to use the group by as I had a similar issue.
By doing SUM((coalesce(VALUE1 ,0)) + (coalesce(VALUE2 ,0))) as Total this will get you the number you want but also rid you of any error for not performing a Group By. This was my query and gave me a total count and total amount for the each dealer and then gave me a subtotal for Quality and Risky dealer loans.

SELECT 
    DISTINCT STEP1.DEALER_NBR
    ,COUNT(*) AS DLR_TOT_CNT
    ,SUM((COALESCE(DLR_QLTY,0))+(COALESCE(DLR_RISKY,0))) AS DLR_TOT_AMT
    ,COUNT(STEP1.DLR_QLTY) AS DLR_QLTY_CNT
    ,SUM(STEP1.DLR_QLTY) AS DLR_QLTY_AMT
    ,COUNT(STEP1.DLR_RISKY) AS DLR_RISKY_CNT
    ,SUM(STEP1.DLR_RISKY) AS DLR_RISKY_AMT
    FROM STEP1
    WHERE DLR_QLTY IS NOT NULL OR DLR_RISKY IS NOT NULL
        GROUP BY STEP1.DEALER_NBR

How to use SqlClient in ASP.NET Core?

I think you may have missed this part in the tutorial:

Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:

System.Data.Common and System.Data.SqlClient.

Currently this creates dependency in project.json –> aspnetcore50 section to these two libraries.

"aspnetcore50": {
       "dependencies": {
           "System.Runtime": "4.0.20-beta-22523",
           "System.Data.Common": "4.0.0.0-beta-22605",
           "System.Data.SqlClient": "4.0.0.0-beta-22605"
       }
}

Try getting System.Data.Common and System.Data.SqlClient via Nuget and see if this adds the above dependencies for you, but in a nutshell you are missing System.Runtime.

Edit: As per Mozarts answer, if you are using .NET Core 3+, reference Microsoft.Data.SqlClient instead.

Save and load MemoryStream to/from a file

The stream should really by disposed of even if there's an exception (quite likely on file I/O) - using clauses are my favourite approach for this, so for writing your MemoryStream, you can use:

using (FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write)) {
    memoryStream.WriteTo(file);
}

And for reading it back:

using (FileStream file = new FileStream("file.bin", FileMode.Open, FileAccess.Read)) {
    byte[] bytes = new byte[file.Length];
    file.Read(bytes, 0, (int)file.Length);
    ms.Write(bytes, 0, (int)file.Length);
}

If the files are large, then it's worth noting that the reading operation will use twice as much memory as the total file size. One solution to that is to create the MemoryStream from the byte array - the following code assumes you won't then write to that stream.

MemoryStream ms = new MemoryStream(bytes, writable: false);

My research (below) shows that the internal buffer is the same byte array as you pass it, so it should save memory.

byte[] testData = new byte[] { 104, 105, 121, 97 };
var ms = new MemoryStream(testData, 0, 4, false, true);
Assert.AreSame(testData, ms.GetBuffer());

SASS and @font-face

I’ve been struggling with this for a while now. Dycey’s solution is correct in that specifying the src multiple times outputs the same thing in your css file. However, this seems to break in OSX Firefox 23 (probably other versions too, but I don’t have time to test).

The cross-browser @font-face solution from Font Squirrel looks like this:

@font-face {
    font-family: 'fontname';
    src: url('fontname.eot');
    src: url('fontname.eot?#iefix') format('embedded-opentype'),
         url('fontname.woff') format('woff'),
         url('fontname.ttf') format('truetype'),
         url('fontname.svg#fontname') format('svg');
    font-weight: normal;
    font-style: normal;
}

To produce the src property with the comma-separated values, you need to write all of the values on one line, since line-breaks are not supported in Sass. To produce the above declaration, you would write the following Sass:

@font-face
  font-family: 'fontname'
  src: url('fontname.eot')
  src: url('fontname.eot?#iefix') format('embedded-opentype'), url('fontname.woff') format('woff'), url('fontname.ttf') format('truetype'), url('fontname.svg#fontname') format('svg')
  font-weight: normal
  font-style: normal

I think it seems silly to write out the path a bunch of times, and I don’t like overly long lines in my code, so I worked around it by writing this mixin:

=font-face($family, $path, $svg, $weight: normal, $style: normal)
  @font-face
    font-family: $family
    src: url('#{$path}.eot')
    src: url('#{$path}.eot?#iefix') format('embedded-opentype'), url('#{$path}.woff') format('woff'), url('#{$path}.ttf') format('truetype'), url('#{$path}.svg##{$svg}') format('svg')
    font-weight: $weight
    font-style: $style

Usage: For example, I can use the previous mixin to setup up the Frutiger Light font like this:

+font-face('frutigerlight', '../fonts/frutilig-webfont', 'frutigerlight')

How do I mock a class without an interface?

I think it's better to create an interface for that class. And create a unit test using interface.

If it you don't have access to that class, you can create an adapter for that class.

For example:

public class RealClass
{
    int DoSomething(string input)
    {
        // real implementation here
    }
}

public interface IRealClassAdapter
{
    int DoSomething(string input);
}

public class RealClassAdapter : IRealClassAdapter
{
    readonly RealClass _realClass;

    public RealClassAdapter() => _realClass = new RealClass();

    int DoSomething(string input) => _realClass.DoSomething(input);
}

This way, you can easily create mock for your class using IRealClassAdapter.

Hope it works.

COUNT / GROUP BY with active record?

Although it is a late answer, I would say this will help you...

$query = $this->db
              ->select('user_id, count(user_id) AS num_of_time')
              ->group_by('user_id')
              ->order_by('num_of_time', 'desc')
              ->get('tablename', 10);
print_r($query->result());

How to run Spring Boot web application in Eclipse itself?

Steps: 1. go to Run->Run configuration -> Maven Build -> New configuration
2. set base directory of you project ie.${workspace_loc:/shc-be-war}
3. set goal spring-boot:run
4. Run project from Run->New_Configuration

enter image description here

How to read data From *.CSV file using javascript?

You can use PapaParse to help. https://www.papaparse.com/

Here is a CodePen. https://codepen.io/sandro-wiggers/pen/VxrxNJ

Papa.parse(e, {
            header:true,
            before: function(file, inputElem){ console.log('Attempting to Parse...')},
            error: function(err, file, inputElem, reason){ console.log(err); },
            complete: function(results, file){ $.PAYLOAD = results; }
        });

How to check whether a file is empty or not?

If you are using Python3 with pathlib you can access os.stat() information using the Path.stat() method, which has the attribute st_size(file size in bytes):

>>> from pathlib import Path 
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty

Converting Stream to String and back...what are we missing?

This is so common but so profoundly wrong. Protobuf data is not string data. It certainly isn't ASCII. You are using the encoding backwards. A text encoding transfers:

  • an arbitrary string to formatted bytes
  • formatted bytes to the original string

You do not have "formatted bytes". You have arbitrary bytes. You need to use something like a base-n (commonly: base-64) encode. This transfers

  • arbitrary bytes to a formatted string
  • a formatted string to the original bytes

look at Convert.ToBase64String and Convert. FromBase64String

How do I get the current username in Windows PowerShell?

[System.Security.Principal.WindowsIdentity]::GetCurrent().Name

Can Javascript read the source of any web page?

You can use the FileReader API to get a file, and when selecting a file, put the url of your web page into the selection box. Use this code:

function readFile() {
    var f = document.getElementById("yourfileinput").files[0]; 
    if (f) {
      var r = new FileReader();
      r.onload = function(e) { 
        alert(r.result);
      }
      r.readAsText(f);
    } else { 
      alert("file could not be found")
    }
  }
}

Why won't bundler install JSON gem?

For OS X make sure you have coreutils

$ brew install coreutils
$ bundle

How do I clear this setInterval inside a function?

The setInterval method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:

function intervalTrigger() {
  return window.setInterval( function() {
    if (timedCount >= markers.length) {
       timedCount = 0;
    }
    google.maps.event.trigger(markers[timedCount], "click");
    timedCount++;
  }, 5000 );
};
var id = intervalTrigger();

Then to clear the interval:

window.clearInterval(id);

hibernate: LazyInitializationException: could not initialize proxy

Okay, finally figured out where I was remiss. I was under the mistaken notion that I should wrap each DAO method in a transaction. Terribly wrong! I've learned my lesson. I've hauled all the transaction code from all the DAO methods and have set up transactions strictly at the application/manager layer. This has totally solved all my problems. Data is properly lazy loaded as I need it, wrapped up and closed down once I do the commit.

Life is goodly... :)

What is a Windows Handle?

A HANDLE is a context-specific unique identifier. By context-specific, I mean that a handle obtained from one context cannot necessarily be used in any other aribtrary context that also works on HANDLEs.

For example, GetModuleHandle returns a unique identifier to a currently loaded module. The returned handle can be used in other functions that accept module handles. It cannot be given to functions that require other types of handles. For example, you couldn't give a handle returned from GetModuleHandle to HeapDestroy and expect it to do something sensible.

The HANDLE itself is just an integral type. Usually, but not necessarily, it is a pointer to some underlying type or memory location. For example, the HANDLE returned by GetModuleHandle is actually a pointer to the base virtual memory address of the module. But there is no rule stating that handles must be pointers. A handle could also just be a simple integer (which could possibly be used by some Win32 API as an index into an array).

HANDLEs are intentionally opaque representations that provide encapsulation and abstraction from internal Win32 resources. This way, the Win32 APIs could potentially change the underlying type behind a HANDLE, without it impacting user code in any way (at least that's the idea).

Consider these three different internal implementations of a Win32 API that I just made up, and assume that Widget is a struct.

Widget * GetWidget (std::string name)
{
    Widget *w;

    w = findWidget(name);

    return w;
}
void * GetWidget (std::string name)
{
    Widget *w;

    w = findWidget(name);

    return reinterpret_cast<void *>(w);
}
typedef void * HANDLE;

HANDLE GetWidget (std::string name)
{
    Widget *w;

    w = findWidget(name);

    return reinterpret_cast<HANDLE>(w);
}

The first example exposes the internal details about the API: it allows the user code to know that GetWidget returns a pointer to a struct Widget. This has a couple of consequences:

  • the user code must have access to the header file that defines the Widget struct
  • the user code could potentially modify internal parts of the returned Widget struct

Both of these consequences may be undesirable.

The second example hides this internal detail from the user code, by returning just void *. The user code doesn't need access to the header that defines the Widget struct.

The third example is exactly the same as the second, but we just call the void * a HANDLE instead. Perhaps this discourages user code from trying to figure out exactly what the void * points to.

Why go through this trouble? Consider this fourth example of a newer version of this same API:

typedef void * HANDLE;

HANDLE GetWidget (std::string name)
{
    NewImprovedWidget *w;

    w = findImprovedWidget(name);

    return reinterpret_cast<HANDLE>(w);
}

Notice that the function's interface is identical to the third example above. This means that user code can continue to use this new version of the API, without any changes, even though the "behind the scenes" implementation has changed to use the NewImprovedWidget struct instead.

The handles in these example are really just a new, presumably friendlier, name for void *, which is exactly what a HANDLE is in the Win32 API (look it up at MSDN). It provides an opaque wall between the user code and the Win32 library's internal representations that increases portability, between versions of Windows, of code that uses the Win32 API.

Difference between & and && in Java?

&& == logical AND

& = bitwise AND

Port 80 is being used by SYSTEM (PID 4), what is that?

I've found out that "SQL Server Reporting Services (MSSQLSERVER)" starts automatically and listens on port 80.

I hope this helps.

O

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

When you use VARIABLE = value, if value is actually a reference to another variable, then the value is only determined when VARIABLE is used. This is best illustrated with an example:

VAL = foo
VARIABLE = $(VAL)
VAL = bar

# VARIABLE and VAL will both evaluate to "bar"

When you use VARIABLE := value, you get the value of value as it is now. For example:

VAL = foo
VARIABLE := $(VAL)
VAL = bar

# VAL will evaluate to "bar", but VARIABLE will evaluate to "foo"

Using VARIABLE ?= val means that you only set the value of VARIABLE if VARIABLE is not set already. If it's not set already, the setting of the value is deferred until VARIABLE is used (as in example 1).

VARIABLE += value just appends value to VARIABLE. The actual value of value is determined as it was when it was initially set, using either = or :=.

EXCEL VBA Check if entry is empty or not 'space'

A common trick is to check like this:

trim(TextBox1.Value & vbnullstring) = vbnullstring

this will work for spaces, empty strings, and genuine null values

Illegal string offset Warning PHP

i think the only reason for this message is because target Array is actually an array like string etc (JSON -> {"host": "127.0.0.1"}) variable

How to use the unsigned Integer in Java 8 and Java 9?

    // Java 8
    int vInt = Integer.parseUnsignedInt("4294967295");
    System.out.println(vInt); // -1
    String sInt = Integer.toUnsignedString(vInt);
    System.out.println(sInt); // 4294967295

    long vLong = Long.parseUnsignedLong("18446744073709551615");
    System.out.println(vLong); // -1
    String sLong = Long.toUnsignedString(vLong);
    System.out.println(sLong); // 18446744073709551615

    // Guava 18.0
    int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
    System.out.println(vIntGu); // -1
    String sIntGu = UnsignedInts.toString(vIntGu);
    System.out.println(sIntGu); // 4294967295

    long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
    System.out.println(vLongGu); // -1
    String sLongGu = UnsignedLongs.toString(vLongGu);
    System.out.println(sLongGu); // 18446744073709551615

    /**
     Integer - Max range
     Signed: From -2,147,483,648 to 2,147,483,647, from -(2^31) to 2^31 – 1
     Unsigned: From 0 to 4,294,967,295 which equals 2^32 - 1

     Long - Max range
     Signed: From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, from -(2^63) to 2^63 - 1
     Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 2^64 – 1
     */

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I was developing flutter using android studio and running the simulator, the simulator was dark and I reset the contents as per accepted answer. But that didn't fix my issue. My CPU was running somehow high enough, so I restarted , but not fixed the issue. I opened Xcode and run one of my native iOS apps, the simulator re-opened as usual. I closed the Xcode and opened Android Studio, then started developing flutter app again.

Using classes with the Arduino

My Webduino library is all based on a C++ class that implements a web server on top of the Arduino Ethernet shield. I defined the whole class in a .h file that any Arduino code can #include. Feel free to look at the code to see how I do it... I ended up just defining it all inline because there's no real reason to separately compile objects with the Arduino IDE.

How to convert int to date in SQL Server 2008

Reading through this helps solve a similar problem. The data is in decimal datatype - [DOB] [decimal](8, 0) NOT NULL - eg - 19700109. I want to get at the month. The solution is to combine SUBSTRING with CONVERT to VARCHAR.

    SELECT [NUM]
       ,SUBSTRING(CONVERT(VARCHAR, DOB),5,2) AS mob
    FROM [Dbname].[dbo].[Tablename] 

Creating threads - Task.Factory.StartNew vs new Thread()

The task gives you all the goodness of the task API:

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

Note that in both cases you can make your code slightly simpler with method group conversions:

DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);

Returning http status code from Web Api controller

Another option:

return new NotModified();

public class NotModified : IHttpActionResult
{
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.NotModified);
        return Task.FromResult(response);
    }
}

Visual Studio Code: format is not using indent settings

If @Maleki's answer isn't working for you, check and see if you have an .editorconfig file in your project folder.

For example the Angular CLI generates one with a new project that looks like this

# Editor configuration, see http://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
max_line_length = off
trim_trailing_whitespace = false

Changing the indent_size here is required as it seems it will override anything in your .vscode workspace or user settings.

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

try this=> numpy.array(yourvariable) followed by the command to compare, whatever you wish to.

How to detect when facebook's FB.init is complete

Sometimes fbAsyncInit doesnt work. I dont know why and use this workaround then:

 var interval = window.setInterval(function(){
    if(typeof FB != 'undefined'){
        FB.init({
            appId      : 'your ID',
            cookie     : true,  // enable cookies to allow the server to access// the session
            xfbml      : true,  // parse social plugins on this page
            version    : 'v2.3' // use version 2.3
        });

        FB.getLoginStatus(function(response) {
            statusChangeCallback(response);
        });
        clearInterval(interval);
    }
},100);

Select first 10 distinct rows in mysql

Try this SELECT DISTINCT 10 * ...

- java.lang.NullPointerException - setText on null object reference

Here lies your problem:

private void fillTextView (int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text); // tv is null
}

--> (TextView) findViewById(id); // returns null But from your code, I can't find why this method returns null. Try to track down, what id you give as a parameter and if this view with the specified id exists.

The error message is very clear and even tells you at what method. From the documentation:

public final View findViewById (int id)
    Look for a child view with the given id. If this view has the given id, return this view.
    Parameters
        id  The id to search for.
    Returns
        The view that has the given id in the hierarchy or null

http://developer.android.com/reference/android/view/View.html#findViewById%28int%29

In other words: You have no view with the id you give as a parameter.

Vertically aligning CSS :before and :after content

Answered my own question after reading your advice on the vertical-align CSS attribute. Thanks for the tip!

.pdf:before {
    padding: 0 5px 0 0;
    content: url(../img/icon/pdf_small.png);
    vertical-align: -50%;
}

Missing maven .m2 folder

Check the configurations in {M2_HOME}\conf\setting.xml as mentioned in the following link.

http://www.mkyong.com/maven/where-is-maven-local-repository/

Hope this helps.

Limiting floats to two decimal points

What about a lambda function like this:

arred = lambda x,n : x*(10**n)//1/(10**n)

This way you could just do:

arred(3.141591657,2)

and get

3.14

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

I've had the same problem in one of my modules.

Running "mvn eclipse:eclipse" in the console/cmd solved the problem for me.

How can I find out if I have Xcode commandline tools installed?

I was able to find my version of Xcode on maxOS Sierra using this command:

pkgutil --pkg-info=com.apple.pkg.CLTools_Executables | grep version

as per this answer.

How to merge a specific commit in Git

I used to cherry pick, but found I had some mysterious issues from time to time. I came across a blog by Raymond Chen, a 25 year veteran at Microsoft, that describes some scenarios where cherry picking can cause issues in certain cases.

One of the rules of thumb is, if you cherry pick from one branch into another, then later merge between those branches, you're likely sooner or later going to experience issues.

Here's a reference to Raymond Chen's blogs on this topic: https://devblogs.microsoft.com/oldnewthing/20180312-00/?p=98215

The only issue I had with Raymond's blog is he did not provide a full working example. So I will attempt to provide one here.

The question above asks how to merge only the commit pointed to by the HEAD in the a-good-feature branch over to master.

Here is how that would be done:

  1. Find the common ancestor between the master and a-good-feature branches.
  2. Create a new branch from that ancestor, we'll call this new branch patch.
  3. Cherry pick one or more commits into this new patch branch.
  4. Merge the patch branch into both the master and a-good-feature branches.
  5. The master branch will now contain the commits, and both master and a-good-feature branches will also have a new common ancestor, which will resolve any future issues if further merging is performed later on.

Here is an example of those commands:

git checkout master...a-good-feature  [checkout the common ancestor]
git checkout -b patch
git cherry-pick a-good-feature  [this is not only the branch name, but also the commit we want]
git checkout master
git merge patch
git checkout a-good-feature
git merge -s ours patch

It might be worth noting that the last line that merged into the a-good-feature branch used the "-s ours" merge strategy. The reason for this is because we simply need to create a commit in the a-good-feature branch that points to a new common ancestor, and since the code is already in that branch, we want to make sure there isn't any chance of a merge conflict. This becomes more important if the commit(s) you are merging are not the most recent.

The scenarios and details surrounding partial merges can get pretty deep, so I recommend reading through all 10 parts of Raymond Chen's blog to gain a full understanding of what can go wrong, how to avoid it, and why this works.

What size should TabBar images be?

Thumbs up first before use codes please!!! Create an image that fully cover the whole tab bar item for each item. This is needed to use the image you created as a tab bar item button. Be sure to make the height/width ratio be the same of each tab bar item too. Then:

UITabBarController *tabBarController = (UITabBarController *)self;
UITabBar *tabBar = tabBarController.tabBar;
UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];

int x,y;

x = tabBar.frame.size.width/4 + 4; //when doing division, it may be rounded so that you need to add 1 to each item; 
y = tabBar.frame.size.height + 10; //the height return always shorter, this is compensated by added by 10; you can change the value if u like.

//because the whole tab bar item will be replaced by an image, u dont need title
tabBarItem1.title = @"";
tabBarItem2.title = @"";
tabBarItem3.title = @"";
tabBarItem4.title = @"";

[tabBarItem1 setFinishedSelectedImage:[self imageWithImage:[UIImage imageNamed:@"item1-select.png"] scaledToSize:CGSizeMake(x, y)] withFinishedUnselectedImage:[self imageWithImage:[UIImage imageNamed:@"item1-deselect.png"] scaledToSize:CGSizeMake(x, y)]];//do the same thing for the other 3 bar item

Razor Views not seeing System.Web.Mvc.HtmlHelper

I had the same issue when updating to MVC 5 and it was solved by updating the web.config inside the Views folder.

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
  </namespaces>
</pages>

The host -> factoryType was set to version:4.0.0.0 hope this helps anyone.

SVN repository backup strategies

If you are using the FSFS repository format (the default), then you can copy the repository itself to make a backup. With the older BerkleyDB system, the repository is not platform independent and you would generally want to use svnadmin dump.

The svnbook documentation topic for backup recommends the svnadmin hotcopy command, as it will take care of issues like files in use and such.

Regex to check with starts with http://, https:// or ftp://

I think the regex / string parsing solutions are great, but for this particular context, it seems like it would make sense just to use java's url parser:

https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html

Taken from that page:

import java.net.*;
import java.io.*;

public class ParseURL {
    public static void main(String[] args) throws Exception {

        URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                           + "/index.html?name=networking#DOWNLOADING");

        System.out.println("protocol = " + aURL.getProtocol());
        System.out.println("authority = " + aURL.getAuthority());
        System.out.println("host = " + aURL.getHost());
        System.out.println("port = " + aURL.getPort());
        System.out.println("path = " + aURL.getPath());
        System.out.println("query = " + aURL.getQuery());
        System.out.println("filename = " + aURL.getFile());
        System.out.println("ref = " + aURL.getRef());
    }
}

yields the following:

protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

How can I convert an Integer to localized month name in Java?

You need to use LLLL for stand-alone month names. this is documented in the SimpleDateFormat documentation, such as:

SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );

Overloading operators in typedef structs (c++)

  1. bool operator==(pos a) const{ - this method doesn't change object's elements.
  2. bool operator==(pos a) { - it may change object's elements.

How to get HttpClient to pass credentials along with the request?

You can configure HttpClient to automatically pass credentials like this:

var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

How do I check how many options there are in a dropdown menu?

Use the length property or the size method to find out how many items are in a jQuery collection. Use the descendant selector to select all <option>'s within a <select>.

HTML:

<select id="myDropDown">
<option>1</option>
<option>2</option>
.
.
.
</select>

JQuery:

var numberOfOptions = $('select#myDropDown option').length

And a quick note, often you will need to do something in jquery for a very specific thing, but you first need to see if the very specific thing exists. The length property is the perfect tool. example:

   if($('#myDropDown option').length > 0{
      //do your stuff..
    } 

This 'translates' to "If item with ID=myDropDown has any descendent 'option' s, go do what you need to do.

Regex: Use start of line/end of line signs (^ or $) in different context

you just need to use word boundary (\b) instead of ^ and $:

\bgarp\b

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

Here is another way that gives you access to the key and the value at the same time, in case you have to do some kind of transformation.

Map<String, Integer> pointsByName = new HashMap<>();
Map<String, Integer> maxPointsByName = new HashMap<>();

Map<String, Double> gradesByName = pointsByName.entrySet().stream()
        .map(entry -> new AbstractMap.SimpleImmutableEntry<>(
                entry.getKey(), ((double) entry.getValue() /
                        maxPointsByName.get(entry.getKey())) * 100d))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Hashmap holding different data types as values for instance Integer, String and Object

If you don't have Your own Data Class, then you can design your map as follows

Map<Integer, Object> map=new HashMap<Integer, Object>();

Here don't forget to use "instanceof" operator while retrieving the values from MAP.

If you have your own Data class then then you can design your map as follows

Map<Integer, YourClassName> map=new HashMap<Integer, YourClassName>();

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class HashMapTest {
public static void main(String[] args) {
    Map<Integer,Demo> map=new HashMap<Integer, Demo>();
    Demo d1= new Demo(1,"hi",new Date(),1,1);
    Demo d2= new Demo(2,"this",new Date(),2,1);
    Demo d3= new Demo(3,"is",new Date(),3,1);
    Demo d4= new Demo(4,"mytest",new Date(),4,1);
    //adding values to map
    map.put(d1.getKey(), d1);
    map.put(d2.getKey(), d2);
    map.put(d3.getKey(), d3);
    map.put(d4.getKey(), d4);
    //retrieving values from map
    Set<Integer> keySet= map.keySet();
    for(int i:keySet){
        System.out.println(map.get(i));
    }
    //searching key on map
    System.out.println(map.containsKey(d1.getKey()));
    //searching value on map
    System.out.println(map.containsValue(d1));
}

}
class Demo{
    private int key;
    private String message;
    private Date time;
    private int count;
    private int version;

    public Demo(int key,String message, Date time, int count, int version){
        this.key=key;
        this.message = message;
        this.time = time;
        this.count = count;
        this.version = version;
    }
    public String getMessage() {
        return message;
    }
    public Date getTime() {
        return time;
    }
    public int getCount() {
        return count;
    }
    public int getVersion() {
        return version;
    }
    public int getKey() {
        return key;
    }
    @Override
    public String toString() {
        return "Demo [message=" + message + ", time=" + time
                + ", count=" + count + ", version=" + version + "]";
    }

}

How to set a string's color

I created an API called JCDP, former JPrinter, which stands for Java Colored Debug Printer. For Linux it uses the ANSI escape codes that WhiteFang mentioned, but abstracts them using words instead of codes which is much more intuitive. For Windows it actually includes the JAnsi library but creates an abstraction layer over it, maintaining the intuitive and simple interface created for Linux.

This library is licensed under the MIT License so feel free to use it.

Have a look at JCDP's github repository.

Two column div layout with fluid left and fixed right column

CSS:

#sidebar {float: right; width: 200px; background: #eee;}
#content {overflow: hidden; background: #dad;}

HTML:

<div id="sidebar">I'm 200px wide</div>
<div id="content"> I take up the remaining space <br> and I don't wrap under the right column</div>

The above should work, you can put that code in wrapper if you want the give it width and center it too, overflow:hidden on the column without a width is the key to getting it to contain, vertically, as in not wrap around the side columns (can be left or right)

IE6 might need zoom:1 set on the #content div too if you need it's support

python pandas dataframe columns convert to dict key and value

If lakes is your DataFrame, you can do something like

area_dict = dict(zip(lakes.area, lakes.count))

Run R script from command line

You need the ?Rscript command to run an R script from the terminal.

Check out http://stat.ethz.ch/R-manual/R-devel/library/utils/html/Rscript.html

Example

## example #! script for a Unix-alike

#! /path/to/Rscript --vanilla --default-packages=utils
args <- commandArgs(TRUE)
res <- try(install.packages(args))
if(inherits(res, "try-error")) q(status=1) else q()

Is embedding background image data into CSS as Base64 good or bad practice?

As far as I have researched,

Use : 1. When you are using an svg sprite. 2. When your images are of a lesser size (max 200mb).

Don't Use : 1. When you are bigger images. 2. Icons as svg's. As they are already good and gzipped after compression.

Application not picking up .css file (flask/python)

In jinja2 templates (which flask uses), use

href="{{ url_for('static', filename='mainpage.css')}}"

The static files are usually in the static folder, though, unless configured otherwise.

Oracle: Call stored procedure inside the package

You're nearly there, just take out the EXECUTE:

DECLARE
  procId NUMBER;

BEGIN
  PKG1.INIT(1143824, 0, procId);
  DBMS_OUTPUT.PUT_LINE(procId);
END;

Junit test case for database insert method with DAO and web service

@Test
public void testSearchManagementStaff() throws SQLException
{
    boolean res=true;
    ManagementDaoImp mdi=new ManagementDaoImp();
    boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
    assertEquals(res,b);
}

How to convert a String to Bytearray

If you are looking for a solution that works in node.js, you can use this:

var myBuffer = [];
var str = 'Stack Overflow';
var buffer = new Buffer(str, 'utf16le');
for (var i = 0; i < buffer.length; i++) {
    myBuffer.push(buffer[i]);
}

console.log(myBuffer);

How to use JavaScript with Selenium WebDriver Java

Following code worked for me:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;

public class SomeClass {

    @Autowired
    private WebDriver driver;

     public void LogInSuperAdmin() {
        ((JavascriptExecutor) driver).executeScript("console.log('Test test');");
     }
}

Re-render React component when prop changes

A friendly method to use is the following, once prop updates it will automatically rerender component:

render {

let textWhenComponentUpdate = this.props.text 

return (
<View>
  <Text>{textWhenComponentUpdate}</Text>
</View>
)

}

Use VBA to Clear Immediate Window?

For cleaning Immediate window I use (VBA Excel 2016) next function:

Private Sub ClrImmediate()
   With Application.VBE.Windows("Immediate")
       .SetFocus
       Application.SendKeys "^g", True
       Application.SendKeys "^a", True
       Application.SendKeys "{DEL}", True
   End With
End Sub

But direct call of ClrImmediate() like this:

Sub ShowCommandBarNames()
    ClrImmediate
 '--   DoEvents    
    Debug.Print "next..."
End Sub

works only if i put the breakpoint on Debug.Print, otherwise the clearing will be done after execution of ShowCommandBarNames() - NOT before Debug.Print. Unfortunately, call of DoEvents() did not help me... And no matter: TRUE or FALSE is set for SendKeys.

To solve this I use next couple of calls:

Sub ShowCommandBarNames()
 '--    ClrImmediate
    Debug.Print "next..."
End Sub

Sub start_ShowCommandBarNames()
   ClrImmediate
   Application.OnTime Now + TimeSerial(0, 0, 1), "ShowCommandBarNames"
End Sub

It seems to me that using Application.OnTime might be very useful in programming for VBA IDE. In this case it's can be used even TimeSerial(0, 0, 0).

"unrecognized selector sent to instance" error in Objective-C

OK, I have to chip in here. The OP dynamically created the button. I had a similar issue and the answer (after hours of hunting) is so simple it made me sick.

When using:

action:@selector(xxxButtonClick:)

or (as in my case)

action:NSSelectorFromString([[NSString alloc] initWithFormat:@"%@BtnTui:", name.lowercaseString])

If you place a colon at the end of the string - it will pass the sender. If you do not place the colon at the end of the string it will not, and the receiver will get an error if it expects one. It is easy to miss the colon if you are dynamically creating the event name.

The receiver code options look like this:

- (void)doneBtnTui:(id)sender {
  NSLog(@"Done Button - with sender");
}
 or
- (void)doneBtnTui {
  NSLog(@"Done Button - no sender");
}

As usual, it is always the obvious answer that gets missed.

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

For me logging in as -Y instead of -X worked.

In case you've got untrusted X11 as shown below, then try -Y flag instead (if you trust the host):

Warning: untrusted X11 forwarding setup failed: xauth key data not generated

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

How to display an unordered list in two columns?

more one answer after a few years!

in this article: http://csswizardry.com/2010/02/mutiple-column-lists-using-one-ul/

HTML:

<ul id="double"> <!-- Alter ID accordingly -->
  <li>CSS</li>
  <li>XHTML</li>
  <li>Semantics</li>
  <li>Accessibility</li>
  <li>Usability</li>
  <li>Web Standards</li>
  <li>PHP</li>
  <li>Typography</li>
  <li>Grids</li>
  <li>CSS3</li>
  <li>HTML5</li>
  <li>UI</li>
</ul>

CSS:

ul{
  width:760px;
  margin-bottom:20px;
  overflow:hidden;
  border-top:1px solid #ccc;
}
li{
  line-height:1.5em;
  border-bottom:1px solid #ccc;
  float:left;
  display:inline;
}
#double li  { width:50%;}
#triple li  { width:33.333%; }
#quad li    { width:25%; }
#six li     { width:16.666%; }

nvm is not compatible with the npm config "prefix" option:

I had this issue after moving my home folder to a new drive on linux. It was fixed by removing .nvm folder and reinstalling nvm

How to convert an array to object in PHP?

use this function that i've made:

function buildObject($class,$data){
    $object = new $class;
    foreach($data as $key=>$value){
        if(property_exists($class,$key)){
            $object->{'set'.ucfirst($key)}($value);
        }
    }
    return $object;
}

Usage:

$myObject = buildObject('MyClassName',$myArray);

Most popular screen sizes/resolutions on Android phones

Here is a list of almost all resolutions of tablets, with the most common ones in bold :

2560X1600
1366X768

1920X1200
1280X800
1280X768
1024X800
1024X768
1024X600

960X640
960X540
854X480
800X600
800X480
800X400

Happy designing .. ! :)

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

How to use Selenium with Python?

You just need to get selenium package imported, that you can do from command prompt using the command

pip install selenium

When you have to use it in any IDE just import this package, no other documentation required to be imported

For Eg :

import selenium 
print(selenium.__filepath__)

This is just a general command you may use in starting to check the filepath of selenium

How to communicate between Docker containers via "hostname"

That should be what --link is for, at least for the hostname part.
With docker 1.10, and PR 19242, that would be:

docker network create --net-alias=[]: Add network-scoped alias for the container

(see last section below)

That is what Updating the /etc/hosts file details

In addition to the environment variables, Docker adds a host entry for the source container to the /etc/hosts file.

For instance, launch an LDAP server:

docker run -t  --name openldap -d -p 389:389 larrycai/openldap

And define an image to test that LDAP server:

FROM ubuntu
RUN apt-get -y install ldap-utils
RUN touch /root/.bash_aliases
RUN echo "alias lds='ldapsearch -H ldap://internalopenldap -LL -b
ou=Users,dc=openstack,dc=org -D cn=admin,dc=openstack,dc=org -w
password'" > /root/.bash_aliases
ENTRYPOINT bash

You can expose the 'openldap' container as 'internalopenldap' within the test image with --link:

 docker run -it --rm --name ldp --link openldap:internalopenldap ldaptest

Then, if you type 'lds', that alias will work:

ldapsearch -H ldap://internalopenldap ...

That would return people. Meaning internalopenldap is correctly reached from the ldaptest image.


Of course, docker 1.7 will add libnetwork, which provides a native Go implementation for connecting containers. See the blog post.
It introduced a more complete architecture, with the Container Network Model (CNM)

https://blog.docker.com/media/2015/04/cnm-model.jpg

That will Update the Docker CLI with new “network” commands, and document how the “-net” flag is used to assign containers to networks.


docker 1.10 has a new section Network-scoped alias, now officially documented in network connect:

While links provide private name resolution that is localized within a container, the network-scoped alias provides a way for a container to be discovered by an alternate name by any other container within the scope of a particular network.
Unlike the link alias, which is defined by the consumer of a service, the network-scoped alias is defined by the container that is offering the service to the network.

Continuing with the above example, create another container in isolated_nw with a network alias.

$ docker run --net=isolated_nw -itd --name=container6 -alias app busybox
8ebe6767c1e0361f27433090060b33200aac054a68476c3be87ef4005eb1df17

--alias=[]         

Add network-scoped alias for the container

You can use --link option to link another container with a preferred alias

You can pause, restart, and stop containers that are connected to a network. Paused containers remain connected and can be revealed by a network inspect. When the container is stopped, it does not appear on the network until you restart it.

If specified, the container's IP address(es) is reapplied when a stopped container is restarted. If the IP address is no longer available, the container fails to start.

One way to guarantee that the IP address is available is to specify an --ip-range when creating the network, and choose the static IP address(es) from outside that range. This ensures that the IP address is not given to another container while this container is not on the network.

$ docker network create --subnet 172.20.0.0/16 --ip-range 172.20.240.0/20 multi-host-network

$ docker network connect --ip 172.20.128.2 multi-host-network container2
$ docker network connect --link container1:c1 multi-host-network container2

create array from mysql query php

Very often this is done in a while loop:

$types = array();

while(($row =  mysql_fetch_assoc($result))) {
    $types[] = $row['type'];
}

Have a look at the examples in the documentation.

The mysql_fetch_* methods will always get the next element of the result set:

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

That is why the while loops works. If there aren't any rows anymore $row will be false and the while loop exists.

It only seems that mysql_fetch_array gets more than one row, because by default it gets the result as normal and as associative value:

By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.

Your example shows it best, you get the same value 18 and you can access it via $v[0] or $v['type'].

what is right way to do API call in react js?

It would be great to use axios for the api request which supports cancellation, interceptors etc. Along with axios, l use react-redux for state management and redux-saga/redux-thunk for the side effects.

How to add a footer to the UITableView?

I had the same problem but I replaced the following line in my header:

@interface MyController : UIViewTableViewController <UITableViewDelegate, UITableViewDataSource>

with this line and it works as expected:

@interface RequestViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

Notice the UIViewController. Good luck :)

How can I check if a MySQL table exists with PHP?

Even faster than a bad query:

SELECT count((1)) as `ct`  FROM INFORMATION_SCHEMA.TABLES where table_schema ='yourdatabasename' and table_name='yourtablename';

This way you can just retrieve one field and one value. .016 seconds for my slower system.

Div height 100% and expands to fit content

This question may be old, but it deserves an update. Here is another way to do that:

#yourdiv {
    display: flex;
    width:100%;
    height:100%;
}

How can I find a specific file from a Linux terminal?

Find from root path find / -name "index.html"

Find from current path find . -name "index.html"

C#: Looping through lines of multiline string

Try using String.Split Method:

string text = @"First line
second line
third line";

foreach (string line in text.Split('\n'))
{
    // do something
}

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

Uninstall homebrew:

 ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Then reinstall

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Warning: This script will remove: /Library/Caches/Homebrew/ - thks benjaminsila

SQL Server, How to set auto increment after creating a table without data loss?

Yes, you can. Go to Tools > Designers > Table and Designers and uncheck "Prevent Saving Changes That Prevent Table Recreation".

How to solve npm error "npm ERR! code ELIFECYCLE"

I did follow steps, it works:

1.

npm cache clean --force
  1. remove the package-lock.json file

  2. restart my WebStorm

adding 1 day to a DATETIME format value

The DateTime constructor takes a parameter string time. $time can be different things, it has to respect the datetime format.

There are some valid values as examples :

  • 'now' (the default value)
  • 2017-10-19
  • 2017-10-19 11:59:59
  • 2017-10-19 +1day

So, in your case you can use the following.

$dt = new \DateTime('now +1 day'); //Tomorrow
$dt = new \DateTime('2016-01-01 +1 day'); //2016-01-02

How do I fix the indentation of an entire file in Vi?

:set paste is your friend I use putty and end up copying code between windows. Before I was turned on to :set paste (and :set nopaste) copy/paste gave me fits for that very reason.

Calculate a MD5 hash from a string

https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5?view=netframework-4.7.2

using System;
using System.Security.Cryptography;
using System.Text;

    static string GetMd5Hash(string input)
            {
                using (MD5 md5Hash = MD5.Create())
                {

                    // Convert the input string to a byte array and compute the hash.
                    byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

                    // Create a new Stringbuilder to collect the bytes
                    // and create a string.
                    StringBuilder sBuilder = new StringBuilder();

                    // Loop through each byte of the hashed data 
                    // and format each one as a hexadecimal string.
                    for (int i = 0; i < data.Length; i++)
                    {
                        sBuilder.Append(data[i].ToString("x2"));
                    }

                    // Return the hexadecimal string.
                    return sBuilder.ToString();
                }
            }

            // Verify a hash against a string.
            static bool VerifyMd5Hash(string input, string hash)
            {
                // Hash the input.
                string hashOfInput = GetMd5Hash(input);

                // Create a StringComparer an compare the hashes.
                StringComparer comparer = StringComparer.OrdinalIgnoreCase;

                return 0 == comparer.Compare(hashOfInput, hash);

            }

Getting current unixtimestamp using Moment.js

To find the Unix Timestamp in seconds:

moment().unix()

The documentation is your friend. :)

What can MATLAB do that R cannot do?

We can't because it's expected/required by our customers.

How to use HTTP GET in PowerShell?

In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:

$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

React: why child component doesn't update when prop changes

export default function DataTable({ col, row }) {
  const [datatable, setDatatable] = React.useState({});
  useEffect(() => {
    setDatatable({
      columns: col,
      rows: row,
    });
  /// do any thing else 
  }, [row]);

  return (
    <MDBDataTableV5
      hover
      entriesOptions={[5, 20, 25]}
      entries={5}
      pagesAmount={4}
      data={datatable}
    />
  );
}

this example use useEffect to change state when props change.

How to change a field name in JSON using Jackson

Be aware that there is org.codehaus.jackson.annotate.JsonProperty in Jackson 1.x and com.fasterxml.jackson.annotation.JsonProperty in Jackson 2.x. Check which ObjectMapper you are using (from which version), and make sure you use the proper annotation.

"Unmappable character for encoding UTF-8" error

"error: unmappable character for encoding UTF-8" means, java has found a character which is not representing in UTF-8. Hence open the file in an editor and set the character encoding to UTF-8. You should be able to find a character which is not represented in UTF-8.Take off this character and recompile.

accepting HTTPS connections with self-signed certificates

The following main steps are required to achieve a secured connection from Certification Authorities which are not considered as trusted by the android platform.

As requested by many users, I've mirrored the most important parts from my blog article here:

  1. Grab all required certificates (root and any intermediate CA’s)
  2. Create a keystore with keytool and the BouncyCastle provider and import the certs
  3. Load the keystore in your android app and use it for the secured connections (I recommend to use the Apache HttpClient instead of the standard java.net.ssl.HttpsURLConnection (easier to understand, more performant)

Grab the certs

You have to obtain all certificates that build a chain from the endpoint certificate the whole way up to the Root CA. This means, any (if present) Intermediate CA certs and also the Root CA cert. You don’t need to obtain the endpoint certificate.

Create the keystore

Download the BouncyCastle Provider and store it to a known location. Also ensure that you can invoke the keytool command (usually located under the bin folder of your JRE installation).

Now import the obtained certs (don’t import the endpoint cert) into a BouncyCastle formatted keystore.

I didn’t test it, but I think the order of importing the certificates is important. This means, import the lowermost Intermediate CA certificate first and then all the way up to the Root CA certificate.

With the following command a new keystore (if not already present) with the password mysecret will be created and the Intermediate CA certificate will be imported. I also defined the BouncyCastle provider, where it can be found on my file system and the keystore format. Execute this command for each certificate in the chain.

keytool -importcert -v -trustcacerts -file "path_to_cert/interm_ca.cer" -alias IntermediateCA -keystore "res/raw/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "path_to_bouncycastle/bcprov-jdk16-145.jar" -storetype BKS -storepass mysecret

Verify if the certificates were imported correctly into the keystore:

keytool -list -keystore "res/raw/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "path_to_bouncycastle/bcprov-jdk16-145.jar" -storetype BKS -storepass mysecret

Should output the whole chain:

RootCA, 22.10.2010, trustedCertEntry, Thumbprint (MD5): 24:77:D9:A8:91:D1:3B:FA:88:2D:C2:FF:F8:CD:33:93
IntermediateCA, 22.10.2010, trustedCertEntry, Thumbprint (MD5): 98:0F:C3:F8:39:F7:D8:05:07:02:0D:E3:14:5B:29:43

Now you can copy the keystore as a raw resource in your android app under res/raw/

Use the keystore in your app

First of all we have to create a custom Apache HttpClient that uses our keystore for HTTPS connections:

import org.apache.http.*

public class MyHttpClient extends DefaultHttpClient {

    final Context context;

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

    @Override
    protected ClientConnectionManager createClientConnectionManager() {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        // Register for port 443 our SSLSocketFactory with our keystore
        // to the ConnectionManager
        registry.register(new Scheme("https", newSslSocketFactory(), 443));
        return new SingleClientConnManager(getParams(), registry);
    }

    private SSLSocketFactory newSslSocketFactory() {
        try {
            // Get an instance of the Bouncy Castle KeyStore format
            KeyStore trusted = KeyStore.getInstance("BKS");
            // Get the raw resource, which contains the keystore with
            // your trusted certificates (root and any intermediate certs)
            InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
            try {
                // Initialize the keystore with the provided trusted certificates
                // Also provide the password of the keystore
                trusted.load(in, "mysecret".toCharArray());
            } finally {
                in.close();
            }
            // Pass the keystore to the SSLSocketFactory. The factory is responsible
            // for the verification of the server certificate.
            SSLSocketFactory sf = new SSLSocketFactory(trusted);
            // Hostname verification from certificate
            // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
            sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            return sf;
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
}

We have created our custom HttpClient, now we can use it for secure connections. For example when we make a GET call to a REST resource:

// Instantiate the custom HttpClient
DefaultHttpClient client = new MyHttpClient(getApplicationContext());
HttpGet get = new HttpGet("https://www.mydomain.ch/rest/contacts/23");
// Execute the GET call and obtain the response
HttpResponse getResponse = client.execute(get);
HttpEntity responseEntity = getResponse.getEntity();

That's it ;)

WooCommerce: Finding the products in database

I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta table. You can find the corresponding products within wp_posts table.

Merge PDF files

Use Pypdf or its successor PyPDF2:

A Pure-Python library built as a PDF toolkit. It is capable of:
* splitting documents page by page,
* merging documents page by page,

(and much more)

Here's a sample program that works with both versions.

#!/usr/bin/env python
import sys
try:
    from PyPDF2 import PdfFileReader, PdfFileWriter
except ImportError:
    from pyPdf import PdfFileReader, PdfFileWriter

def pdf_cat(input_files, output_stream):
    input_streams = []
    try:
        # First open all the files, then produce the output file, and
        # finally close the input files. This is necessary because
        # the data isn't read from the input files until the write
        # operation. Thanks to
        # https://stackoverflow.com/questions/6773631/problem-with-closing-python-pypdf-writing-getting-a-valueerror-i-o-operation/6773733#6773733
        for input_file in input_files:
            input_streams.append(open(input_file, 'rb'))
        writer = PdfFileWriter()
        for reader in map(PdfFileReader, input_streams):
            for n in range(reader.getNumPages()):
                writer.addPage(reader.getPage(n))
        writer.write(output_stream)
    finally:
        for f in input_streams:
            f.close()

if __name__ == '__main__':
    if sys.platform == "win32":
        import os, msvcrt
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    pdf_cat(sys.argv[1:], sys.stdout)

How does one create an InputStream from a String?

Java 7+

It's possible to take advantage of the StandardCharsets JDK class:

String str=...
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(str).array());

How to check if C string is empty

If you want to check if a string is empty:

if (str[0] == '\0')
{
    // your code here
}

Event handlers for Twitter Bootstrap dropdowns?

Try this:

$('div.btn-group ul.dropdown-menu li a').click(function (e) {
    var $div = $(this).parent().parent().parent(); 
    var $btn = $div.find('button');
    $btn.html($(this).text() + ' <span class="caret"></span>');
    $div.removeClass('open');
    e.preventDefault();
    return false;
});

Convert string with commas to array

More "Try it Yourself" examples below.

Definition and Usage The split() method is used to split a string into an array of substrings, and returns the new array.

Tip: If an empty string ("") is used as the separator, the string is split between each character.

Note: The split() method does not change the original string.

var res = str.split(",");

How do I print an IFrame from javascript in Safari/Chrome

Use this:

window.onload = setTimeout("window.print()", 1000);

client denied by server configuration

In my case, I modified directory tag.

From

<Directory "D:/Devel/matysart/matysart_dev1">
  Allow from all
  Order Deny,Allow
</Directory>

To

<Directory "D:/Devel/matysart/matysart_dev1">
  Require local
</Directory>

And it seriously worked. It's seems changed with Apache 2.4.2.

Open Excel file for reading with VBA without display

Open them from a new instance of Excel.

Sub Test()

    Dim xl As Excel.Application
    Set xl = CreateObject("Excel.Application")

    Dim w As Workbook
    Set w = xl.Workbooks.Add()

    MsgBox "Not visible yet..."
    xl.Visible = True

    w.Close False
    Set xl = Nothing

End Sub

You need to remember to clean up after you're done.

Does --disable-web-security Work In Chrome Anymore?

This flag worked for me at v30.0.1599.101 m enter image description here

The warning "You are using an unsupported command-line flag" can be ignored. The flag still works (as of Chrome v86).

rsync copy over only certain types of files using include option

Wrote this handy function and put in my bash scripts or ~/.bash_aliases. Tested sync'ing locally on Linux with bash and awk installed. It works

selrsync(){
# selective rsync to sync only certain filetypes;
# based on: https://stackoverflow.com/a/11111793/588867
# Example: selrsync 'tsv,csv' ./source ./target --dry-run
types="$1"; shift; #accepts comma separated list of types. Must be the first argument.
includes=$(echo $types| awk  -F',' \
    'BEGIN{OFS=" ";}
    {
    for (i = 1; i <= NF; i++ ) { if (length($i) > 0) $i="--include=*."$i; } print
    }')
restargs="$@"

echo Command: rsync -avz --prune-empty-dirs --include="*/" $includes --exclude="*" "$restargs"
eval rsync -avz --prune-empty-dirs --include="*/" "$includes" --exclude="*" $restargs
}

Avantages:

short handy and extensible when one wants to add more arguments (i.e. --dry-run).

Example:

selrsync 'tsv,csv' ./source ./target --dry-run

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)

Using C# to check if string contains a string in string array

Simple solution, not required linq any

String.Join(",", array).Contains(Value+",");

What is the difference between properties and attributes in HTML?

well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html

but currently attr and prop are not so different and there are almost the same

but they prefer prop for some things

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)

Converting time stamps in excel to dates

Be aware of number of digits in epoch time. Usually they are ten (1534936923) ,then use:

=(A1 / 86400) + 25569    

For thirteen digits (1534936923000) of epoch time adjust the formula:

=(LEFT(A1,LEN(A1)-3) / 86400) + 25569    

to avoid

###################################

Dates or times that are negative or too large display as ######

See more on https://www.epochconverter.com/

How to use delimiter for csv in python

Your code is blanking out your file:

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)

if you want to read the file in, you will need to use csv.reader and open the file for reading.

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
    print line

If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).

How to read lines of a file in Ruby

Your first file has Mac Classic line endings (that’s "\r" instead of the usual "\n"). Open it with

File.open('foo').each(sep="\r") do |line|

to specify the line endings.

Will using 'var' affect performance?

There's no extra IL code for the var keyword: the resulting IL should be identical for non-anonymous types. If the compiler can't create that IL because it can't figure out what type you intended to use, you'll get a compiler error.

The only trick is that var will infer an exact type where you may have chosen an Interface or parent type if you were to set the type manually.


Update 8 Years Later

I need to update this as my understanding has changed. I now believe it may be possible for var to affect performance in the situation where a method returns an interface, but you would have used an exact type. For example, if you have this method:

IList<int> Foo()
{
    return Enumerable.Range(0,10).ToList();
}

Consider these three lines of code to call the method:

List<int> bar1 = Foo();
IList<int> bar = Foo();
var bar3 = Foo();

All three compile and execute as expected. However, the first two lines are not exactly the same, and the third line will match the second, rather than the first. Because the signature of Foo() is to return an IList<int>, that is how the compiler will build the bar3 variable.

From a performance standpoint, mostly you won't notice. However, there are situations where the performance of the third line may not be quite as fast as the performance of the first. As you continue to use the bar3 variable, the compiler may not be able to dispatch method calls the same way.

Note that it's possible (likely even) the jitter will be able to erase this difference, but it's not guaranteed. Generally, you should still consider var to be a non-factor in terms of performance. It's certainly not at all like using a dynamic variable. But to say it never makes a difference at all may be overstating it.

Yahoo Finance API

IMHO the best place to find this information is: http://code.google.com/p/yahoo-finance-managed/

I used to use the "gummy-stuff" too but then I found this page which is far more organized and full of easy to use examples. I am using it now to get the data in CSV files and use the files in my C++/Qt project.

How to pass url arguments (query string) to a HTTP request on Angular?

import ...
declare var $:any;
...
getSomeEndPoint(params:any): Observable<any[]> {
    var qStr = $.param(params); //<---YOUR GUY
    return this._http.get(this._adUrl+"?"+qStr)
      .map((response: Response) => <any[]> response.json())
      .catch(this.handleError);
}

provided that you have installed jQuery, I do npm i jquery --save and include in apps.scripts in angular-cli.json

How to easily duplicate a Windows Form in Visual Studio?

  1. Right-Click on Form -> Copy Class

enter image description here

  1. Right click on destination Folder and Paste Class

enter image description here

  1. Rename new Form and say yes to renaming all references to this class.

enter image description here

Android/Eclipse: how can I add an image in the res/drawable folder?

When inserting an image into the drawable folders, another import point in addition to the "no capital letters" rule is that the image name cannot contain dashes or other special characters.

How to apply border radius in IE8 and below IE8 browsers?

The border-radius property is supported in IE9+, Firefox 4+, Chrome, Safari 5+, and Opera, because it is CSS3 property. so, you could use css3pie

first check this demo in IE 8 and download it from here write your css rule like this

 #myAwesomeElement {
    border: 1px solid #999;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    behavior: url(path/to/pie_files/PIE.htc);
}   

note: added behavior: url(path/to/pie_files/PIE.htc); in the above rule. within url() you need to specify your PIE.htc file location

Windows equivalent of $export

There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.

What's the best way to iterate an Android Cursor?

Initially cursor is not on the first row show using moveToNext() you can iterate the cursor when record is not exist then it return false,unless it return true,

while (cursor.moveToNext()) {
    ...
}

List comprehension vs map

Actually, map and list comprehensions behave quite differently in the Python 3 language. Take a look at the following Python 3 program:

def square(x):
    return x*x
squares = map(square, [1, 2, 3])
print(list(squares))
print(list(squares))

You might expect it to print the line "[1, 4, 9]" twice, but instead it prints "[1, 4, 9]" followed by "[]". The first time you look at squares it seems to behave as a sequence of three elements, but the second time as an empty one.

In the Python 2 language map returns a plain old list, just like list comprehensions do in both languages. The crux is that the return value of map in Python 3 (and imap in Python 2) is not a list - it's an iterator!

The elements are consumed when you iterate over an iterator unlike when you iterate over a list. This is why squares looks empty in the last print(list(squares)) line.

To summarize:

  • When dealing with iterators you have to remember that they are stateful and that they mutate as you traverse them.
  • Lists are more predictable since they only change when you explicitly mutate them; they are containers.
  • And a bonus: numbers, strings, and tuples are even more predictable since they cannot change at all; they are values.

What does '&' do in a C++ declaration?

The "&" denotes a reference instead of a pointer to an object (In your case a constant reference).

The advantage of having a function such as

foo(string const& myname) 

over

foo(string const* myname)

is that in the former case you are guaranteed that myname is non-null, since C++ does not allow NULL references. Since you are passing by reference, the object is not copied, just like if you were passing a pointer.

Your second example:

const string &GetMethodName() { ... }

Would allow you to return a constant reference to, for example, a member variable. This is useful if you do not wish a copy to be returned, and again be guaranteed that the value returned is non-null. As an example, the following allows you direct, read-only access:

class A
{
  public:
  int bar() const {return someValue;}
  //Big, expensive to copy class
}

class B
{
public:
 A const& getA() { return mA;}
private:
 A mA;
}
void someFunction()
{
 B b = B();
 //Access A, ability to call const functions on A
 //No need to check for null, since reference is guaranteed to be valid.
 int value = b.getA().bar(); 
}

You have to of course be careful to not return invalid references. Compilers will happily compile the following (depending on your warning level and how you treat warnings)

int const& foo() 
{
 int a;

 //This is very bad, returning reference to something on the stack. This will
 //crash at runtime.
 return a; 
}

Basically, it is your responsibility to ensure that whatever you are returning a reference to is actually valid.

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

Does JavaScript pass by reference?

My two cents.... It's irrelevant whether JavaScript passes parameters by reference or value. What really matters is assignment vs. mutation.

I wrote a longer, more detailed explanation in this link.

When you pass anything (whether that be an object or a primitive), all JavaScript does is assign a new variable while inside the function... just like using the equal sign (=).

How that parameter behaves inside the function is exactly the same as it would behave if you just assigned a new variable using the equal sign... Take these simple examples.

_x000D_
_x000D_
var myString = 'Test string 1';

// Assignment - A link to the same place as myString
var sameString = myString;

// If I change sameString, it will not modify myString,
// it just re-assigns it to a whole new string
sameString = 'New string';

console.log(myString); // Logs 'Test string 1';
console.log(sameString); // Logs 'New string';
_x000D_
_x000D_
_x000D_

If I were to pass myString as a parameter to a function, it behaves as if I simply assigned it to a new variable. Now, let's do the same thing, but with a function instead of a simple assignment

_x000D_
_x000D_
function myFunc(sameString) {

  // Reassignment... Again, it will not modify myString
  sameString = 'New string';
}

var myString = 'Test string 1';

// This behaves the same as if we said sameString = myString
myFunc(myString);

console.log(myString); // Again, logs 'Test string 1';
_x000D_
_x000D_
_x000D_

The only reason that you can modify objects when you pass them to a function is because you are not reassigning... Instead, objects can be changed or mutated.... Again, it works the same way.

var myObject = { name: 'Joe'; }

// Assignment - We simply link to the same object
var sameObject = myObject;

// This time, we can mutate it. So a change to myObject affects sameObject and visa versa
myObject.name = 'Jack';
console.log(sameObject.name); // Logs 'Jack'

sameObject.name = 'Jill';
console.log(myObject.name); // Logs 'Jill'

// If we re-assign it, the link is lost
sameObject = { name: 'Howard' };
console.log(myObject.name); // Logs 'Jill'

If I were to pass myObject as a parameter to a function, it behaves as if I simply assigned it to a new variable. Again, the same thing with the exact same behavior but with a function.

_x000D_
_x000D_
function myFunc(sameObject) {
  // We mutate the object, so the myObject gets the change too... just like before.
  sameObject.name = 'Jill';

  // But, if we re-assign it, the link is lost
  sameObject = {
    name: 'Howard'
  };
}

var myObject = {
  name: 'Joe'
};

// This behaves the same as if we said sameObject = myObject;
myFunc(myObject);
console.log(myObject.name); // Logs 'Jill'
_x000D_
_x000D_
_x000D_

Every time you pass a variable to a function, you are "assigning" to whatever the name of the parameter is, just like if you used the equal = sign.

Always remember that the equals sign = means assignment. And passing a parameter to a function also means assignment. They are the same and the two variables are connected in exactly the same way.

The only time that modifying a variable affects a different variable is when the underlying object is mutated.

There is no point in making a distinction between objects and primitives, because it works the same exact way as if you didn't have a function and just used the equal sign to assign to a new variable.

Disable HttpClient logging

For me, the below lines in the log4j.properties file cleaned up all the mess that came from HttpClient logging... Hurray!!! :)

log4j.logger.org.apache.http.headers=ERROR
log4j.logger.org.apache.http.wire=ERROR
log4j.logger.org.apache.http.impl.conn.PoolingHttpClientConnectionManager=ERROR
log4j.logger.org.apache.http.impl.conn.DefaultManagedHttpClientConnection=ERROR
log4j.logger.org.apache.http.conn.ssl.SSLConnectionSocketFactory=ERROR
log4j.logger.org.springframework.web.client.RestTemplate=ERROR
log4j.logger.org.apache.http.client.protocol.RequestAddCookies=ERROR
log4j.logger.org.apache.http.client.protocol.RequestAuthCache=ERROR
log4j.logger.org.apache.http.impl.execchain.MainClientExec=ERROR
log4j.logger.org.apache.http.impl.conn.DefaultHttpClientConnectionOperator=ERROR

How to resolve /var/www copy/write permission denied?

Enter the following command in the directory you want to modify the right:

for example the directory: /var/www/html

sudo setfacl -m g:username:rwx . #-> for file

sudo setfacl -d -m g:username: rwx . #-> for directory

This will solve the problem.

Replace username with your username.

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

For me I was working under Ubuntu

The error disappeared if I use sudo with ng

sudo ng build
sudo ng serve

Service located in another namespace

It is so simple to do it

if you want to use it as host and want to resolve it

If you are using ambassador to any other API gateway for service located in another namespace it's always suggested to use :

            Use : <service name>
            Use : <service.name>.<namespace name>
            Not : <service.name>.<namespace name>.svc.cluster.local

it will be like : servicename.namespacename.svc.cluster.local

this will send request to a particular service inside the namespace you have mention.

example:

kind: Service
apiVersion: v1
metadata:
  name: service
spec:
  type: ExternalName
  externalName: <servicename>.<namespace>.svc.cluster.local

Here replace the <servicename> and <namespace> with the appropriate value.

In Kubernetes, namespaces are used to create virtual environment but all are connect with each other.

Calculate text width with JavaScript

Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.

_x000D_
_x000D_
var fontSize = 12;_x000D_
var test = document.getElementById("Test");_x000D_
test.style.fontSize = fontSize;_x000D_
var height = (test.clientHeight + 1) + "px";_x000D_
var width = (test.clientWidth + 1) + "px"_x000D_
_x000D_
console.log(height, width);
_x000D_
#Test_x000D_
{_x000D_
    position: absolute;_x000D_
    visibility: hidden;_x000D_
    height: auto;_x000D_
    width: auto;_x000D_
    white-space: nowrap; /* Thanks to Herb Caudill comment */_x000D_
}
_x000D_
<div id="Test">_x000D_
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS transition shorthand with multiple properties?

If you have several specific properties that you want to transition in the same way (because you also have some properties you specifically don't want to transition, say opacity), another option is to do something like this (prefixes omitted for brevity):

.myclass {
    transition: all 200ms ease;
    transition-property: box-shadow, height, width, background, font-size;
}

The second declaration overrides the all in the shorthand declaration above it and makes for (occasionally) more concise code.

_x000D_
_x000D_
/* prefixes omitted for brevity */_x000D_
.box {_x000D_
    height: 100px;_x000D_
    width: 100px;_x000D_
    background: red;_x000D_
    box-shadow: red 0 0 5px 1px;_x000D_
    transition: all 500ms ease;_x000D_
    /*note: not transitioning width */_x000D_
    transition-property: height, background, box-shadow;_x000D_
}_x000D_
_x000D_
.box:hover {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  box-shadow: blue 0 0 10px 3px;_x000D_
  background: blue;_x000D_
}
_x000D_
<p>Hover box for demo</p>_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

Demo

What's the difference between "Write-Host", "Write-Output", or "[console]::WriteLine"?

Write-Output should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen. The pipeline will eventually write it to out-default if nothing else uses it first.

Write-Host should be used when you want to do the opposite.

[console]::WriteLine is essentially what Write-Host is doing behind the scenes.

Run this demonstration code and examine the result.

function Test-Output {
    Write-Output "Hello World"
}

function Test-Output2 {
    Write-Host "Hello World" -foreground Green
}

function Receive-Output {
    process { Write-Host $_ -foreground Yellow }
}

#Output piped to another function, not displayed in first.
Test-Output | Receive-Output

#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output 

#Pipeline sends to Out-Default at the end.
Test-Output 

You'll need to enclose the concatenation operation in parentheses, so that PowerShell processes the concatenation before tokenizing the parameter list for Write-Host, or use string interpolation

write-host ("count=" + $count)
# or
write-host "count=$count"

BTW - Watch this video of Jeffrey Snover explaining how the pipeline works. Back when I started learning PowerShell I found this to be the most useful explanation of how the pipeline works.

Load RSA public key from file

Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/

   import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;

    public class Demo {

        public static final String PRIVATE_KEY="/home/user/private.der";
        public static final String PUBLIC_KEY="/home/user/public.der";

        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
            //get the private key
            File file = new File(PRIVATE_KEY);
            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);

            byte[] keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
            System.out.println("Exponent :" + privKey.getPrivateExponent());
            System.out.println("Modulus" + privKey.getModulus());

            //get the public key
            File file1 = new File(PUBLIC_KEY);
            FileInputStream fis1 = new FileInputStream(file1);
            DataInputStream dis1 = new DataInputStream(fis1);
            byte[] keyBytes1 = new byte[(int) file1.length()];
            dis1.readFully(keyBytes1);
            dis1.close();

            X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
            KeyFactory kf1 = KeyFactory.getInstance("RSA");
            RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);

            System.out.println("Exponent :" + pubKey.getPublicExponent());
            System.out.println("Modulus" + pubKey.getModulus());
        }
    }

Why does GitHub recommend HTTPS over SSH?

GitHub have changed their recommendation several times (example).

It appears that they currently recommend HTTPS because it is the easiest to set up on the widest range of networks and platforms, and by users who are new to all this.

There is no inherent flaw in SSH (if there was they would disable it) -- in the links below, you will see that they still provide details about SSH connections too:

  1. HTTPS is less likely to be blocked by a firewall.

    https://help.github.com/articles/which-remote-url-should-i-use/

    The https:// clone URLs are available on all repositories, public and private. These URLs work everywhere--even if you are behind a firewall or proxy.

  2. An HTTPS connection allows credential.helper to cache your password.

    https://help.github.com/articles/set-up-git

    Good to know: The credential helper only works when you clone an HTTPS repo URL. If you use the SSH repo URL instead, SSH keys are used for authentication. While we do not recommend it, if you wish to use this method, check out this guide for help generating and using an SSH key.

SQL Server Escape an Underscore

None of these worked for me in SSIS v18.0, so I would up doing something like this:

WHERE CHARINDEX('_', thingyoursearching) < 1

..where I am trying to ignore strings with an underscore in them. If you want to find things that have an underscore, just flip it around:

WHERE CHARINDEX('_', thingyoursearching) > 0

How to run a class from Jar which is not the Main-Class in its Manifest file

Another similar option that I think Nick briefly alluded to in the comments is to create multiple wrapper jars. I haven't tried it, but I think they could be completely empty other than the manifest file, which should specify the main class to load as well as the inclusion of the MyJar.jar to the classpath.

MyJar1.jar\META-INF\MANIFEST.MF

Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir1.MainClass1
Class-Path: MyJar.jar

MyJar2.jar\META-INF\MANIFEST.MF

Manifest-Version: 1.0
Main-Class: com.mycomp.myproj.dir2.MainClass2
Class-Path: MyJar.jar

etc. Then just run it with java -jar MyJar2.jar

Postgres DB Size Command

-- Database Size
SELECT pg_size_pretty(pg_database_size('Database Name'));
-- Table Size
SELECT pg_size_pretty(pg_relation_size('table_name'));

HTML SELECT - Change selected option by VALUE using JavaScript

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

How do I register a DLL file on Windows 7 64-bit?

And while doing this, if you get error code 0x80040201, try the solution in DllRegisterServer failed with the error code 0x80040201, but make sure, you open command prompt as Run as Administrator.

The static keyword and its various uses in C++

Variables:

static variables exist for the "lifetime" of the translation unit that it's defined in, and:

  • If it's in a namespace scope (i.e. outside of functions and classes), then it can't be accessed from any other translation unit. This is known as "internal linkage" or "static storage duration". (Don't do this in headers except for constexpr. Anything else, and you end up with a separate variable in each translation unit, which is crazy confusing)
  • If it's a variable in a function, it can't be accessed from outside of the function, just like any other local variable. (this is the local they mentioned)
  • class members have no restricted scope due to static, but can be addressed from the class as well as an instance (like std::string::npos). [Note: you can declare static members in a class, but they should usually still be defined in a translation unit (cpp file), and as such, there's only one per class]

locations as code:

static std::string namespaceScope = "Hello";
void foo() {
    static std::string functionScope= "World";
}
struct A {
   static std::string classScope = "!";
};

Before any function in a translation unit is executed (possibly after main began execution), the variables with static storage duration (namespace scope) in that translation unit will be "constant initialized" (to constexpr where possible, or zero otherwise), and then non-locals are "dynamically initialized" properly in the order they are defined in the translation unit (for things like std::string="HI"; that aren't constexpr). Finally, function-local statics will be initialized the first time execution "reaches" the line where they are declared. All static variables all destroyed in the reverse order of initialization.

The easiest way to get all this right is to make all static variables that are not constexpr initialized into function static locals, which makes sure all of your statics/globals are initialized properly when you try to use them no matter what, thus preventing the static initialization order fiasco.

T& get_global() {
    static T global = initial_value();
    return global;
}

Be careful, because when the spec says namespace-scope variables have "static storage duration" by default, they mean the "lifetime of the translation unit" bit, but that does not mean it can't be accessed outside of the file.

Functions

Significantly more straightforward, static is often used as a class member function, and only very rarely used for a free-standing function.

A static member function differs from a regular member function in that it can be called without an instance of a class, and since it has no instance, it cannot access non-static members of the class. Static variables are useful when you want to have a function for a class that definitely absolutely does not refer to any instance members, or for managing static member variables.

struct A {
    A() {++A_count;}
    A(const A&) {++A_count;}
    A(A&&) {++A_count;}
    ~A() {--A_count;}

    static int get_count() {return A_count;}
private:
    static int A_count;
}

int main() {
    A var;

    int c0 = var.get_count(); //some compilers give a warning, but it's ok.
    int c1 = A::get_count(); //normal way
}

A static free-function means that the function will not be referred to by any other translation unit, and thus the linker can ignore it entirely. This has a small number of purposes:

  • Can be used in a cpp file to guarantee that the function is never used from any other file.
  • Can be put in a header and every file will have it's own copy of the function. Not useful, since inline does pretty much the same thing.
  • Speeds up link time by reducing work
  • Can put a function with the same name in each translation unit, and they can all do different things. For instance, you could put a static void log(const char*) {} in each cpp file, and they could each all log in a different way.

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

Seems that with IIS Express and VS 2015, there's a copy of the applicationHost.config file at $(solutionDir).vs\config\applicationhost.config so you'll need to make changes there. See this link: http://digitaldrummerj.me/iis-express-windows-authentication/

Make sure these lines are changed per below:

<section name="windowsAuthentication" overrideModeDefault="Allow" />
<section name="anonymousAuthentication" overrideModeDefault="Allow" />
<add name="WindowsAuthenticationModule" lockItem="false" />
<add name="AnonymousAuthenticationModule" lockItem="false" />

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

read file in classpath

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class readFile {
    /**
     * feel free to make any modification I have have been here so I feel you
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        File dir = new File(".");// read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }`enter code here`

}

Merging Cells in Excel using C#

This solves the issue in the appropriate way

// Merge a row
            ws.Cell("B2").Value = "Merged Row(1) of Range (B2:D3)";
            ws.Range("B2:D3").Row(1).Merge();

How to read and write xml files?

The above answer only deal with DOM parser (that normally reads the entire file in memory and parse it, what for a big file is a problem), you could use a SAX parser that uses less memory and is faster (anyway that depends on your code).

SAX parser callback some functions when it find a start of element, end of element, attribute, text between elements, etc, so it can parse the document and at the same time you get what you need.

Some example code:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

Ansible: get current target host's IP address

The following snippet will return the public ip of the remote machine and also default ip(i.e: LAN)

This will print ip's in quotes also to avoid confusion in using config files.

_x000D_
_x000D_
>> main.yml_x000D_
_x000D_
---_x000D_
- hosts: localhost_x000D_
  tasks:_x000D_
    - name: ipify_x000D_
      ipify_facts:_x000D_
    - debug: var=hostvars[inventory_hostname]['ipify_public_ip']_x000D_
    - debug: var=hostvars[inventory_hostname]['ansible_default_ipv4']['address']_x000D_
    - name: template_x000D_
      template:_x000D_
        src: debug.j2_x000D_
        dest: /tmp/debug.ansible_x000D_
_x000D_
>> templates/debug.j2_x000D_
_x000D_
public_ip={{ hostvars[inventory_hostname]['ipify_public_ip'] }}_x000D_
public_ip_in_quotes="{{ hostvars[inventory_hostname]['ipify_public_ip'] }}"_x000D_
_x000D_
default_ipv4={{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}_x000D_
default_ipv4_in_quotes="{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"
_x000D_
_x000D_
_x000D_

Using PowerShell to write a file in UTF-8 without the BOM

Change multiple files by extension to UTF-8 without BOM:

$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
foreach($i in ls -recurse -filter "*.java") {
    $MyFile = Get-Content $i.fullname 
    [System.IO.File]::WriteAllLines($i.fullname, $MyFile, $Utf8NoBomEncoding)
}

DB2 Date format

select to_char(current date, 'yyyymmdd') from sysibm.sysdummy1

result: 20160510

Double value to round up in Java

The problem is that you use a localizing formatter that generates locale-specific decimal point, which is "," in your case. But Double.parseDouble() expects non-localized double literal. You could solve your problem by using a locale-specific parsing method or by changing locale of your formatter to something that uses "." as the decimal point. Or even better, avoid unnecessary formatting by using something like this:

double rounded = (double) Math.round(value * 100.0) / 100.0;