Programs & Examples On #Flat

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.

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

Set the space between Elements in Row Flutter

Row(
 children: <Widget>[
  Flexible(
   child: TextFormField()),
  Container(width: 20, height: 20),
  Flexible(
   child: TextFormField())
 ])

This works for me, there are 3 widgets inside row: Flexible, Container, Flexible

Create a button with rounded border

Use StadiumBorder shape

              OutlineButton(
                onPressed: () {},
                child: Text("Follow"),
                borderSide: BorderSide(color: Colors.blue),
                shape: StadiumBorder(),
              )

How to make flutter app responsive according to different screen size?

An Another approach :) easier for flutter web

class SampleView extends StatelessWidget {
@override
Widget build(BuildContext context) {
 return Center(
  child: Container(
    width: 200,
    height: 200,
    color: Responsive().getResponsiveValue(
        forLargeScreen: Colors.red,
        forMediumScreen: Colors.green,
        forShortScreen: Colors.yellow,
        forMobLandScapeMode: Colors.blue,
        context: context),
    // You dodn't need to provide the values for every 
    //parameter(except shortScreen & context)
    // but default its provide the value as ShortScreen for Larger and 
    //mediumScreen
    ),
   );
 }
}



 // utility 
          class Responsive {
            // function reponsible for providing value according to screensize
            getResponsiveValue(
                {dynamic forShortScreen,
                dynamic forMediumScreen,
                dynamic forLargeScreen,
                dynamic forMobLandScapeMode,
                BuildContext context}) {

              if (isLargeScreen(context)) {

                return forLargeScreen ?? forShortScreen;
              } else if (isMediumScreen(context)) {

                return forMediumScreen ?? forShortScreen;
              } 
           else if (isSmallScreen(context) && isLandScapeMode(context)) {

                return forMobLandScapeMode ?? forShortScreen;
              } else {
                return forShortScreen;
              }
            }
          
            isLandScapeMode(BuildContext context) {
              if (MediaQuery.of(context).orientation == Orientation.landscape) {
                return true;
              } else {
                return false;
              }
            }
          
            static bool isLargeScreen(BuildContext context) {
              return getWidth(context) > 1200;
            }
          
            static bool isSmallScreen(BuildContext context) {
              return getWidth(context) < 800;
            }
          
            static bool isMediumScreen(BuildContext context) {
              return getWidth(context) > 800 && getWidth(context) < 1200;
            }
          
            static double getWidth(BuildContext context) {
              return MediaQuery.of(context).size.width;
            }
          }

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

I was struggling with this as well. I used an interceptor, it captures the response headers, then clone the headers(since headers are immutable objects) and then sends the modified headers. https://angular.io/guide/http#intercepting-requests-and-responses

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

As addition of good answers, You don't have to use [FromForm] to get form data in controller. Framework automatically convert form data to model as you wish. You can implement like following.

[HttpPost]
public async Task<IActionResult> Submit(MyModel model)
{
    //...
}

Android Room - simple select query - Cannot access database on the main thread

In my opinion the right thing to do is to delegate the query to an IO thread using RxJava.

I have an example of a solution to an equivalent problem I've just encountered.

((ProgressBar) view.findViewById(R.id.progressBar_home)).setVisibility(View.VISIBLE);//Always good to set some good feedback
        Completable.fromAction(() -> {
            //Creating view model requires DB access
            homeViewModel = new ViewModelProvider(this, factory).get(HomeViewModel.class);
        }).subscribeOn(Schedulers.io())//The DB access executes on a non-main-thread thread
        .observeOn(AndroidSchedulers.mainThread())//Upon completion of the DB-involved execution, the continuation runs on the main thread
        .subscribe(
                () ->
                {
                    mAdapter = new MyAdapter(homeViewModel.getExams());
                    recyclerView.setAdapter(mAdapter);
                    ((ProgressBar) view.findViewById(R.id.progressBar_home)).setVisibility(View.INVISIBLE);
                },
                error -> error.printStackTrace()
        );

And if we want to generalize the solution:

((ProgressBar) view.findViewById(R.id.progressBar_home)).setVisibility(View.VISIBLE);//Always good to set some good feedback
        Completable.fromAction(() -> {
            someTaskThatTakesTooMuchTime();
        }).subscribeOn(Schedulers.io())//The long task executes on a non-main-thread thread
        .observeOn(AndroidSchedulers.mainThread())//Upon completion of the DB-involved execution, the continuation runs on the main thread
        .subscribe(
                () ->
                {
                    taskIWantToDoOnTheMainThreadWhenTheLongTaskIsDone();
                },
                error -> error.printStackTrace()
        );

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

Add this config to your webpack config file when using webpack-dev-server (you can still specify the host as 0.0.0.0).

devServer: {
    disableHostCheck: true,
    host: '0.0.0.0',
    port: 3000
}

How to predict input image using trained model in Keras?

Forwarding the example by @ritiek, I'm a beginner in ML too, maybe this kind of formatting will help see the name instead of just class number.

images = np.vstack([x, y])

prediction = model.predict(images)

print(prediction)

i = 1

for things in prediction:  
    if(things == 0):
        print('%d.It is cancer'%(i))
    else:
        print('%d.Not cancer'%(i))
    i = i + 1

How to re-render flatlist?

For quick and simple solution Try:

  1. set extra data to a boolean value.

    extraData={this.state.refresh}

  2. Toggle the value of boolean state when you want to re-render/refresh list

    this.setState({ 
        refresh: !this.state.refresh
    })
    

What is the role of "Flatten" in Keras?

Flatten make explicit how you serialize a multidimensional tensor (tipically the input one). This allows the mapping between the (flattened) input tensor and the first hidden layer. If the first hidden layer is "dense" each element of the (serialized) input tensor will be connected with each element of the hidden array. If you do not use Flatten, the way the input tensor is mapped onto the first hidden layer would be ambiguous.

Why plt.imshow() doesn't display the image?

If you want to print the picture using imshow() you also execute plt.show()

Model summary in pytorch

You can use

from torchsummary import summary

You can specify device

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

You can create a Network, and if you are using MNIST datasets, then following commands will work and show you summary

model = Network().to(device)
summary(model,(1,28,28))

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

when using the categorical_crossentropy loss, your targets should be in categorical format (e.g. if you have 10 classes, the target for each sample should be a 10-dimensional vector that is all-zeros except for a 1 at the index corresponding to the class of the sample).

Keras, How to get the output of each layer?

You can easily get the outputs of any layer by using: model.layers[index].output

For all layers use this:

from keras import backend as K

inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers]          # all layer outputs
functors = [K.function([inp, K.learning_phase()], [out]) for out in outputs]    # evaluation functions

# Testing
test = np.random.random(input_shape)[np.newaxis,...]
layer_outs = [func([test, 1.]) for func in functors]
print layer_outs

Note: To simulate Dropout use learning_phase as 1. in layer_outs otherwise use 0.

Edit: (based on comments)

K.function creates theano/tensorflow tensor functions which is later used to get the output from the symbolic graph given the input.

Now K.learning_phase() is required as an input as many Keras layers like Dropout/Batchnomalization depend on it to change behavior during training and test time.

So if you remove the dropout layer in your code you can simply use:

from keras import backend as K

inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers]          # all layer outputs
functors = [K.function([inp], [out]) for out in outputs]    # evaluation functions

# Testing
test = np.random.random(input_shape)[np.newaxis,...]
layer_outs = [func([test]) for func in functors]
print layer_outs

Edit 2: More optimized

I just realized that the previous answer is not that optimized as for each function evaluation the data will be transferred CPU->GPU memory and also the tensor calculations needs to be done for the lower layers over-n-over.

Instead this is a much better way as you don't need multiple functions but a single function giving you the list of all outputs:

from keras import backend as K

inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers]          # all layer outputs
functor = K.function([inp, K.learning_phase()], outputs )   # evaluation function

# Testing
test = np.random.random(input_shape)[np.newaxis,...]
layer_outs = functor([test, 1.])
print layer_outs

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

Essentially it means you don't have the index you are trying to reference. For example:

df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)

will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:

df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)

Hope that answers your question!

Type of expression is ambiguous without more context Swift

This can happen if any part of your highlighted method or property is attempting to access a property or method with the incorrect type.

Here is a troubleshooting checklist:

  • Make sure the type of arguments match in the call site and implementation.
  • Make sure the argument names match in the call site and implementation.
  • Make sure the method name matches in the call site and implementation.
  • Make sure the returned value of a property or method matches in the usage and implementation (ie: enumerated())
  • Make sure you don't have a duplicated method with potentially ambiguous types such as with protocols or generics.
  • Make sure the compiler can infer the correct type when using type inference.

A Strategy

  • Try breaking apart your method into a greater number of simpler method/implementations.

For example, lets say you are running compactMap on an array of custom Types. In the closure you are passing to the compactMap method, you initialize and return another custom struct. When you get this error, it is difficult to tell which part of your code is offending.

  • For debugging purposes, you can use a for loop instead of compactMap.
  • instead of passing the arguments, directly, you can assign them to constants in the for loop.

By this point, you may come to a realization, such as, instead of the property you thought you wanted to assign actually had a property on it that had the actual value you wanted to pass.

Changing background color of selected item in recyclerview

If you use kotlin, it's really simple.

In your RecyclerAdapter class

userV.invalidateRecycler()

holder.card_User.setCardBackgroundColor(Color.parseColor("#3eb1ae").withAlpha(60))

In your fragment or Activity

 override fun invalidateRecycler() {
    if (v1.recyclerCompanies.childCount > 0) {
        v1.recyclerCompanies.childrenRecursiveSequence().iterator().forEach { card ->
            if (card is CardView) {
                card.setCardBackgroundColor(Color.WHITE)
            }
        }
    }
}

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

Using Moshi:

When building your Retrofit Service add .asLenient() to your MoshiConverterFactory. You don't need a ScalarsConverter. It should look something like this:

return Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ENDPOINT)
                .addConverterFactory(MoshiConverterFactory.create().asLenient())
                .build()
                .create(UserService::class.java)

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

http post - how to send Authorization header?

If you are like me, and starring at your angular/ionic typescript, which looks like..

  getPdf(endpoint: string): Observable<Blob> {
    let url = this.url + '/' + endpoint;
    let token = this.msal.accessToken;
    console.log(token);
    return this.http.post<Blob>(url, {
      headers: new HttpHeaders(
        {
          'Access-Control-Allow-Origin': 'https://localhost:5100',
          'Access-Control-Allow-Methods': 'POST',
          'Content-Type': 'application/pdf',
          'Authorization': 'Bearer ' + token,
          'Accept': '*/*',
        }),
        //responseType: ResponseContentType.Blob,
      });
  }

And while you are setting options but can't seem to figure why they aren't anywhere..

Well.. if you were like me and started this post from a copy/paste of a get, then...

Change to:

  getPdf(endpoint: string): Observable<Blob> {
    let url = this.url + '/' + endpoint;
    let token = this.msal.accessToken;
    console.log(token);
    return this.http.post<Blob>(url, null, { //  <-----  notice the null  *****
      headers: new HttpHeaders(
        {
          'Authorization': 'Bearer ' + token,
          'Accept': '*/*',
        }),
        //responseType: ResponseContentType.Blob,
      });
  }

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

Add Favicon with React and Webpack

For future googlers: You can also use copy-webpack-plugin and add this to webpack's production config:

plugins: [
  new CopyWebpackPlugin({ 
    patterns: [ 
     // relative path is from src
     { from: './static/favicon.ico' }, // <- your path to favicon
    ]
 })
]

Django values_list vs values

values()

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable.

values_list()

Returns a QuerySet that returns list of tuples, rather than model instances, when used as an iterable.

distinct()

distinct are used to eliminate the duplicate elements.

Example:

>>> list(Article.objects.values_list('id', flat=True)) # flat=True will remove the tuples and return the list   
[1, 2, 3, 4, 5, 6]

>>> list(Article.objects.values('id'))
[{'id':1}, {'id':2}, {'id':3}, {'id':4}, {'id':5}, {'id':6}]

How do you use youtube-dl to download live streams (that are live)?

There is no need to pass anything to ffmpeg you can just grab the desired format, in this example, it was the "95" format.

So once you know that it is the 95, you just type:

youtube-dl -f 95  https://www.youtube.com/watch\?v\=6aXR-SL5L2o

that is to say:

youtube-dl -f <format number> <url>

It will begin generating on the working directory a <somename>.<probably mp4>.part which is the partially downloaded file, let it go and just press <Ctrl-C> to stop the capture.

The file will still be named <something>.part, rename it to <whatever>.mp4 and there it is...

The ffmpeg code:

ffmpeg -i $(youtube-dl -f <format number> -g <url>) -copy <file_name>.ts

also worked for me, but sound and video got out of sync, using just youtube-dl seemed to yield a better result although it too uses ffmpeg.

The downside of this approach is that you cannot watch the video while downloading, well you can open yet another FF or Chrome, but it seems that mplayer cannot process the video output till youtube-dl/ffmpeg are running.

Keras model.summary() result - Understanding the # of Parameters

The number of parameters is 7850 because with every hidden unit you have 784 input weights and one weight of connection with bias. This means that every hidden unit gives you 785 parameters. You have 10 units so it sums up to 7850.

The role of this additional bias term is really important. It significantly increases the capacity of your model. You can read details e.g. here Role of Bias in Neural Networks.

How to set menu to Toolbar in Android

You can achieve this by two methods

  1. Using XML
  2. Using java

Using XML Add this attribute to toolbar XML app:menu = "menu_name"

Using java By overriding onCreateOptionMenu(Menu menu)

public class MainActivity extends AppCompatActivity { 

  private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
}
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.demo_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }
}

for more details or implementating click on the menu go through this article https://bedevelopers.tech/android-toolbar-implementation-using-android-studio/

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

I solved it by interchanging the arguments, I was using

export default connect(mapDispatchToProps, mapStateToProps)(Checkbox)

which is wrong. The mapStateToProps has to be the first argument:

export default connect(mapStateToProps, mapDispatchToProps)(Checkbox)

It sounds obvious now, but might help someone.

Python reshape list to ndim array

You can specify the interpretation order of the axes using the order parameter:

np.reshape(arr, (2, -1), order='F')

android: data binding error: cannot find symbol class

You need to declare and pass the binding in the activity layout, not in the included layout.

Example from the documentation:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:bind="http://schemas.android.com/apk/res-auto">
   <data>
       <variable name="user" type="com.example.User"/>
   </data>
   <LinearLayout
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <include layout="@layout/name"
           bind:user="@{user}"/>
       <include layout="@layout/contact"
           bind:user="@{user}"/>
  </LinearLayout>
</layout>

Here, there must be a user variable in both the name.xml and contact.xml layout files.

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

Update October 2018

If you are still uncertain about Front-end dev, you can take a quick look into an excellent resource here.

https://github.com/kamranahmedse/developer-roadmap

Update June 2018

Learning modern JavaScript is tough if you haven’t been there since the beginning. If you are the newcomer, remember to check this excellent written to have a better overview.

https://medium.com/the-node-js-collection/modern-javascript-explained-for-dinosaurs-f695e9747b70

Update July 2017

Recently I found a comprehensive guide from Grab team about how to approach front-end development in 2017. You can check it out as below.

https://github.com/grab/front-end-guide


I've been also searching for this quite some time since there are a lot of tools out there and each of them benefits us in a different aspect. The community is divided across tools like Browserify, Webpack, jspm, Grunt and Gulp. You might also hear about Yeoman or Slush. That’s not a problem, it’s just confusing for everyone trying to understand a clear path forward.

Anyway, I would like to contribute something.

Table Of Content

  • Table Of Content
  • 1. Package Manager
    • NPM
    • Bower
    • Difference between Bower and NPM
    • Yarn
    • jspm
  • 2. Module Loader/Bundling
    • RequireJS
    • Browserify
    • Webpack
    • SystemJS
  • 3. Task runner
    • Grunt
    • Gulp
  • 4. Scaffolding tools
    • Slush and Yeoman

1. Package Manager

Package managers simplify installing and updating project dependencies, which are libraries such as: jQuery, Bootstrap, etc - everything that is used on your site and isn't written by you.

Browsing all the library websites, downloading and unpacking the archives, copying files into the projects — all of this is replaced with a few commands in the terminal.

NPM

It stands for: Node JS package manager helps you to manage all the libraries your software relies on. You would define your needs in a file called package.json and run npm install in the command line... then BANG, your packages are downloaded and ready to use. It could be used both for front-end and back-end libraries.

Bower

For front-end package management, the concept is the same with NPM. All your libraries are stored in a file named bower.json and then run bower install in the command line.

Bower is recommended their user to migrate over to npm or yarn. Please be careful

Difference between Bower and NPM

The biggest difference between Bower and NPM is that NPM does nested dependency tree while Bower requires a flat dependency tree as below.

Quoting from What is the difference between Bower and npm?

NPM

project root
[node_modules] // default directory for dependencies
 -> dependency A
 -> dependency B
    [node_modules]
    -> dependency A

 -> dependency C
    [node_modules]
    -> dependency B
      [node_modules]
       -> dependency A
    -> dependency D

Bower

project root
[bower_components] // default directory for dependencies
 -> dependency A
 -> dependency B // needs A
 -> dependency C // needs B and D
 -> dependency D

There are some updates on npm 3 Duplication and Deduplication, please open the doc for more detail.

Yarn

A new package manager for JavaScript published by Facebook recently with some more advantages compared to NPM. And with Yarn, you still can use both NPMand Bower registry to fetch the package. If you've installed a package before, yarn creates a cached copy which facilitates offline package installs.

jspm

JSPM is a package manager for the SystemJS universal module loader, built on top of the dynamic ES6 module loader. It is not an entirely new package manager with its own set of rules, rather it works on top of existing package sources. Out of the box, it works with GitHub and npm. As most of the Bower based packages are based on GitHub, we can install those packages using jspm as well. It has a registry that lists most of the commonly used front-end packages for easier installation.

See the different between Bower and jspm: Package Manager: Bower vs jspm


2. Module Loader/Bundling

Most projects of any scale will have their code split between several files. You can just include each file with an individual <script> tag, however, <script> establishes a new HTTP connection, and for small files – which is a goal of modularity – the time to set up the connection can take significantly longer than transferring the data. While the scripts are downloading, no content can be changed on the page.

  • The problem of download time can largely be solved by concatenating a group of simple modules into a single file and minifying it.

E.g

<head>
    <title>Wagon</title>
    <script src=“build/wagon-bundle.js”></script>
</head>
  • The performance comes at the expense of flexibility though. If your modules have inter-dependency, this lack of flexibility may be a showstopper.

E.g

<head>
    <title>Skateboard</title>
    <script src=“connectors/axle.js”></script>
    <script src=“frames/board.js”></script>
    <!-- skateboard-wheel and ball-bearing both depend on abstract-rolling-thing -->
    <script src=“rolling-things/abstract-rolling-thing.js”></script>
    <script src=“rolling-things/wheels/skateboard-wheel.js”></script>
    <!-- but if skateboard-wheel also depends on ball-bearing -->
    <!-- then having this script tag here could cause a problem -->
    <script src=“rolling-things/ball-bearing.js”></script>
    <!-- connect wheels to axle and axle to frame -->
    <script src=“vehicles/skateboard/our-sk8bd-init.js”></script>
</head>

Computers can do that better than you can, and that is why you should use a tool to automatically bundle everything into a single file.

Then we heard about RequireJS, Browserify, Webpack and SystemJS

RequireJS

It is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Node.

E.g: myModule.js

// package/lib is a dependency we require
define(["package/lib"], function (lib) {
  // behavior for our module
  function foo() {
    lib.log("hello world!");
  }

  // export (expose) foo to other modules as foobar
  return {
    foobar: foo,
  };
});

In main.js, we can import myModule.js as a dependency and use it.

require(["package/myModule"], function(myModule) {
    myModule.foobar();
});

And then in our HTML, we can refer to use with RequireJS.

<script src=“app/require.js” data-main=“main.js” ></script>

Read more about CommonJS and AMD to get understanding easily. Relation between CommonJS, AMD and RequireJS?

Browserify

Set out to allow the use of CommonJS formatted modules in the browser. Consequently, Browserify isn’t as much a module loader as a module bundler: Browserify is entirely a build-time tool, producing a bundle of code that can then be loaded client-side.

Start with a build machine that has node & npm installed, and get the package:

npm install -g –save-dev browserify

Write your modules in CommonJS format

//entry-point.js
var foo = require("../foo.js");
console.log(foo(4));

And when happy, issue the command to bundle:

browserify entry-point.js -o bundle-name.js

Browserify recursively finds all dependencies of entry-point and assembles them into a single file:

<script src="”bundle-name.js”"></script>

Webpack

It bundles all of your static assets, including JavaScript, images, CSS, and more, into a single file. It also enables you to process the files through different types of loaders. You could write your JavaScript with CommonJS or AMD modules syntax. It attacks the build problem in a fundamentally more integrated and opinionated manner. In Browserify you use Gulp/Grunt and a long list of transforms and plugins to get the job done. Webpack offers enough power out of the box that you typically don’t need Grunt or Gulp at all.

Basic usage is beyond simple. Install Webpack like Browserify:

npm install -g –save-dev webpack

And pass the command an entry point and an output file:

webpack ./entry-point.js bundle-name.js

SystemJS

It is a module loader that can import modules at run time in any of the popular formats used today (CommonJS, UMD, AMD, ES6). It is built on top of the ES6 module loader polyfill and is smart enough to detect the format being used and handle it appropriately. SystemJS can also transpile ES6 code (with Babel or Traceur) or other languages such as TypeScript and CoffeeScript using plugins.

Want to know what is the node module and why it is not well adapted to in-browser.

More useful article:


Why jspm and SystemJS?

One of the main goals of ES6 modularity is to make it really simple to install and use any Javascript library from anywhere on the Internet (Github, npm, etc.). Only two things are needed:

  • A single command to install the library
  • One single line of code to import the library and use it

So with jspm, you can do it.

  1. Install the library with a command: jspm install jquery
  2. Import the library with a single line of code, no need to external reference inside your HTML file.

display.js

var $ = require('jquery');

$('body').append("I've imported jQuery!");
  1. Then you configure these things within System.config({ ... }) before importing your module. Normally when run jspm init, there will be a file named config.js for this purpose.

  2. To make these scripts run, we need to load system.js and config.js on the HTML page. After that, we will load the display.js file using the SystemJS module loader.

index.html

<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
<script>
  System.import("scripts/display.js");
</script>

Noted: You can also use npm with Webpack as Angular 2 has applied it. Since jspm was developed to integrate with SystemJS and it works on top of the existing npm source, so your answer is up to you.


3. Task runner

Task runners and build tools are primarily command-line tools. Why we need to use them: In one word: automation. The less work you have to do when performing repetitive tasks like minification, compilation, unit testing, linting which previously cost us a lot of times to do with command line or even manually.

Grunt

You can create automation for your development environment to pre-process codes or create build scripts with a config file and it seems very difficult to handle a complex task. Popular in the last few years.

Every task in Grunt is an array of different plugin configurations, that simply get executed one after another, in a strictly independent, and sequential fashion.

grunt.initConfig({
    clean: {
    src: ['build/app.js', 'build/vendor.js']
    },

    copy: {
    files: [{
        src: 'build/app.js',
        dest: 'build/dist/app.js'
    }]
    }

    concat: {
    'build/app.js': ['build/vendors.js', 'build/app.js']
    }

    // ... other task configurations ...

});

grunt.registerTask('build', ['clean', 'bower', 'browserify', 'concat', 'copy']);

Gulp

Automation just like Grunt but instead of configurations, you can write JavaScript with streams like it's a node application. Prefer these days.

This is a Gulp sample task declaration.

//import the necessary gulp plugins
var gulp = require("gulp");
var sass = require("gulp-sass");
var minifyCss = require("gulp-minify-css");
var rename = require("gulp-rename");

//declare the task
gulp.task("sass", function (done) {
  gulp
    .src("./scss/ionic.app.scss")
    .pipe(sass())
    .pipe(gulp.dest("./www/css/"))
    .pipe(
      minifyCss({
        keepSpecialComments: 0,
      })
    )
    .pipe(rename({ extname: ".min.css" }))
    .pipe(gulp.dest("./www/css/"))
    .on("end", done);
});

See more: https://preslav.me/2015/01/06/gulp-vs-grunt-why-one-why-the-other/


4. Scaffolding tools

Slush and Yeoman

You can create starter projects with them. For example, you are planning to build a prototype with HTML and SCSS, then instead of manually create some folder like scss, css, img, fonts. You can just install yeoman and run a simple script. Then everything here for you.

Find more here.

npm install -g yo
npm install --global generator-h5bp
yo h5bp

See more: https://www.quora.com/What-are-the-differences-between-NPM-Bower-Grunt-Gulp-Webpack-Browserify-Slush-Yeoman-and-Express


My answer is not matched with the content of the question but when I'm searching for this knowledge on Google, I always see the question on top so that I decided to answer it in summary. I hope you guys found it helpful.

If you like this post, you can read more on my blog at trungk18.com. Thanks for visiting :)

How to use data-binding with Fragment

Kotlin syntax:

lateinit var binding: MartianDataBinding
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    binding = DataBindingUtil.inflate(inflater, R.layout.martian_data, container, false)
    return binding.root
}

How can I clone a JavaScript object except for one key?

var clone = Object.assign({}, {a: 1, b: 2, c: 3});
delete clone.b;

or if you accept property to be undefined:

var clone = Object.assign({}, {a: 1, b: 2, c: 3}, {b: undefined});

How to add a recyclerView inside another recyclerView

you can use LayoutInflater to inflate your dynamic data as a layout file.

UPDATE : first create a LinearLayout inside your CardView's layout and assign an ID for it. after that create a layout file that you want to inflate. at last in your onBindViewHolder method in your "RAdaper" class. write these codes :

  mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

  view = mInflater.inflate(R.layout.my_list_custom_row, parent, false);

after that you can initialize data and ClickListeners with your RAdapter Data. hope it helps.

this and this may useful :)

How do I install Keras and Theano in Anaconda Python on Windows?

In case you want to train CNN's with the theano backend like the Keras mnist_cnn.py example:

You better use theano bleeding edge version. Otherwise there may occur assertion errors.

  • Run Theano bleeding edge
    pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
  • Run Keras (like 1.0.8 works fine)
    pip install git+git://github.com/fchollet/keras.git

RecyclerView - Get view at particular position

To get specific view from recycler view list OR show error at edittext of recycler view.

private void popupErrorMessageAtPosition(int itemPosition) {

    RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(itemPosition);
    View view = viewHolder.itemView;
    EditText etDesc = (EditText) view.findViewById(R.id.et_description);
    etDesc.setError("Error message here !");
}

What does from __future__ import absolute_import actually do?

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

In particular:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Note that python2 pkg/main2.py has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.

In android how to set navigation drawer header image and name programmatically in class file?

It's and old post, but it's new for me. So, it is straight forward! In this part of the code:

 public boolean onNavigationItemSelected(MenuItem item) {

} , I bound an ImageView to the LinearLayout, which contains the ImageView from the example, listed below. Mind: it's the same code you get when you start a new project, and choose the template "Navigation Drawer Activity":

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />

I gave the LinearLayout and ID, inside nav_header_main.xml (in my case I chose 'navigation_header_container' , so it went this way:

LinearLayout lV = (LinearLayout) findViewById(R.id.navigation_header_container);

    ivCloseDrawer = (ImageView) lV.findViewById(R.id.imageView);
    ivCloseDrawer.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            drawer.closeDrawer(GravityCompat.START);
        }
    });

Note: I have a private ImageView ivCloseDrawer declared at the top, before onCreate (MainActivity).

It worked fine! Hope it helps, Best Regards.

Why do we need to use flatMap?

Here to show equivalent implementation of a flatMap using subscribes.

Without flatMap:

this.searchField.valueChanges.debounceTime(400)
.subscribe(
  term => this.searchService.search(term)
  .subscribe( results => {
      console.log(results);  
      this.result = results;
    }
  );
);

With flatMap:

this.searchField.valueChanges.debounceTime(400)
    .flatMap(term => this.searchService.search(term))
    .subscribe(results => {
      console.log(results);
      this.result = results;
    });

http://plnkr.co/edit/BHGmEcdS5eQGX703eRRE?p=preview

Hope it could help.

Olivier.

CheckBox in RecyclerView keeps on checking different items

public class TagYourDiseaseAdapter extends RecyclerView.Adapter { private ReCyclerViewItemClickListener mRecyclerViewItemClickListener; private Context mContext;

List<Datum> deviceList = Collections.emptyList();

/**
 * Initialize the values
 *
 * @param context : context reference
 * @param devices : data
 */

public TagYourDiseaseAdapter(Context context, List<Datum> devices,
                             ReCyclerViewItemClickListener mreCyclerViewItemClickListener) {
    this.mContext = context;
    this.deviceList = devices;
    this.mRecyclerViewItemClickListener = mreCyclerViewItemClickListener;
}


/**
 * @param parent   : parent ViewPgroup
 * @param viewType : viewType
 * @return ViewHolder
 * <p>
 * Inflate the Views
 * Create the each views and Hold for Reuse
 */
@Override
public TagYourDiseaseAdapter.OrderHistoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tag_disease, parent, false);
    TagYourDiseaseAdapter.OrderHistoryViewHolder myViewHolder = new TagYourDiseaseAdapter.OrderHistoryViewHolder(view);
    return myViewHolder;
}


/**
 * @param holder   :view Holder
 * @param position : position of each Row
 *                 set the values to the views
 */
@Override
public void onBindViewHolder(final TagYourDiseaseAdapter.OrderHistoryViewHolder holder, final int position) {
    Picasso.with(mContext).load(deviceList.get(position).getIconUrl()).into(holder.document);
    holder.name.setText(deviceList.get(position).getDiseaseName());

    holder.radioButton.setOnCheckedChangeListener(null);
    holder.radioButton.setChecked(deviceList.get(position).isChecked());

    //if true, your checkbox will be selected, else unselected
    //holder.radioButton.setChecked(objIncome.isSelected());

    holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            deviceList.get(position).setChecked(isChecked);
        }
    });


}

@Override
public int getItemCount() {
    return deviceList.size();
}


/**
 * Create The view First Time and hold for reuse
 * View Holder for Create and Hold the view for ReUse the views instead of create again
 * Initialize the views
 */

public class OrderHistoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    ImageView document;
    TextView name;
    CheckBox radioButton;

    public OrderHistoryViewHolder(View itemView) {
        super(itemView);
        document = itemView.findViewById(R.id.img_tag);
        name = itemView.findViewById(R.id.text_tag_name);
        radioButton = itemView.findViewById(R.id.rdBtn_tag_disease);
        radioButton.setOnClickListener(this);
        //this.setIsRecyclable(false);
    }


    @Override
    public void onClick(View view) {
        mRecyclerViewItemClickListener.onItemClickListener(this.getAdapterPosition(), view);
    }
}

}

Android: Unable to add window. Permission denied for this window type

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT);

    params.gravity = Gravity.START | Gravity.TOP;
    params.x = left;
    params.y = top;
    windowManager.addView(view, params);

} else {
    WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT);


    params.gravity = Gravity.START | Gravity.TOP;
    params.x = left;
    params.y = top;
    windowManager.addView(view, params);
}

How to get a context in a recycler view adapter

First globally declare

Context mContext;

pass context with the constructor, by modifying it.

public FeedAdapter(List<Post> myDataset, Context context) {
    mDataset = myDataset;
    this.mContext = context;
}

then use the mContext whereever you need it

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

If you are using CentOS linux system the Maven local repositary will be:

/root/.m2/repository/

You can remove .m2 and build your maven project in dev tool will fix the issue.

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

another reason this problem happens is when you call these methods with wrong indexes (indexes which there has NOT happened insert or remove in them)

-notifyItemRangeRemoved

-notifyItemRemoved

-notifyItemRangeInserted

-notifyItemInserted

check indexe parameters to these methods and make sure they are precise and correct.

How to update RecyclerView Adapter Data?

This is a general answer for future visitors. The various ways to update the adapter data are explained. The process includes two main steps every time:

  1. Update the data set
  2. Notify the adapter of the change

#Insert single item

Add "Pig" at index 2.

Insert single item
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);

#Insert multiple items

Insert three more animals at index 2.

Insert multiple items
ArrayList<String> items = new ArrayList<>();
items.add("Pig");
items.add("Chicken");
items.add("Dog");
int insertIndex = 2;
data.addAll(insertIndex, items);
adapter.notifyItemRangeInserted(insertIndex, items.size());

#Remove a single item

Remove "Pig" from the list.

Remove single item
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);

#Remove multiple items

Remove "Camel" and "Sheep" from the list.

Remove multiple items
int startIndex = 2; // inclusive
int endIndex = 4;   // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);

#Remove all items

Clear the whole list.

Remove all items
data.clear();
adapter.notifyDataSetChanged();

#Replace old list with the new list

Clear the old list then add a new one.

Replace old list with new list
// clear old list
data.clear();

// add new list
ArrayList<String> newList = new ArrayList<>();
newList.add("Lion");
newList.add("Wolf");
newList.add("Bear");
data.addAll(newList);

// notify adapter
adapter.notifyDataSetChanged();

The adapter has a reference to data, so it is important that I didn't set data to a new object. Instead, I cleared the old items from data and then added the new ones.

#Update single item

Change the "Sheep" item so that it says "I like sheep."

Update single item
String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);

#Move single item

Move "Sheep" from position 3 to position 1.

Move single item
int fromPosition = 3;
int toPosition = 1;

// update data array
String item = data.get(fromPosition);
data.remove(fromPosition);
data.add(toPosition, item);

// notify adapter
adapter.notifyItemMoved(fromPosition, toPosition);

#Code

Here is the project code for your reference. The RecyclerView Adapter code can be found at this answer.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    List<String> data;
    MyRecyclerViewAdapter adapter;

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

        // data to populate the RecyclerView with
        data = new ArrayList<>();
        data.add("Horse");
        data.add("Cow");
        data.add("Camel");
        data.add("Sheep");
        data.add("Goat");

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvAnimals);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
                layoutManager.getOrientation());
        recyclerView.addItemDecoration(dividerItemDecoration);
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }

    public void onButtonClick(View view) {
        insertSingleItem();
    }

    private void insertSingleItem() {
        String item = "Pig";
        int insertIndex = 2;
        data.add(insertIndex, item);
        adapter.notifyItemInserted(insertIndex);
    }

    private void insertMultipleItems() {
        ArrayList<String> items = new ArrayList<>();
        items.add("Pig");
        items.add("Chicken");
        items.add("Dog");
        int insertIndex = 2;
        data.addAll(insertIndex, items);
        adapter.notifyItemRangeInserted(insertIndex, items.size());
    }

    private void removeSingleItem() {
        int removeIndex = 2;
        data.remove(removeIndex);
        adapter.notifyItemRemoved(removeIndex);
    }

    private void removeMultipleItems() {
        int startIndex = 2; // inclusive
        int endIndex = 4;   // exclusive
        int count = endIndex - startIndex; // 2 items will be removed
        data.subList(startIndex, endIndex).clear();
        adapter.notifyItemRangeRemoved(startIndex, count);
    }

    private void removeAllItems() {
        data.clear();
        adapter.notifyDataSetChanged();
    }

    private void replaceOldListWithNewList() {
        // clear old list
        data.clear();

        // add new list
        ArrayList<String> newList = new ArrayList<>();
        newList.add("Lion");
        newList.add("Wolf");
        newList.add("Bear");
        data.addAll(newList);

        // notify adapter
        adapter.notifyDataSetChanged();
    }

    private void updateSingleItem() {
        String newValue = "I like sheep.";
        int updateIndex = 3;
        data.set(updateIndex, newValue);
        adapter.notifyItemChanged(updateIndex);
    }

    private void moveSingleItem() {
        int fromPosition = 3;
        int toPosition = 1;

        // update data array
        String item = data.get(fromPosition);
        data.remove(fromPosition);
        data.add(toPosition, item);

        // notify adapter
        adapter.notifyItemMoved(fromPosition, toPosition);
    }
}

#Notes

  • If you use notifyDataSetChanged(), then no animation will be performed. This can also be an expensive operation, so it is not recommended to use notifyDataSetChanged() if you are only updating a single item or a range of items.
  • Check out DiffUtil if you are making large or complex changes to a list.

#Further study

Java 8 - Difference between Optional.flatMap and Optional.map

Note:- below is the illustration of map and flatmap function, otherwise Optional is primarily designed to be used as a return type only.

As you already may know Optional is a kind of container which may or may not contain a single object, so it can be used wherever you anticipate a null value(You may never see NPE if use Optional properly). For example if you have a method which expects a person object which may be nullable you may want to write the method something like this:

void doSome(Optional<Person> person){
  /*and here you want to retrieve some property phone out of person
    you may write something like this:
  */
  Optional<String> phone = person.map((p)->p.getPhone());
  phone.ifPresent((ph)->dial(ph));
}
class Person{
  private String phone;
  //setter, getters
}

Here you have returned a String type which is automatically wrapped in an Optional type.

If person class looked like this, i.e. phone is also Optional

class Person{
  private Optional<String> phone;
  //setter,getter
}

In this case invoking map function will wrap the returned value in Optional and yield something like:

Optional<Optional<String>> 
//And you may want Optional<String> instead, here comes flatMap

void doSome(Optional<Person> person){
  Optional<String> phone = person.flatMap((p)->p.getPhone());
  phone.ifPresent((ph)->dial(ph));
}

PS; Never call get method (if you need to) on an Optional without checking it with isPresent() unless you can't live without NullPointerExceptions.

Error inflating class android.support.design.widget.NavigationView

Make sure your drawables for the menu are in the correct folder, mine where put in drawablev21 hence this caused a nullpointer to the resource.

Fixed it buy moving my icons to drawables folder

How to filter a RecyclerView with a SearchView

Recyclerview with searchview and clicklistener

Add an interface in your adapter.

public interface SelectedUser{

    void selectedUser(UserModel userModel);

}

implement the interface in your mainactivity and override the method. @Override public void selectedUser(UserModel userModel) {

    startActivity(new Intent(MainActivity.this, SelectedUserActivity.class).putExtra("data",userModel));



}

Full tutorial and source code: Recyclerview with searchview and onclicklistener

How get data from material-ui TextField, DropDownMenu components?

Here's the simplest solution i came up with, we get the value of the input created by material-ui textField :

      create(e) {
        e.preventDefault();
        let name = this.refs.name.input.value;
        alert(name);
      }

      constructor(){
        super();
        this.create = this.create.bind(this);
      }

      render() {
        return (
              <form>
                <TextField ref="name" hintText="" floatingLabelText="Your name" /><br/>
                <RaisedButton label="Create" onClick={this.create} primary={true} />
              </form>
        )}

hope this helps.

Java finished with non-zero exit value 2 - Android Gradle

If you want to see what exactly is causing the error, try building your project via gradle terminal, like this ./gradlew assembleDebug --stacktrace --debug . I've seen the following error in my case com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

This happened when I was trying to entegrate Google Maps to my project. To fix it, I simply checked libraries I was including

compile 'com.google.android.gms:play-services:9.8.0'

I simply changed it to

compile 'com.google.android.gms:play-services-maps:9.8.0'

and problem was gone

Manage toolbar's navigation and back button from fragment in android

I have head around lots of solutions and none of them works perfectly. I've used variation of solutions available in my project which is here as below. Please use this code inside class where you are initialising toolbar and drawer layout.

getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(false);
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);// show back button
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onBackPressed();
                    }
                });
            } else {
                //show hamburger
                drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(true);
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                drawerFragment.mDrawerToggle.syncState();
                toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        drawerFragment.mDrawerLayout.openDrawer(GravityCompat.START);
                    }
                });
            }
        }
    });

How to open a different activity on recyclerView item onclick

iconView = (ImageView) itemLayoutView .findViewById(R.id.iconId);

        itemLayoutView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(v.getContext(), SecondPage.class);
                v.getContext().startActivity(intent);
                Toast.makeText(v.getContext(), "os version is: " + feed.getTitle(), Toast.LENGTH_SHORT).show();
            }
        });

How to remove button shadow (android)

A simpler way to do is adding this tag to your button:

android:stateListAnimator="@null"

though it requires API level 21 or more..

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

How do I access previous promise results in a .then() chain?

I am not going to use this pattern in my own code since I'm not a big fan of using global variables. However, in a pinch it will work.

User is a promisified Mongoose model.

var globalVar = '';

User.findAsync({}).then(function(users){
  globalVar = users;
}).then(function(){
  console.log(globalVar);
});

How can I change default dialog button text color in android 5

Here is how you do it: Simple way

// Initializing a new alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.message);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        doAction();
    }
});
builder.setNegativeButton(R.string.cancel, null);

// Create the alert dialog and change Buttons colour
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface arg0) {
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.red));
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.blue));
        //dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(getResources().getColor(R.color.black));
    }
});
dialog.show();

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

The problem is the tv.setText(text). The variable tv is probably null and you call the setText method on that null, which you can't. My guess that the problem is on the findViewById method, but it's not here, so I can't tell more, without the code.

Add a new item to recyclerview programmatically?

First add your item to mItems and then use:

mAdapter.notifyItemInserted(mItems.size() - 1);

this method is better than using:

mAdapter.notifyDataSetChanged();

in performance.

Cannot resolve method 'getSupportFragmentManager ( )' inside Fragment

Replace getSupportFragmentManager() with getFragmentManager() if you are working in api 21. OR If your app supports versions of Android older than 3.0, be sure you've set up your Android project with the support library as described in Setting Up a Project to Use a Library and use getSupportFragmentManager() this time.

How to use SearchView in Toolbar Android

If you want to add it directly in the toolbar.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="Search"
            android:layout_centerHorizontal="true" />

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

Android: remove left margin from actionbar's custom layout

If you check the documentation of toolbar, by default it has style defined and there is an item contentInsetStart.

<item name="contentInsetStart">16dp</item>

If you want to override this padding then it can be done in two ways.

1.Override the style and add your own style with contentInsetStart and contentInsetEnd values

<style name="MyActionBar" parent="Widget.AppCompat.ActionBar">
    <item name="contentInsetStart">0dp</item>
    <item name="contentInsetEnd">0dp</item>
</style>

2.In XML you can directly define the contentInsetStart and contentInsetEnd values

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    android:layout_height="?attr/actionBarSize">

    <!--Add your views here-->

</androidx.appcompat.widget.Toolbar>

How to load local file in sc.textFile, instead of HDFS

You do not have to use sc.textFile(...) to convert local files into dataframes. One of options is, to read a local file line by line and then transform it into Spark Dataset. Here is an example for Windows machine in Java:

StructType schemata = DataTypes.createStructType(
            new StructField[]{
                    createStructField("COL1", StringType, false),
                    createStructField("COL2", StringType, false),
                    ...
            }
    );

String separator = ";";
String filePath = "C:\\work\\myProj\\myFile.csv";
SparkContext sparkContext = new SparkContext(new SparkConf().setAppName("MyApp").setMaster("local"));
JavaSparkContext jsc = new JavaSparkContext (sparkContext );
SQLContext sqlContext = SQLContext.getOrCreate(sparkContext );

List<String[]> result = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
    String line;
    while ((line = br.readLine()) != null) {
      String[] vals = line.split(separator);
      result.add(vals);
    }
 } catch (Exception ex) {
       System.out.println(ex.getMessage());
       throw new RuntimeException(ex);
  }
  JavaRDD<String[]> jRdd = jsc.parallelize(result);
  JavaRDD<Row> jRowRdd = jRdd .map(RowFactory::create);
  Dataset<Row> data = sqlContext.createDataFrame(jRowRdd, schemata);

Now you can use dataframe data in your code.

Java 8 stream map on entry set

Here is a shorter solution by AbacusUtil

Stream.of(input).toMap(e -> e.getKey().substring(subLength), 
                       e -> AttributeType.GetByName(e.getValue()));

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);

Unable to add window -- token null is not valid; is your activity running?

If you're using getApplicationContext() as Context in Activity for the dialog like this

Dialog dialog = new Dialog(getApplicationContext());

then use YourActivityName.this

Dialog dialog = new Dialog(YourActivityName.this);

How to add buttons like refresh and search in ToolBar in Android?

Try to do this:

getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);

and if you made your custom toolbar (which i presume you did) then you can use the simplest way possible to do this:

toolbarTitle = (TextView)findViewById(R.id.toolbar_title);
toolbarSubTitle = (TextView)findViewById(R.id.toolbar_subtitle);
toolbarTitle.setText("Title");
toolbarSubTitle.setText("Subtitle");

Same goes for any other views you put in your toolbar. Hope it helps.

What's the difference between map() and flatMap() methods in Java 8?

Map:- This method takes one Function as an argument and returns a new stream consisting of the results generated by applying the passed function to all the elements of the stream.

Let's imagine, I have a list of integer values ( 1,2,3,4,5 ) and one function interface whose logic is square of the passed integer. ( e -> e * e ).

List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> newList = intList.stream().map( e -> e * e ).collect(Collectors.toList());

System.out.println(newList);

output:-

[1, 4, 9, 16, 25]

As you can see, an output is a new stream whose values are square of values of the input stream.

[1, 2, 3, 4, 5] -> apply e -> e * e -> [ 1*1, 2*2, 3*3, 4*4, 5*5 ] -> [1, 4, 9, 16, 25 ]

http://codedestine.com/java-8-stream-map-method/

FlatMap :- This method takes one Function as an argument, this function accepts one parameter T as an input argument and returns one stream of parameter R as a return value. When this function is applied to each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method.

Let's image, I have a list of student objects, where each student can opt for multiple subjects.

List<Student> studentList = new ArrayList<Student>();

  studentList.add(new Student("Robert","5st grade", Arrays.asList(new String[]{"history","math","geography"})));
  studentList.add(new Student("Martin","8st grade", Arrays.asList(new String[]{"economics","biology"})));
  studentList.add(new Student("Robert","9st grade", Arrays.asList(new String[]{"science","math"})));

  Set<Student> courses = studentList.stream().flatMap( e -> e.getCourse().stream()).collect(Collectors.toSet());

  System.out.println(courses);

output:-

[economics, biology, geography, science, history, math]

As you can see, an output is a new stream whose values are a collection of all the elements of the streams return by each element of the input stream.

[ S1 , S2 , S3 ] -> [ {"history","math","geography"}, {"economics","biology"}, {"science","math"} ] -> take unique subjects -> [economics, biology, geography, science, history, math]

http://codedestine.com/java-8-stream-flatmap-method/

How do I get the position selected in a RecyclerView?

@Override
public void onClick(View v) {
     int pos = getAdapterPosition();
}

Simple as that, on ViewHolder

Nested Recycler view height doesn't wrap its content

Based on the work of Denis Nek, it works well if the sum of item's widths is smaller than the size of the container. other than that, it will make the recyclerview non scrollable and only will show subset of the data.

to solve this problem, i modified the solution alittle so that it choose the min of the provided size and calculated size. see below:

package com.linkdev.gafi.adapters;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.linkdev.gafi.R;

public class MyLinearLayoutManager extends LinearLayoutManager {

    public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
        super(context, orientation, reverseLayout);
        this.c = context;
    }


    private Context c;
    private int[] mMeasuredDimension = new int[2];


    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                          int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);



        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            measureScrapChild(recycler, i,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);

            if (getOrientation() == HORIZONTAL) {
                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }


        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        int widthDesired = Math.min(widthSize,width);
        setMeasuredDimension(widthDesired, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        View view = recycler.getViewForPosition(position);
        if (view != null) {
            RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight(), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom(), p.height);
            view.measure(childWidthSpec, childHeightSpec);
            measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
            measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }}

Display a RecyclerView in Fragment

This was asked some time ago now, but based on the answer that @nacho_zona3 provided, and previous experience with fragments, the issue is that the views have not been created by the time you are trying to find them with the findViewById() method in onCreate() to fix this, move the following code:

// 1. get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);

// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(this));

// this is data fro recycler view
ItemData itemsData[] = { new ItemData("Indigo",R.drawable.circle),
        new ItemData("Red",R.drawable.color_ic_launcher),
        new ItemData("Blue",R.drawable.indigo),
        new ItemData("Green",R.drawable.circle),
        new ItemData("Amber",R.drawable.color_ic_launcher),
        new ItemData("Deep Orange",R.drawable.indigo)};


// 3. create an adapter
MyAdapter mAdapter = new MyAdapter(itemsData);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
// 5. set item animator to DefaultAnimator
recyclerView.setItemAnimator(new DefaultItemAnimator()); 

to your fragment's onCreateView() call. A small amount of refactoring is required because all variables and methods called from this method have to be static. The final code should look like:

 public class ColorsFragment extends Fragment {

     public ColorsFragment() {}

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

         View rootView = inflater.inflate(R.layout.fragment_colors, container, false);
         // 1. get a reference to recyclerView
         RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.list);

         // 2. set layoutManger
         recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

         // this is data fro recycler view
         ItemData itemsData[] = {
             new ItemData("Indigo", R.drawable.circle),
                 new ItemData("Red", R.drawable.color_ic_launcher),
                 new ItemData("Blue", R.drawable.indigo),
                 new ItemData("Green", R.drawable.circle),
                 new ItemData("Amber", R.drawable.color_ic_launcher),
                 new ItemData("Deep Orange", R.drawable.indigo)
         };


         // 3. create an adapter
         MyAdapter mAdapter = new MyAdapter(itemsData);
         // 4. set adapter
         recyclerView.setAdapter(mAdapter);
         // 5. set item animator to DefaultAnimator
         recyclerView.setItemAnimator(new DefaultItemAnimator());

         return rootView;
     }
 }

So the main thing here is that anywhere you call findViewById() you will need to use rootView.findViewById()

Cannot catch toolbar home button click event

I changed the DrawerLayout a bit to get the events and be able to consume and event, such as if you want to use the actionToggle as back if you are in detail view:

public class ListenableDrawerLayout extends DrawerLayout {

    private OnToggleButtonClickedListener mOnToggleButtonClickedListener;
    private boolean mManualCall;

    public ListenableDrawerLayout(Context context) {
        super(context);
    }

    public ListenableDrawerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ListenableDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * Sets the listener for the toggle button
     *
     * @param mOnToggleButtonClickedListener
     */
    public void setOnToggleButtonClickedListener(OnToggleButtonClickedListener mOnToggleButtonClickedListener) {
        this.mOnToggleButtonClickedListener = mOnToggleButtonClickedListener;
    }

    /**
     * Opens the navigation drawer manually from code<br>
     * <b>NOTE: </b>Use this function instead of the normal openDrawer method
     *
     * @param drawerView
     */
    public void openDrawerManual(View drawerView) {
        mManualCall = true;
        openDrawer(drawerView);
    }

    /**
     * Closes the navigation drawer manually from code<br>
     * <b>NOTE: </b>Use this function instead of the normal closeDrawer method
     *
     * @param drawerView
     */
    public void closeDrawerManual(View drawerView) {
        mManualCall = true;
        closeDrawer(drawerView);
    }


    @Override
    public void openDrawer(View drawerView) {

        // Check for listener and for not manual open
        if (!mManualCall && mOnToggleButtonClickedListener != null) {

            // Notify the listener and behave on its reaction
            if (mOnToggleButtonClickedListener.toggleOpenDrawer()) {
                return;
            }

        }
        // Manual call done
        mManualCall = false;

        // Let the drawer layout to its stuff
        super.openDrawer(drawerView);
    }

    @Override
    public void closeDrawer(View drawerView) {

        // Check for listener and for not manual close
        if (!mManualCall && mOnToggleButtonClickedListener != null) {

            // Notify the listener and behave on its reaction
            if (mOnToggleButtonClickedListener.toggleCloseDrawer()) {
                return;
            }

        }
        // Manual call done
        mManualCall = false;

        // Let the drawer layout to its stuff
        super.closeDrawer(drawerView);
    }

    /**
     * Interface for toggle button callbacks
     */
    public static interface OnToggleButtonClickedListener {

        /**
         * The ActionBarDrawerToggle has been pressed in order to open the drawer
         *
         * @return true if we want to consume the event, false if we want the normal behaviour
         */
        public boolean toggleOpenDrawer();

        /**
         * The ActionBarDrawerToggle has been pressed in order to close the drawer
         *
         * @return true if we want to consume the event, false if we want the normal behaviour
         */
        public boolean toggleCloseDrawer();
    }

}

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

I had the same error. Eventually I got this notice that a plugin was out of date:

error dialog

After I updated, the problem went away.

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

I had issues including toolbar in a RelativeLayout, try with LinearLayout. If you want to overlay the toolbar, try with:

 <RelativeLayout>

    <LinearLayout>
      --INCLUDE tOOLBAR--
    </LinearLayout>

    <Button></Button>

 </RelativeLayout>

I don't understand why but it works for me.

Is there an addHeaderView equivalent for RecyclerView?

you can create addHeaderView and use

adapter.addHeaderView(View).

This code build the addHeaderView for more then one header. the headers should have:

android:layout_height="wrap_content"

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_ITEM = -1;
    public class MyViewSHolder extends RecyclerView.ViewHolder {
        public MyViewSHolder (View view) {
            super(view);
        }
        // put you code. for example:
        View mView;
        ...
    }

    public class ViewHeader extends RecyclerView.ViewHolder {
        public ViewHeader(View view) {
            super(view);
        }
    }

    private List<View> mHeaderViews = new ArrayList<>();
    public void addHeaderView(View headerView) {
        mHeaderViews.add(headerView);
    }

    @Override
    public int getItemCount() {
       return ... + mHeaderViews.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderViews.size() > position) {
            return position;
        }

        return TYPE_ITEM;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType != TYPE_ITEM) {
            //inflate your layout and pass it to view holder
            return new ViewHeader(mHeaderViews.get(viewType));
        }
        ...
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int basePosition1) {
        if (holder instanceof ViewHeader) {
            return;
        }
        int basePosition = basePosition1 -  mHeaderViews.size();
        ...
    }
}

Android 5.0 - Add header/footer to a RecyclerView

I know I come late, but only recently I was able to implement such "addHeader" to the Adapter. In my FlexibleAdapter project you can call setHeader on a Sectionable item, then you call showAllHeaders. If you need only 1 header then the first item should have the header. If you delete this item, then the header is automatically linked to the next one.

Unfortunately footers are not covered (yet).

The FlexibleAdapter allows you to do much more than create headers/sections. You really should have a look: https://github.com/davideas/FlexibleAdapter.

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

Insted of

drawer.setDrawerListener(toggle);

You can use

drawer.addDrawerListener(toggle);

How to change option menu icon in the action bar?

1) Declare menu in your class.

private Menu menu;

2) In onCreateOptionsMenu do the following :

public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
    getMenuInflater().inflate(R.menu.menu_orders_screen, menu);
    return true;
}   

3) In onOptionsItemSelected, get the item and do the changes as required(icon, text, colour, background)

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_search) {
        return true;
    }
    if (id == R.id.ventor_status) {
        return true;
    }
    if (id == R.id.action_settings_online) {
        menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.history_converted));
        menu.getItem(1).setTitle("Online");
        return true;
    }
    if (id == R.id.action_settings_offline) {
        menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.cross));
        menu.getItem(1).setTitle("Offline");
        return true;
    }

    return super.onOptionsItemSelected(item);
}

Note:
If you have 3 menu items :
menu.getItem(0) = 1 item,
menu.getItem(1) = 2 iteam,
menu.getItem(2) = 3 item

Based on this make the changes accordingly as per your requirement.

How to create RecyclerView with multiple view type?

Yes, it is possible. In your adapter getItemViewType Layout like this ....

  public class MultiViewTypeAdapter extends RecyclerView.Adapter {

        private ArrayList<Model>dataSet;
        Context mContext;
        int total_types;
        MediaPlayer mPlayer;
        private boolean fabStateVolume = false;

        public static class TextTypeViewHolder extends RecyclerView.ViewHolder {

            TextView txtType;
            CardView cardView;

            public TextTypeViewHolder(View itemView) {
                super(itemView);

                this.txtType = (TextView) itemView.findViewById(R.id.type);
                this.cardView = (CardView) itemView.findViewById(R.id.card_view);
            }
        }

        public static class ImageTypeViewHolder extends RecyclerView.ViewHolder {

            TextView txtType;
            ImageView image;

            public ImageTypeViewHolder(View itemView) {
                super(itemView);

                this.txtType = (TextView) itemView.findViewById(R.id.type);
                this.image = (ImageView) itemView.findViewById(R.id.background);
            }
        }

        public static class AudioTypeViewHolder extends RecyclerView.ViewHolder {

            TextView txtType;
            FloatingActionButton fab;

            public AudioTypeViewHolder(View itemView) {
                super(itemView);

                this.txtType = (TextView) itemView.findViewById(R.id.type);
                this.fab = (FloatingActionButton) itemView.findViewById(R.id.fab);
            }
        }

        public MultiViewTypeAdapter(ArrayList<Model>data, Context context) {
            this.dataSet = data;
            this.mContext = context;
            total_types = dataSet.size();
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view;
            switch (viewType) {
                case Model.TEXT_TYPE:
                    view = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_type, parent, false);
                    return new TextTypeViewHolder(view);
                case Model.IMAGE_TYPE:
                    view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_type, parent, false);
                    return new ImageTypeViewHolder(view);
                case Model.AUDIO_TYPE:
                    view = LayoutInflater.from(parent.getContext()).inflate(R.layout.audio_type, parent, false);
                    return new AudioTypeViewHolder(view);
            }
            return null;
        }

        @Override
        public int getItemViewType(int position) {

            switch (dataSet.get(position).type) {
                case 0:
                    return Model.TEXT_TYPE;
                case 1:
                    return Model.IMAGE_TYPE;
                case 2:
                    return Model.AUDIO_TYPE;
                default:
                    return -1;
            }
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int listPosition) {

            Model object = dataSet.get(listPosition);
            if (object != null) {
                switch (object.type) {
                    case Model.TEXT_TYPE:
                        ((TextTypeViewHolder) holder).txtType.setText(object.text);

                        break;
                    case Model.IMAGE_TYPE:
                        ((ImageTypeViewHolder) holder).txtType.setText(object.text);
                        ((ImageTypeViewHolder) holder).image.setImageResource(object.data);
                        break;
                    case Model.AUDIO_TYPE:

                        ((AudioTypeViewHolder) holder).txtType.setText(object.text);

                }
            }
        }

        @Override
        public int getItemCount() {
            return dataSet.size();
        }
    }

for reference link : https://www.journaldev.com/12372/android-recyclerview-example

Android RecyclerView addition & removal of items

The problem I had was I was removing an item from the list that was no longer associated with the adapter to make sure you are modifying the correct adapter you can implement a method like this in your adapter:

public void removeItemAtPosition(int position) {
    items.remove(position);
}

And call it in your fragment or activity like this:

adapter.removeItemAtPosition(position);

Recyclerview and handling different type of row inflation

You can just return ItemViewType and use it. See below code:

@Override
public int getItemViewType(int position) {

    Message item = messageList.get(position);
    // return my message layout
    if(item.getUsername() == Message.userEnum.I)
        return R.layout.item_message_me;
    else
        return R.layout.item_message; // return other message layout
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(viewType, viewGroup, false);
    return new ViewHolder(view);
}

pip is not able to install packages correctly: Permission denied error

Set up a virtualenv:

% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py 
% sudo python /tmp/get-pip.py

These commands install pip into the global site-packages directory.

% sudo pip install virtualenv

and ditto for virtualenv:

% mkdir -p ~/.virtualenvs

I like my virtualenvs under one tree in my home directory called .virtualenvs

% virtualenv ~/.virtualenvs/lxmltest

Creates a virtualenv.

% . ~/.virtualenvs/lxmltest/bin/activate

Removes the need to specify the full path to pip/python in this virtualenv.

% pip install lxml

Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest and start again from a new virtualenv.

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

For AWS S3, setting the Cross-origin resource sharing (CORS) to the following worked for me:

[
    {
        "AllowedHeaders": [
            "Authorization"
        ],
        "AllowedMethods": [
            "GET",
            "HEAD"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

I was receiving the same error. You need to go increase the column length while importing the data for particular column. Choose a data source >> Advanced >> increase the column from default 50 to 200 or more.

It worked for me!

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

We see this a lot with OAuth2 integrations. We provide API services to our Customers, and they'll naively try to put their private key into an AJAX call. This is really poor security. And well-coded API Gateways, backends for frontend, and other such proxies, do not allow this. You should get this error.

I will quote @aspillers comment and change a single word: "Access-Control-Allow-Origin is a header sent in a server response which indicates IF the client is allowed to see the contents of a result".

ISSUE: The problem is that a developer is trying to include their private key inside a client-side (browser) JavaScript request. They will get an error, and this is because they are exposing their client secret.

SOLUTION: Have the JavaScript web application talk to a backend service that holds the client secret securely. That backend service can authenticate the web app to the OAuth2 provider, and get an access token. Then the web application can make the AJAX call.

View RDD contents in Python Spark?

By latest document, you can use rdd.collect().foreach(println) on the driver to display all, but it may cause memory issues on the driver, best is to use rdd.take(desired_number)

https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html

To print all elements on the driver, one can use the collect() method to first bring the RDD to the driver node thus: rdd.collect().foreach(println). This can cause the driver to run out of memory, though, because collect() fetches the entire RDD to a single machine; if you only need to print a few elements of the RDD, a safer approach is to use the take(): rdd.take(100).foreach(println).

How do I copy directories recursively with gulp?

The following works without flattening the folder structure:

gulp.src(['input/folder/**/*']).pipe(gulp.dest('output/folder'));

The '**/*' is the important part. That expression is a glob which is a powerful file selection tool. For example, for copying only .js files use: 'input/folder/**/*.js'

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.

@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {

    @ApiObjectField(description = "The code which is to be verified.")
    @NotBlank(message = "mandatory")
    private final String code;

    @ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
    private final String maskedMobileNumber;

    public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
        this.code = code;
        this.maskedMobileNumber = maskedMobileNumber;
    }

    public String getcode() {
        return code;
    }

    public String getMaskedMobileNumber() {
        return maskedMobileNumber;
    }
}

The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been

public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
    this.code = code;
    this.maskedMobileNumber = maskedMobileNumber;
}

How to implement OnFragmentInteractionListener

Just an addendum:

OnFragmentInteractionListener handle communication between Activity and Fragment using an interface (OnFragmentInteractionListener) and is created by default by Android Studio, but if you dont need to communicate with your activity, you can just get ride of it.

The goal is that you can attach your fragment to multiple activities and still reuse the same communication approach (Every activity could have its own OnFragmentInteractionListener for each fragment).

But and if im sure my fragment will be attached to only one type of activity and i want to communicate with that activity?

Then, if you dont want to use OnFragmentInteractionListener because of its verbosity, you can access your activity methods using:

((MyActivityClass) getActivity()).someMethod()

Custom Listview Adapter with filter Android

Just an update.

If the ticked answer is working fine for you but it shows nothing when the search text is empty. Here is the solution:

private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        
        String filterString = constraint.toString().toLowerCase();
        
        FilterResults results = new FilterResults();

        if(constraint.length() == 0)
        {
            results.count = originalData.size();
            results.values = originalData;
        }else {

        
        final List<String> list = originalData;

        int count = list.size();
        final ArrayList<String> nlist = new ArrayList<String>(count);

        String filterableString ;
        
        for (int i = 0; i < count; i++) {
            filterableString = list.get(i);
            if (filterableString.toLowerCase().contains(filterString)) {
                nlist.add(filterableString);
            }
        }
        
        results.values = nlist;
        results.count = nlist.size();
     }
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        filteredData = (ArrayList<String>) results.values;
        notifyDataSetChanged();
      }

   }

For any query comment below

notifyDataSetChanged not working on RecyclerView

Although it is a bit strange, but the notifyDataSetChanged does not really work without setting new values to adapter. So, you should do:

array = getNewItems();                    
((MyAdapter) mAdapter).setValues(array);  // pass the new list to adapter !!!
mAdapter.notifyDataSetChanged();       

This has worked for me.

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

Adding local .aar files to Gradle build using "flatDirs" is not working

The easiest way now is to add it as a module

enter image description here

This will create a new module containing the aar file, so you just need to include that module as a dependency afterwards

How do I convert csv file to rdd

Another alternative is to use the mapPartitionsWithIndex method as you'll get the partition index number and a list of all lines within that partition. Partition 0 and line 0 will be be the header

val rows = sc.textFile(path)
  .mapPartitionsWithIndex({ (index: Int, rows: Iterator[String]) => 
    val results = new ArrayBuffer[(String, Int)]

    var first = true
    while (rows.hasNext) {
      // check for first line
      if (index == 0 && first) {
        first = false
        rows.next // skip the first row
      } else {
        results += rows.next
      }
    }

    results.toIterator
}, true)

rows.flatMap { row => row.split(",") }

How to change link color (Bootstrap)

using bootstrap 4 and SCSS check out this link here for full details

https://getbootstrap.com/docs/4.0/getting-started/theming/

in a nutshell...

open up lib/bootstrap/scss/_navbar.scss and find the statements that create these variables

  .navbar-nav {
    .nav-link {
      color: $navbar-light-color;

      @include hover-focus() {
        color: $navbar-light-hover-color;
      }

      &.disabled {
        color: $navbar-light-disabled-color;
      }
    }

so now you need to override

$navbar-light-color
$navbar-light-hover-color
$navbar-light-disabled-color

create a new scss file _localVariables.scss and add the following (with your colors)

$navbar-light-color : #520b71
$navbar-light-hover-color: #F3EFE6;
$navbar-light-disabled-color: #F3EFE6;

@import "../lib/bootstrap/scss/functions";
@import "../lib/bootstrap/scss/variables";
@import "../lib/bootstrap/scss/mixins/_breakpoints";

and on your other scss pages just add

@import "_localVariables";

instead of

@import "../lib/bootstrap/scss/functions";
@import "../lib/bootstrap/scss/variables";
@import "../lib/bootstrap/scss/mixins/_breakpoints";

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

You can mark source directory as a source root like so:

  • Right-click on source directory
  • Mark Directory As --> Source Root
  • File --> Invalidate Caches / Restart... -> Invalidate and Restart

How to move from one fragment to another fragment on click of an ImageView in Android?

purple.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Fragment fragment = new tasks();
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
});

you write the above code...there we are replacing R.id.content_frame with our fragment. hope this helps you

Hide/Show Action Bar Option Menu Item for different fragments

Try this...

You don't need to override onCreateOptionsMenu() in your Fragment class again. Menu items visibility can be changed by overriding onPrepareOptionsMenu() method available in Fragment class.

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
    menu.findItem(R.id.action_search).setVisible(false);
    super.onPrepareOptionsMenu(menu);
}

Postgres - Transpose Rows to Columns

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
   $$
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:

Detailed explanation and instructions here:

And in particular, for "extra columns":

The special difficulties here are:

  • The lack of key names.
    -> We substitute with row_number() in a subquery.

  • The varying number of emails.
    -> We limit to a max. of three in the outer SELECT
    and use crosstab() with two parameters, providing a list of possible keys.

Pay attention to NULLS LAST in the ORDER BY.

When do you use map vs flatMap in RxJava?

In some cases you might end up having chain of observables, wherein your observable would return another observable. 'flatmap' kind of unwraps the second observable which is buried in the first one and let you directly access the data second observable is spitting out while subscribing.

Using Java 8's Optional with Stream::flatMap

I'm adding this second answer based on a proposed edit by user srborlongan to my other answer. I think the technique proposed was interesting, but it wasn't really suitable as an edit to my answer. Others agreed and the proposed edit was voted down. (I wasn't one of the voters.) The technique has merit, though. It would have been best if srborlongan had posted his/her own answer. This hasn't happened yet, and I didn't want the technique to be lost in the mists of the StackOverflow rejected edit history, so I decided to surface it as a separate answer myself.

Basically the technique is to use some of the Optional methods in a clever way to avoid having to use a ternary operator (? :) or an if/else statement.

My inline example would be rewritten this way:

Optional<Other> result =
    things.stream()
          .map(this::resolve)
          .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
          .findFirst();

An my example that uses a helper method would be rewritten this way:

/**
 * Turns an Optional<T> into a Stream<T> of length zero or one depending upon
 * whether a value is present.
 */
static <T> Stream<T> streamopt(Optional<T> opt) {
    return opt.map(Stream::of)
              .orElseGet(Stream::empty);
}

Optional<Other> result =
    things.stream()
          .flatMap(t -> streamopt(resolve(t)))
          .findFirst();

COMMENTARY

Let's compare the original vs modified versions directly:

// original
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())

// modified
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))

The original is a straightforward if workmanlike approach: we get an Optional<Other>; if it has a value, we return a stream containing that value, and if it has no value, we return an empty stream. Pretty simple and easy to explain.

The modification is clever and has the advantage that it avoids conditionals. (I know that some people dislike the ternary operator. If misused it can indeed make code hard to understand.) However, sometimes things can be too clever. The modified code also starts off with an Optional<Other>. Then it calls Optional.map which is defined as follows:

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

The map(Stream::of) call returns an Optional<Stream<Other>>. If a value was present in the input Optional, the returned Optional contains a Stream that contains the single Other result. But if the value was not present, the result is an empty Optional.

Next, the call to orElseGet(Stream::empty) returns a value of type Stream<Other>. If its input value is present, it gets the value, which is the single-element Stream<Other>. Otherwise (if the input value is absent) it returns an empty Stream<Other>. So the result is correct, the same as the original conditional code.

In the comments discussing on my answer, regarding the rejected edit, I had described this technique as "more concise but also more obscure". I stand by this. It took me a while to figure out what it was doing, and it also took me a while to write up the above description of what it was doing. The key subtlety is the transformation from Optional<Other> to Optional<Stream<Other>>. Once you grok this it makes sense, but it wasn't obvious to me.

I'll acknowledge, though, that things that are initially obscure can become idiomatic over time. It might be that this technique ends up being the best way in practice, at least until Optional.stream gets added (if it ever does).

UPDATE: Optional.stream has been added to JDK 9.

AlertDialog.Builder with custom layout and EditText; cannot access view

editText is a part of alertDialog layout so Just access editText with reference of alertDialog

EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);

Update:

Because in code line dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));

inflater is Null.

update your code like below, and try to understand the each code line

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);

EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

Update 2:

As you are using View object created by Inflater to update UI components else you can directly use setView(int layourResId) method of AlertDialog.Builder class, which is available from API 21 and onwards.

Aren't promises just callbacks?

Yes, Promises are asynchronous callbacks. They can't do anything that callbacks can't do, and you face the same problems with asynchrony as with plain callbacks.

However, Promises are more than just callbacks. They are a very mighty abstraction, allow cleaner and better, functional code with less error-prone boilerplate.

So what's the main idea?

Promises are objects representing the result of a single (asynchronous) computation. They resolve to that result only once. There's a few things what this means:

Promises implement an observer pattern:

  • You don't need to know the callbacks that will use the value before the task completes.
  • Instead of expecting callbacks as arguments to your functions, you can easily return a Promise object
  • The promise will store the value, and you can transparently add a callback whenever you want. It will be called when the result is available. "Transparency" implies that when you have a promise and add a callback to it, it doesn't make a difference to your code whether the result has arrived yet - the API and contracts are the same, simplifying caching/memoisation a lot.
  • You can add multiple callbacks easily

Promises are chainable (monadic, if you want):

  • If you need to transform the value that a promise represents, you map a transform function over the promise and get back a new promise that represents the transformed result. You cannot synchronously get the value to use it somehow, but you can easily lift the transformation in the promise context. No boilerplate callbacks.
  • If you want to chain two asynchronous tasks, you can use the .then() method. It will take a callback to be called with the first result, and returns a promise for the result of the promise that the callback returns.

Sounds complicated? Time for a code example.

var p1 = api1(); // returning a promise
var p3 = p1.then(function(api1Result) {
    var p2 = api2(); // returning a promise
    return p2; // The result of p2 …
}); // … becomes the result of p3

// So it does not make a difference whether you write
api1().then(function(api1Result) {
    return api2().then(console.log)
})
// or the flattened version
api1().then(function(api1Result) {
    return api2();
}).then(console.log)

Flattening does not come magically, but you can easily do it. For your heavily nested example, the (near) equivalent would be

api1().then(api2).then(api3).then(/* do-work-callback */);

If seeing the code of these methods helps understanding, here's a most basic promise lib in a few lines.

What's the big fuss about promises?

The Promise abstraction allows much better composability of functions. For example, next to then for chaining, the all function creates a promise for the combined result of multiple parallel-waiting promises.

Last but not least Promises come with integrated error handling. The result of the computation might be that either the promise is fulfilled with a value, or it is rejected with a reason. All the composition functions handle this automatically and propagate errors in promise chains, so that you don't need to care about it explicitly everywhere - in contrast to a plain-callback implementation. In the end, you can add a dedicated error callback for all occurred exceptions.

Not to mention having to convert things to promises.

That's quite trivial actually with good promise libraries, see How do I convert an existing callback API to promises?

Create listview in fragment android

Instead:

public class PhotosFragment extends Fragment

You can use:

public class PhotosFragment extends ListFragment

It change the methods

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ArrayList<ListviewContactItem> listContact = GetlistContact();
        setAdapter(new ListviewContactAdapter(getActivity(), listContact));
    }

onActivityCreated is void and you didn't need to return a view like in onCreateView

You can see an example here

Android - save/restore fragment state

Android fragment has some advantages and some disadvantages. The most disadvantage of the fragment is that when you want to use a fragment you create it ones. When you use it, onCreateView of the fragment is called for each time. If you want to keep state of the components in the fragment you must save fragment state and yout must load its state in the next shown. This make fragment view a bit slow and weird.

I have found a solution and I have used this solution: "Everything is great. Every body can try".

When first time onCreateView is being run, create view as a global variable. When second time you call this fragment onCreateView is called again you can return this global view. The fragment component state will be kept.

View view;

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    setActionBar(null);
    if (view != null) {
        if ((ViewGroup)view.getParent() != null)
            ((ViewGroup)view.getParent()).removeView(view);
        return view; 
    }
    view = inflater.inflate(R.layout.mylayout, container, false);
}

Java 8 Streams FlatMap method example

Given this:

  public class SalesTerritory
    {
        private String territoryName;
        private Set<String> geographicExtents;

        public SalesTerritory( String territoryName, Set<String> zipCodes )
        {
            this.territoryName = territoryName;
            this.geographicExtents = zipCodes;
        }

        public String getTerritoryName()
        {
            return territoryName;
        }

        public void setTerritoryName( String territoryName )
        {
            this.territoryName = territoryName;
        }

        public Set<String> getGeographicExtents()
        {
            return geographicExtents != null ? Collections.unmodifiableSet( geographicExtents ) : Collections.emptySet();
        }

        public void setGeographicExtents( Set<String> geographicExtents )
        {
            this.geographicExtents = new HashSet<>( geographicExtents );
        }

        @Override
        public int hashCode()
        {
            int hash = 7;
            hash = 53 * hash + Objects.hashCode( this.territoryName );
            return hash;
        }

        @Override
        public boolean equals( Object obj )
        {
            if ( this == obj ) {
                return true;
            }
            if ( obj == null ) {
                return false;
            }
            if ( getClass() != obj.getClass() ) {
                return false;
            }
            final SalesTerritory other = (SalesTerritory) obj;
            if ( !Objects.equals( this.territoryName, other.territoryName ) ) {
                return false;
            }
            return true;
        }

        @Override
        public String toString()
        {
            return "SalesTerritory{" + "territoryName=" + territoryName + ", geographicExtents=" + geographicExtents + '}';
        }

    }

and this:

public class SalesTerritories
{
    private static final Set<SalesTerritory> territories
        = new HashSet<>(
            Arrays.asList(
                new SalesTerritory[]{
                    new SalesTerritory( "North-East, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Maine", "New Hampshire", "Vermont",
                                                                                    "Rhode Island", "Massachusetts", "Connecticut",
                                                                                    "New York", "New Jersey", "Delaware", "Maryland",
                                                                                    "Eastern Pennsylvania", "District of Columbia" } ) ) ),
                    new SalesTerritory( "Appalachia, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "West-Virgina", "Kentucky",
                                                                                    "Western Pennsylvania" } ) ) ),
                    new SalesTerritory( "South-East, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Virginia", "North Carolina", "South Carolina",
                                                                                    "Georgia", "Florida", "Alabama", "Tennessee",
                                                                                    "Mississippi", "Arkansas", "Louisiana" } ) ) ),
                    new SalesTerritory( "Mid-West, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Ohio", "Michigan", "Wisconsin", "Minnesota",
                                                                                    "Iowa", "Missouri", "Illinois", "Indiana" } ) ) ),
                    new SalesTerritory( "Great Plains, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Oklahoma", "Kansas", "Nebraska",
                                                                                    "South Dakota", "North Dakota",
                                                                                    "Eastern Montana",
                                                                                    "Wyoming", "Colorada" } ) ) ),
                    new SalesTerritory( "Rocky Mountain, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Western Montana", "Idaho", "Utah", "Nevada" } ) ) ),
                    new SalesTerritory( "South-West, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Arizona", "New Mexico", "Texas" } ) ) ),
                    new SalesTerritory( "Pacific North-West, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Washington", "Oregon", "Alaska" } ) ) ),
                    new SalesTerritory( "Pacific South-West, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "California", "Hawaii" } ) ) )
                }
            )
        );

    public static Set<SalesTerritory> getAllTerritories()
    {
        return Collections.unmodifiableSet( territories );
    }

    private SalesTerritories()
    {
    }

}

We can then do this:

System.out.println();
System.out
    .println( "We can use 'flatMap' in combination with the 'AbstractMap.SimpleEntry' class to flatten a hierarchical data-structure to a set of Key/Value pairs..." );
SalesTerritories.getAllTerritories()
    .stream()
    .flatMap( t -> t.getGeographicExtents()
        .stream()
        .map( ge -> new SimpleEntry<>( t.getTerritoryName(), ge ) )
    )
    .map( e -> String.format( "%-30s : %s",
                              e.getKey(),
                              e.getValue() ) )
    .forEach( System.out::println );

What is the difference between map and flatMap and a good use case for each?

Flatmap and Map both transforms the collection.

Difference:

map(func)
Return a new distributed dataset formed by passing each element of the source through a function func.

flatMap(func)
Similar to map, but each input item can be mapped to 0 or more output items (so func should return a Seq rather than a single item).

The transformation function:
map: One element in -> one element out.
flatMap: One element in -> 0 or more elements out (a collection).

Button button = findViewById(R.id.button) always resolves to null in Android Studio

This is because findViewById() searches in the activity_main layout, while the button is located in the fragment's layout fragment_main.

Move that piece of code in the onCreateView() method of the fragment:

//...

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        onButtonClick((Button) view);
    }
});

Notice that now you access it through rootView view:

Button buttonClick = (Button)rootView.findViewById(R.id.button);

otherwise you would get again NullPointerException.

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I'm not sure if I am correct, but from the request header that you post:

Request headers

Accept: Application/json

Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36

Content-Type: application/x-www-form-urlencoded

Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8

it seems like you didn't config your request body to JSON type.

.jar error - could not find or load main class

You can always run this:

java -cp HelloWorld.jar HelloWorld

-cp HelloWorld.jar adds the jar to the classpath, then HelloWorld runs the class you wrote.

To create a runnable jar with a main class with no package, add Class-Path: . to the manifest:

Manifest-Version: 1.0
Class-Path: .
Main-Class: HelloWorld

I would advise using a package to give your class its own namespace. E.g.

package com.stackoverflow.user.blrp;

public class HelloWorld {
    ...
}

Inverse of a matrix using numpy

The I attribute only exists on matrix objects, not ndarrays. You can use numpy.linalg.inv to invert arrays:

inverse = numpy.linalg.inv(x)

Note that the way you're generating matrices, not all of them will be invertible. You will either need to change the way you're generating matrices, or skip the ones that aren't invertible.

try:
    inverse = numpy.linalg.inv(x)
except numpy.linalg.LinAlgError:
    # Not invertible. Skip this one.
    pass
else:
    # continue with what you were doing

Also, if you want to go through all 3x3 matrices with elements drawn from [0, 10), you want the following:

for comb in itertools.product(range(10), repeat=9):

rather than combinations_with_replacement, or you'll skip matrices like

numpy.array([[0, 1, 0],
             [0, 0, 0],
             [0, 0, 0]])

Apache: "AuthType not set!" 500 Error

I think that you have a version 2.4.x of Apache.

Have you sure that you load this 2 modules ? - mod_authn_core - mod_authz_core

LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_core_module modules/mod_authz_core.so

PS : My recommendation for authorization and rights is (by default) :

LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so

Apache Spark: map vs mapPartitions?

Imp. TIP :

Whenever you have heavyweight initialization that should be done once for many RDD elements rather than once per RDD element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), use mapPartitions() instead of map(). mapPartitions() provides for the initialization to be done once per worker task/thread/partition instead of once per RDD data element for example : see below.

val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = partition.map(record => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB 

  connection.close() // close dbconnection here
  newPartition.iterator // create a new iterator
})

Q2. does flatMap behave like map or like mapPartitions?

Yes. please see example 2 of flatmap.. its self explanatory.

Q1. What's the difference between an RDD's map and mapPartitions

map works the function being utilized at a per element level while mapPartitions exercises the function at the partition level.

Example Scenario : if we have 100K elements in a particular RDD partition then we will fire off the function being used by the mapping transformation 100K times when we use map.

Conversely, if we use mapPartitions then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.

There will be performance gain since map works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions).

map

Applies a transformation function on each item of the RDD and returns the result as a new RDD.

Listing Variants

def map[U: ClassTag](f: T => U): RDD[U]

Example :

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
 val b = a.map(_.length)
 val c = a.zip(b)
 c.collect
 res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8)) 

mapPartitions

This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.

preservesPartitioning indicates whether the input function preserves the partitioner, which should be false unless this is a pair RDD and the input function doesn't modify the keys.

Listing Variants

def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]

Example 1

val a = sc.parallelize(1 to 9, 3)
 def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
   var res = List[(T, T)]()
   var pre = iter.next
   while (iter.hasNext)
   {
     val cur = iter.next;
     res .::= (pre, cur)
     pre = cur;
   }
   res.iterator
 }
 a.mapPartitions(myfunc).collect
 res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8)) 

Example 2

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
 def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
   var res = List[Int]()
   while (iter.hasNext) {
     val cur = iter.next;
     res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
   }
   res.iterator
 }
 x.mapPartitions(myfunc).collect
 // some of the number are not outputted at all. This is because the random number generated for it is zero.
 res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10) 

The above program can also be written using flatMap as follows.

Example 2 using flatmap

val x  = sc.parallelize(1 to 10, 3)
 x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect

 res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10) 

Conclusion :

mapPartitions transformation is faster than map since it calls your function once/partition, not once/element..

Further reading : foreach Vs foreachPartitions When to use What?

What are best practices for REST nested resources?

I've tried both design strategies - nested and non-nested endpoints. I've found that:

  1. if the nested resource has a primary key and you don't have its parent primary key, the nested structure requires you to get it, even though the system doesn't actually require it.

  2. nested endpoints typically require redundant endpoints. In other words, you will more often than not, need the additional /employees endpoint so you can get a list of employees across departments. If you have /employees, what exactly does /companies/departments/employees buy you?

  3. nesting endpoints don't evolve as nicely. E.g. you might not need to search for employees now but you might later and if you have a nested structure, you have no choice but to add another endpoint. With a non-nested design, you just add more parameters, which is simpler.

  4. sometimes a resource could have multiple types of parents. Resulting in multiple endpoints all returning the same resource.

  5. redundant endpoints makes the docs harder to write and also makes the api harder to learn.

In short, the non-nested design seems to allow a more flexible and simpler endpoint schema.

Intent from Fragment to Activity

For Kotlin you can use

val myIntent = Intent(activity, your_destination_activity::class.java)
startActivity(myIntent)

Access-Control-Allow-Origin and Angular.js $http

@Swapnil Niwane

I was able to solve this issue by calling an ajax request and formatting the data to 'jsonp'.

$.ajax({
          method: 'GET',
          url: url,
          defaultHeaders: {
              'Content-Type': 'application/json',
              "Access-Control-Allow-Origin": "*",
              'Accept': 'application/json'
           },

          dataType: 'jsonp',

          success: function (response) {
            console.log("success ");
            console.log(response);
          },
          error: function (xhr) {
            console.log("error ");
            console.log(xhr);
          }
});

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I've ran into the same problem. The question here is that play-java-jpa artifact (javaJpa key in the build.sbt file) depends on a different version of the spec (version 2.0 -> "org.hibernate.javax.persistence" % "hibernate-jpa-2.0-api" % "1.0.1.Final").

When you added hibernate-entitymanager 4.3 this brought the newer spec (2.1) and a different factory provider for the entitymanager. Basically you ended up having both jars in the classpath as transitive dependencies.

Edit your build.sbt file like this and it will temporarily fix you problem until play releases a new version of the jpa plugin for the newer api dependency.

libraryDependencies ++= Seq(
javaJdbc,
javaJpa.exclude("org.hibernate.javax.persistence", "hibernate-jpa-2.0-api"),
"org.hibernate" % "hibernate-entitymanager" % "4.3.0.Final"
)

This is for play 2.2.x. In previous versions there were some differences in the build files.

Using Service to run background and create notification

Your error is in UpdaterServiceManager in onCreate and showNotification method.

You are trying to show notification from Service using Activity Context. Whereas Every Service has its own Context, just use the that. You don't need to pass a Service an Activity's Context.I don't see why you need a specific Activity's Context to show Notification.

Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.

You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference

Get the Application Context In Fragment In Android?

You can get the context using getActivity().getApplicationContext();

android.content.res.Resources$NotFoundException: String resource ID #0x0

You can do it. this is a easy way.

txtTopicNo.setText(10+"");

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

With Kotlin have this extension function to read the file return as string.

fun AssetManager.readAssetsFile(fileName : String): String = open(fileName).bufferedReader().use{it.readText()}

Parse the output string using any JSON parser.

How to calculate percentage when old value is ZERO

There is no rate of growth from 0 to any other number. That is to say, there is no percentage of increase from zero to greater than zero and there is no percentage of decrease from zero to less than zero (a negative number). What you have to decide is what to put as an output when this situation happens. Here are two possibilities I am comfortable with:

  1. Any time you have to show a rate of increase from zero, output the infinity symbol (8). That's Alt + 236 on your number pad, in case you're wondering. You could also use negative infinity (-8) for a negative growth rate from zero.
  2. Output a statement such as "[Increase/Decrease] From Zero" or something along those lines.

Unfortunately, if you need the growth rate for further calculations, the above options will not work, but, on the other hand, any number would give your following calculations incorrect data any way so the point is moot. You'd need to update your following calculations to account for this eventuality.

As an aside, the ((New-Old)/Old) function will not work when your new and old values are both zero. You should create an initial check to see if both values are zero and, if they are, output zero percent as the growth rate.

How to change MenuItem icon in ActionBar programmatically

Lalith's answer is correct.

You may also try this approach:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            invalidateOptionsMenu();
        }
    });

 @Override
 public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem settingsItem = menu.findItem(R.id.action_settings);
    // set your desired icon here based on a flag if you like
    settingsItem.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher)); 

    return super.onPrepareOptionsMenu(menu);
 }

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

Are android:name and class: interchangeable?

Presumably, yes. I have only used class, and that seems to be what most of Google's examples use, but I do see where they use android:name in some samples. Unfortunately, there is no formal and complete documentation for fragment.

use

class = "com.fragment.NavigationDrawerFragment"

insted of

android:name="com.fragment.NavigationDrawerFragment"

That seemingly means that program looks "class" attribute first. And on fail looks "name" attribute. So as far as it's true using "class" if more efficient

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

If you want to allow all origins and keep credentials true, this worked for me:

app.use(cors({
  origin: function(origin, callback){
    return callback(null, true);
  },
  optionsSuccessStatus: 200,
  credentials: true
}));

How to change the background color of Action Bar's Option Menu in Android 4.2?

The Action Bar Style Generator, suggested by Sunny, is very useful, but it generates a lot of files, most of which are irrelevant if you only want to change the background colour.

So, I dug deeper into the zip it generates, and tried to narrow down what are the parts that matter, so I can make the minimum amount of changes to my app. Below is what I found out.


In the style generator, the relevant setting is Popup color, which affects "Overflow menu, submenu and spinner panel background".

enter image description here

Go on and generate the zip, but out of all the files generated, you only really need one image, menu_dropdown_panel_example.9.png, which looks something like this:

enter image description here

So, add the different resolution versions of it to res/drawable-*. (And perhaps rename them to menu_dropdown_panel.9.png.)

Then, as an example, in res/values/themes.xml you would have the following, with android:popupMenuStyle and android:popupBackground being the key settings.

<resources>

    <style name="MyAppActionBarTheme" parent="android:Theme.Holo.Light">
        <item name="android:popupMenuStyle">@style/MyApp.PopupMenu</item>
        <item name="android:actionBarStyle">@style/MyApp.ActionBar</item>
    </style>

    <!-- The beef: background color for Action Bar overflow menu -->
    <style name="MyApp.PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
        <item name="android:popupBackground">@drawable/menu_dropdown_panel</item>
    </style>

    <!-- Bonus: if you want to style whole Action Bar, not just the menu -->
    <style name="MyApp.ActionBar" parent="android:Widget.Holo.Light.ActionBar.Solid">
        <!-- Blue background color & black bottom border -->
        <item name="android:background">@drawable/blue_action_bar_background</item>
    </style>   

</resources>

And, of course, in AndroidManifest.xml:

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

What you get with this setup:

enter image description here

Note that I'm using Theme.Holo.Light as the base theme. If you use Theme.Holo (Holo Dark), there's an additional step needed as this answer describes!

Also, if you (like me) wanted to style the whole Action Bar, not just the menu, put something like this in res/drawable/blue_action_bar_background.xml:

<!-- Bonus: if you want to style whole Action Bar, not just the menu -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:color="#FF000000" />
            <solid android:color="#FF2070B0" />                   
        </shape>
    </item>

    <item android:bottom="2dp">
        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:color="#FF2070B0" />
            <solid android:color="#00000000" />
            <padding android:bottom="2dp" />
        </shape>
    </item>

</layer-list>

Works great at least on Android 4.0+ (API level 14+).

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

How to change icon on Google map marker

You have to add the targeted map :

var markers = [
            {
            "title": 'This is title',
            "lat": '-37.801578',
            "lng": '145.060508',
            "map":  map,
            "icon": 'http://google-maps-icons.googlecode.com/files/sailboat-tourism.png',
            "description": 'Vikash Rathee. <strong> This is test Description</strong> <br/><a href="http://www.pricingindia.in/pincode.aspx">Pin Code by 

City</a>'
            }
];

Fastest way to flatten / un-flatten nested JSON objects

Here's a recursive solution for flatten I put together in PowerShell:

#---helper function for ConvertTo-JhcUtilJsonTable
#
function getNodes {
    param (
        [Parameter(Mandatory)]
        [System.Object]
        $job,
        [Parameter(Mandatory)]
        [System.String]
        $path
    )

    $t = $job.GetType()
    $ct = 0
    $h = @{}

    if ($t.Name -eq 'PSCustomObject') {
        foreach ($m in Get-Member -InputObject $job -MemberType NoteProperty) {
            getNodes -job $job.($m.Name) -path ($path + '.' + $m.Name)
        }
        
    }
    elseif ($t.Name -eq 'Object[]') {
        foreach ($o in $job) {
            getNodes -job $o -path ($path + "[$ct]")
            $ct++
        }
    }
    else {
        $h[$path] = $job
        $h
    }
}


#---flattens a JSON document object into a key value table where keys are proper JSON paths corresponding to their value
#
function ConvertTo-JhcUtilJsonTable {
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [System.Object[]]
        $jsonObj
    )

    begin {
        $rootNode = 'root'    
    }
    
    process {
        foreach ($o in $jsonObj) {
            $table = getNodes -job $o -path $rootNode

            # $h = @{}
            $a = @()
            $pat = '^' + $rootNode
            
            foreach ($i in $table) {
                foreach ($k in $i.keys) {
                    # $h[$k -replace $pat, ''] = $i[$k]
                    $a += New-Object -TypeName psobject -Property @{'Key' = $($k -replace $pat, ''); 'Value' = $i[$k]}
                    # $h[$k -replace $pat, ''] = $i[$k]
                }
            }
            # $h
            $a
        }
    }

    end{}
}

Example:

'{"name": "John","Address": {"house": "1234", "Street": "Boogie Ave"}, "pets": [{"Type": "Dog", "Age": 4, "Toys": ["rubberBall", "rope"]},{"Type": "Cat", "Age": 7, "Toys": ["catNip"]}]}' | ConvertFrom-Json | ConvertTo-JhcUtilJsonTable
Key              Value
---              -----
.Address.house   1234
.Address.Street  Boogie Ave
.name            John
.pets[0].Age     4
.pets[0].Toys[0] rubberBall
.pets[0].Toys[1] rope
.pets[0].Type    Dog
.pets[1].Age     7
.pets[1].Toys[0] catNip
.pets[1].Type    Cat

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

Just add this to your Application_OnBeginRequest method (this will enable CORS support globally for your application) and "handle" preflight requests :

var res = HttpContext.Current.Response;
var req = HttpContext.Current.Request;
res.AppendHeader("Access-Control-Allow-Origin", req.Headers["Origin"]);
res.AppendHeader("Access-Control-Allow-Credentials", "true");
res.AppendHeader("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");

// ==== Respond to the OPTIONS verb =====
if (req.HttpMethod == "OPTIONS")
{
    res.StatusCode = 200;
    res.End();
}

* security: be aware that this will enable ajax requests from anywhere to your server (you can instead only allow a comma separated list of Origins/urls if you prefer).

I used current client origin instead of * because this will allow credentials => setting Access-Control-Allow-Credentials to true will enable cross browser session managment

also you need to enable delete and put, patch and options verbs in your webconfig section system.webServer, otherwise IIS will block them :

<handlers>
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

hope this helps

Fix footer to bottom of page

You can use Grid Layout. It is newer than Flexbox, and less supported in browsers.

Check it out:

HTML

<body>
  <div class="content">
    content
  </div>
  <footer class="footer"></footer>
</body>

CSS

html {
  height: 100%;
}

body {
  min-height: 100%;
  display: grid;
  grid-template-rows: 1fr auto;
}   

.footer {
  grid-row-start: 2;
  grid-row-end: 3;
}

Useful Links:

Browser Supoort: Can I Use - Grid Layout

Complete Guide: Grid Laoyut Guid

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

Okay adding to @null's awesome post about using the Asset Catalog.

You may need to do the following to get the App's Icon linked and working for Ad-Hoc distributions / production to be seen in Organiser, Test flight and possibly unknown AppStore locations.


After creating the Asset Catalog, take note of the name of the Launch Images and App Icon names listed in the .xassets in Xcode.

By Default this should be

  • AppIcon
  • LaunchImage

[To see this click on your .xassets folder/icon in Xcode.] (this can be changed, so just take note of this variable for later)


What is created now each build is the following data structures in your .app:

For App Icons:

iPhone

  • AppIcon57x57.png (iPhone non retina) [Notice the Icon name prefix]
  • [email protected] (iPhone retina)

And the same format for each of the other icon resolutions.

iPad

  • AppIcon72x72~ipad.png (iPad non retina)
  • AppIcon72x72@2x~ipad.png (iPad retina)

(For iPad it is slightly different postfix)


Main Problem

Now I noticed that in my Info.plist in Xcode 5.0.1 it automatically attempted and failed to create a key for "Icon files (iOS 5)" after completing the creation of the Asset Catalog.

If it did create a reference successfully / this may have been patched by Apple or just worked, then all you have to do is review the image names to validate the format listed above.

Final Solution:

Add the following key to you main .plist

I suggest you open your main .plist with a external text editor such as TextWrangler rather than in Xcode to copy and paste the following key in.

<key>CFBundleIcons</key>
<dict>
    <key>CFBundlePrimaryIcon</key>
    <dict>
        <key>CFBundleIconFiles</key>
        <array>
            <string>AppIcon57x57.png</string>
            <string>[email protected]</string>
            <string>AppIcon72x72~ipad.png</string>
            <string>AppIcon72x72@2x~ipad.png</string>
        </array>
    </dict>
</dict>

Please Note I have only included my example resolutions, you will need to add them all.


If you want to add this Key in Xcode without an external editor, Use the following:

  • Icon files (iOS 5) - Dictionary
  • Primary Icon - Dictionary
  • Icon files - Array
  • Item 0 - String = AppIcon57x57.png And for each other item / app icon.

Now when you finally archive your project the final .xcarchive payload .plist will now include the above stated icon locations to build and use.

Do not add the following to any .plist: Just an example of what Xcode will now generate for your final payload

<key>IconPaths</key>
<array>
    <string>Applications/Example.app/AppIcon57x57.png</string>
    <string>Applications/Example.app/[email protected]</string>
    <string>Applications/Example.app/AppIcon72x72~ipad.png</string>
    <string>Applications/Example.app/AppIcon72x72@2x~ipad.png</string>
</array>

How to flatten only some dimensions of a numpy array

A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.

e.g. to flatten all but the last two dimensions:

arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)

EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:

arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)

How to add Action bar options menu in Android Fragments

I am late for the answer but I think this is another solution which is not mentioned here so posting.

Step 1: Make a xml of menu which you want to add like I have to add a filter action on my action bar so I have created a xml filter.xml. The main line to notice is android:orderInCategory this will show the action icon at first or last wherever you want to show. One more thing to note down is the value, if the value is less then it will show at first and if value is greater then it will show at last.

filter.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" >


    <item
        android:id="@+id/action_filter"
        android:title="@string/filter"
        android:orderInCategory="10"
        android:icon="@drawable/filter"
        app:showAsAction="ifRoom" />


</menu>

Step 2: In onCreate() method of fragment just put the below line as mentioned, which is responsible for calling back onCreateOptionsMenu(Menu menu, MenuInflater inflater) method just like in an Activity.

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

Step 3: Now add the method onCreateOptionsMenu which will be override as:

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.filter, menu);  // Use filter.xml from step 1
    }

Step 4: Now add onOptionsItemSelected method by which you can implement logic whatever you want to do when you select the added action icon from actionBar:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.action_filter){
            //Do whatever you want to do 
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

Button Listener for button in fragment in android

Try this :

FragmentOne.java

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentOne extends Fragment{

    View rootView;        

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

        rootView = inflater.inflate(R.layout.fragment_one, container, false);


        Button button = (Button) rootView.findViewById(R.id.buttonSayHi);
        button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                onButtonClicked(v);
            }
        });
        return rootView;
    }

  public void onButtonClicked(View view)
  {
          //do your stuff here..           
    final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
    ft.replace(R.id.frameLayoutFragmentContainer, new FragmentTwo(), "NewFragmentTag"); 
    ft.commit(); 

    ft.addToBackStack(null);    
  }
}

check this : click here

Tar a directory, but don't store full absolute paths in the archive

If you want to archive a subdirectory and trim subdirectory path this command will be useful:

tar -cjf site1.bz2 -C /var/www/ site1

Getting the current Fragment instance in the viewpager

In my previous implementation I stored a list of child Fragments to be able to access them later, but this turned out to be a wrong implementation causing huge memory leaks.

I end up using instantiateItem(...) method to get current Fragment:

val currentFragment = adapter?.instantiateItem(viewPager, viewPager.currentItem)

Or to get any other Fragment on position:

val position = 0
val myFirstFragment: MyFragment? = (adapter?.instantiateItem(viewPager, position) as? MyFragment)

From documentation:

Create the page for the given position. The adapter is responsible for adding the view to the container given here, although it only must ensure this is done by the time it returns from finishUpdate(ViewGroup).

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

The Advanced Editor did not resolve my issue, instead I was forced to edit dtsx-file through notepad (or your favorite text/xml editor) and manually replace values in attributes to

length="0" dataType="nText" (I'm using unicode)

Always make a backup of the dtsx-file before you edit in text/xml mode.

Running SQL Server 2008 R2

How to convert Java String into byte[]?

I know I'm a little late tothe party but thisworks pretty neat (our professor gave it to us)

public static byte[] asBytes (String s) {                   
           String tmp;
           byte[] b = new byte[s.length() / 2];
           int i;
           for (i = 0; i < s.length() / 2; i++) {
             tmp = s.substring(i * 2, i * 2 + 2);
             b[i] = (byte)(Integer.parseInt(tmp, 16) & 0xff);
           }
           return b;                                            //return bytes
    }

Android findViewById() in Custom View

If it's fixed layout you can do like that:

public void onClick(View v) {
   ViewGroup parent = (ViewGroup) IdNumber.this.getParent();
   EditText firstName = (EditText) parent.findViewById(R.id.display_name);
   firstName.setText("Some Text");
}

If you want find the EditText in flexible layout, I will help you later. Hope this help.

Play sound on button click android

  • The audio must be placed in the raw folder, if it doesn't exists, create one.
  • The raw folder must be inside the res folder
  • The name mustn't have any - or special characters in it.

On your activity, you need to have a object MediaPlayer, inside the onCreate method or the onclick method, you have to initialize the MediaPlayer, like MediaPlayer.create(this, R.raw.name_of_your_audio_file), then your audio file ir ready to be played with the call for start(), in your case, since you want it to be placed in a button, you'll have to put it inside the onClick method.

Example:

private Button myButton;
private MediaPlayer mp;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myactivity);
        mp = MediaPlayer.create(this, R.raw.gunshot);

        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.start();
            }
        });
}
}

How to implement a ViewPager with different Fragments / Layouts

This is also fine:

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
public class MainActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

    }
}


public class FragmentTab1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
        return rootView;
    }
}

class MyPagerAdapter extends FragmentPagerAdapter{

    public MyPagerAdapter(FragmentManager fragmentManager){
        super(fragmentManager);

    }
    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        switch(position){
            case 0:
                FragmentTab1 fm =   new FragmentTab1();
                return fm;
            case 1: return new FragmentTab2();
            case 2: return new FragmentTab3();
        }
        return null;
    }

    @Override
    public int getCount() {
        return 3;
    }
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/Fragment1" />

</RelativeLayout>

SSIS - Text was truncated or one or more characters had no match in the target code page - Special Characters

If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.

EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character

How to send a correct authorization header for basic authentication

You can include the user and password as part of the URL:

http://user:[email protected]/index.html

see this URL, for more

HTTP Basic Authentication credentials passed in URL and encryption

of course, you'll need the username password, it's not 'Basic hashstring.

hope this helps...

Slide a layout up from bottom of screen

Ok, there are two possible approaches. The simplest - is to use a sliding menu library. It allows creating a bottom sliding menu, it can animate the top container to make bottom visible, it suports both dragging it with your finger, or animating it programmatically via button (StaticDrawer).

Harder way - if you want to use Animations, as was already suggested. With animations you must FIRST change your layouts. So try first to make your layout change to the final state without any animations whatsoever. Because it is very likely that you are not laying out your views properly in RelativeLayout, so even though you show your bottom view, it remains obscured by the top one. Once you achieved proper layout change - all you need to do is to is to remember translations before layout and apply translate animation AFTER layout.

How to change navigation bar color in iOS 7 or 6?

The background color property is ignored on a UINavigationBar, so if you want to adjust the look and feel you either have to use the tintColor or call some of the other methods listed under "Customizing the Bar Appearance" of the UINavigationBar class reference (like setBackgroundImage:forBarMetrics:).

Be aware that the tintColor property works differently in iOS 7, so if you want a consistent look between iOS 7 and prior version using a background image might be your best bet. It's also worth mentioning that you can't configure the background image in the Storyboard, you'll have to create an IBOutlet to your UINavigationBar and change it in viewDidLoad or some other appropriate place.

Get Selected Item Using Checkbox in Listview

You can use model class and use setTag() getTag() methods to keep track which items from listview are checked and which not.

More reference for this : listview with checkbox in android

Source code for model

public class Model {

    private boolean isSelected;
    private String animal;

    public String getAnimal() {
        return animal;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public boolean getSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}

put this in your custom adapter

 holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();

                if(modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

whole code for customAdapter is

public class CustomAdapter  extends BaseAdapter {

    private Context context;
    public static ArrayList<Model> modelArrayList;


    public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {

        this.context = context;
        this.modelArrayList = modelArrayList;

    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }
    @Override
    public int getItemViewType(int position) {

        return position;
    }

    @Override
    public int getCount() {
        return modelArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return modelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lv_item, null, true);

            holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
            holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);

            convertView.setTag(holder);
        }else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }


        holder.checkBox.setText("Checkbox "+position);
        holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());

        holder.checkBox.setChecked(modelArrayList.get(position).getSelected());

        holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();

                if(modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

        return convertView;
    }

    private class ViewHolder {

        protected CheckBox checkBox;
        private TextView tvAnimal;

    }

}

Update Fragment from ViewPager

In your PagerAdapter override getItemPosition

@Override
public int getItemPosition(Object object) {
// POSITION_NONE makes it possible to reload the PagerAdapter
return POSITION_NONE;
}

After that add viewPager.getAdapter().notifyDataSetChanged(); this code like below

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            viewPager.getAdapter().notifyDataSetChanged();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

should work.

Android button background color

This is my way to do custom Button with different color.`

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke android:width="3dp"
        android:color="#80FFFFFF" />

  <corners android:radius="25dp" />

  <gradient android:angle="270"
            android:centerColor="#90150517"
            android:endColor="#90150517"
            android:startColor="#90150517" />
</shape>

This way you set as background.

<Button android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_marginBottom="25dp"
        android:layout_centerInParent="true"
        android:background="@drawable/button"/>

Build tree array from flat array in javascript

also do it with lodashjs(v4.x)

function buildTree(arr){
  var a=_.keyBy(arr, 'id')
  return _
   .chain(arr)
   .groupBy('parentId')
   .forEach(function(v,k){ 
     k!='0' && (a[k].children=(a[k].children||[]).concat(v));
   })
   .result('0')
   .value();
}

Laravel view not found exception

Create the index.blade.php file in the views folder, that should be all

getSupportActionBar() The method getSupportActionBar() is undefined for the type TaskActivity. Why?

If you are already extending from ActionBarActivity and you are trying to get the action bar from a fragment:

ActionBar mActionBar = (ActionBarActivity)getActivity()).getSupportActionBar();

Wampserver icon not going green fully, mysql services not starting up?

Basically this happens when you have not installed pre required software installed on your machine while installing Wampserver you might have got error bellow error at the time of installation.

program can't start because msvcr120.dll is missing OR

program can't start because msvcr120.dll is missing

If you fixed those issue after the installation of wampserver then you might get stuck at this problem.

Then You can simply uninstall and install wamp server again

And If you have not install pre required dependency then first of all uninstall wampserver . And then install pre requirement first and then finally you can install Wampserver and it should work now.

you can download Pre-required applications from following link

For x64 Machines

microsoft visual c++ 2010 redistributable package (x64) https://www.microsoft.com/en-in/download/details.aspx?id=14632

Visual C++ Redistributable for Visual Studio 2012 Update 4 https://www.microsoft.com/en-in/download/details.aspx?id=30679

Visual C++ Redistributable Packages for Visual Studio 2013 https://www.microsoft.com/en-in/download/details.aspx?id=40784

Visual C++ Redistributable for Visual Studio 2015 https://www.microsoft.com/en-in/download/details.aspx?id=48145

For x86 Machines

Microsoft Visual C++ 2010 Redistributable Package (x86) https://www.microsoft.com/en-in/download/details.aspx?id=14632

Visual C++ Redistributable for Visual Studio 2012 Update 4 https://www.microsoft.com/en-in/download/details.aspx?id=30679

Visual C++ Redistributable Packages for Visual Studio 2013 https://www.microsoft.com/en-in/download/details.aspx?id=40784

Visual C++ Redistributable for Visual Studio 2015 https://www.microsoft.com/en-in/download/details.aspx?id=48145

Note:- Take backup of your project files before uninstall

How to get current location in Android

I'm using this tutorial and it works nicely for my application.

In my activity I put this code:

GPSTracker tracker = new GPSTracker(this);
    if (!tracker.canGetLocation()) {
        tracker.showSettingsAlert();
    } else {
        latitude = tracker.getLatitude();
        longitude = tracker.getLongitude();
    }

also check if your emulator runs with Google API

Angular JS POST request not sending JSON data

If you are serializing your data object, it will not be a proper json object. Take what you have, and just wrap the data object in a JSON.stringify().

$http({
    url: '/user_to_itsr',
    method: "POST",
    data: JSON.stringify({application:app, from:d1, to:d2}),
    headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
    $scope.users = data.users; // assign  $scope.persons here as promise is resolved here 
}).error(function (data, status, headers, config) {
    $scope.status = status + ' ' + headers;
});

Moving from one activity to another Activity in Android

1) place setContentView(R.layout.avtivity_next); to the next-activity's onCreate() method just like this (main) activity's onCreate()

2) if you have not defined the next-activity in your-apps manifest file then do this also, like:

<application
        android:allowBackup="true"
        android:icon="@drawable/app_icon"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="Main Activity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".NextActivity"
            android:label="Next Activity" >
        </activity>
    </application>

You must have to perform the 2nd step every time you create a new activity, otherwise your app will crash

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

How to activate "Share" button in android app?

Add a Button and on click of the Button add this code:

Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));

Useful links:

For basic sharing

For customization

OnClickListener in Android Studio

you will need to button initilzation inside method instead of trying to initlzing View's at class level do it as:

 Button button;  //<< declare here..

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button= (Button) findViewById(R.id.standingsButton); //<< initialize here
         // set OnClickListener for Button here
        button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
        }
      });
    }

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

How to know if a Fragment is Visible?

Adding some information here that I experienced:

fragment.isVisible is only working (true/false) when you replaceFragment() otherwise if you work with addFragment(), isVisible always returns true whether the fragment is in behind of some other fragment.

How do I change the background of a Frame in Tkinter?

You use ttk.Frame, bg option does not work for it. You should create style and apply it to the frame.

from tkinter import *
from tkinter.ttk import * 

root = Tk()

s = Style()
s.configure('My.TFrame', background='red')

mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()

How to get Android GPS location

Here's your problem:

int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());

Latitude and Longitude are double-values, because they represent the location in degrees.

By casting them to int, you're discarding everything behind the comma, which makes a big difference. See "Decimal Degrees - Wiki"

runOnUiThread in fragment

Use a Kotlin extension function

fun Fragment?.runOnUiThread(action: () -> Unit) {
    this ?: return
    if (!isAdded) return // Fragment not attached to an Activity
    activity?.runOnUiThread(action)
}

Then, in any Fragment you can just call runOnUiThread. This keeps calls consistent across activities and fragments.

runOnUiThread {
    // Call your code here
}

NOTE: If Fragment is no longer attached to an Activity, callback will not be called and no exception will be thrown

If you want to access this style from anywhere, you can add a common object and import the method:

object ThreadUtil {
    private val handler = Handler(Looper.getMainLooper())

    fun runOnUiThread(action: () -> Unit) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            handler.post(action)
        } else {
            action.invoke()
        }
    }
}

PHP: How to get referrer URL?

Underscore. Not space.

$_SERVER['HTTP_REFERER']

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

Angular, content type is not being sent with $http

$http({
    url: 'http://localhost:8080/example/teste',
    dataType: 'json',
    method: 'POST',
    data: '',
    headers: {
        "Content-Type": "application/json"
    }

}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

Try like this.

How to pass values between Fragments

You can achieve your goal by ViewModel and Live Data which is cleared by Arnav Rao. Now I put an example to clear it more neatly.

First, the assumed ViewModel is named SharedViewModel.java.

public class SharedViewModel extends ViewModel {
    private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

    public void select(Item item) {
        selected.setValue(item);
    }
    public LiveData<Item> getSelected() {
        return selected;
    }
}

Then the source fragment is the MasterFragment.java from where we want to send a data.

public class MasterFragment extends Fragment {
    private SharedViewModel model;

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        itemSelector.setOnClickListener(item -> {

            // Data is sent

            model.select(item);
        });
    }
}

And finally the destination fragment is the DetailFragment.java to where we want to receive the data.

public class DetailFragment extends Fragment {

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        model.getSelected().observe(getViewLifecycleOwner(), { item ->

           // Data is received 

        });
    }
}

Python Request Post with param data

params is for GET-style URL parameters, data is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.

Your raw post contains JSON data though. requests can handle JSON encoding for you, and it'll set the correct Content-Type header too; all you need to do is pass in the Python object to be encoded as JSON into the json keyword argument.

You could split out the URL parameters as well:

params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

then post your data with:

import requests

url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, json=data)

The json keyword is new in requests version 2.4.2; if you still have to use an older version, encode the JSON manually using the json module and post the encoded result as the data key; you will have to explicitly set the Content-Type header in that case:

import requests
import json

headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, data=json.dumps(data), headers=headers)

onCreateOptionsMenu inside Fragments

Set setHasMenuOptions(true) works if application has a theme with Actionbar such as Theme.MaterialComponents.DayNight.DarkActionBar or Activity has it's own Toolbar, otherwise onCreateOptionsMenu in fragment does not get called.

If you want to use standalone Toolbar you either need to get activity and set your Toolbar as support action bar with

(requireActivity() as? MainActivity)?.setSupportActionBar(toolbar)

which lets your fragment onCreateOptionsMenu to be called.

Other alternative is, you can inflate your Toolbar's own menu with toolbar.inflateMenu(R.menu.YOUR_MENU) and item listener with

toolbar.setOnMenuItemClickListener {
   // do something
   true
}

Can typescript export a function?

To answer the title of your question directly because this comes up in Google first:

YES, TypeScript can export a function!

Here is a direct quote from the TS Documentation:

"Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."

Reference Link

In Angular, I need to search objects in an array

I know if that can help you a bit.

Here is something I tried to simulate for you.

Checkout the jsFiddle ;)

http://jsfiddle.net/migontech/gbW8Z/5/

Created a filter that you also can use in 'ng-repeat'

app.filter('getById', function() {
  return function(input, id) {
    var i=0, len=input.length;
    for (; i<len; i++) {
      if (+input[i].id == +id) {
        return input[i];
      }
    }
    return null;
  }
});

Usage in controller:

app.controller('SomeController', ['$scope', '$filter', function($scope, $filter) {
     $scope.fish = [{category:'freshwater', id:'1', name: 'trout', more:'false'},  {category:'freshwater', id:'2', name:'bass', more:'false'}]

     $scope.showdetails = function(fish_id){
         var found = $filter('getById')($scope.fish, fish_id);
         console.log(found);
         $scope.selected = JSON.stringify(found);
     }
}]);

If there are any questions just let me know.

Adding a custom header to HTTP request using angular.js

You are just adding a header which server does not allow.

eg - your server is set up CORS to allow these headers only (accept,cache-control,pragma,content-type,origin)

and in your http request you are adding like this

 headers: {
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json',
        'x-testing': 'testingValue'
    }

then the Server will reject this request since (Authorization and x-testing) are not allowed.

This is server side configuration.

And there is nothing to do with HTTP Options, it is just a preflight to server which is from different domain to check if server will allow actual call or not.

Setting Custom ActionBar Title from Fragment

In your MainActivity, under onCreate:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

And in your fragment activity under onResume:

getActivity().setTitle(R.string.app_name_science);

Optional:- if they show warning of null reference

Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);


Objects.requireNonNull(getActivity()).setTitle(R.string.app_name_science);

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

Start an activity from a fragment

Start new Activity From a Fragment:

Intent intent = new Intent(getActivity(), TargetActivity.class);
startActivity(intent);

Start new Activity From a Activity:

Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);

notifyDataSetChange not working from custom adapter

In my case I simply forget to add in my fragment mRecyclerView.setAdapter(adapter)

Android: Pass data(extras) to a fragment

I prefer Serializable = no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable does not matter.

I would also always provide a helper method for a Fragment or Activity, this way you always know, what data has to be passed. Here an example for your ListMusicFragment:

private static final String EXTRA_MUSIC_LIST = "music_list";

public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_MUSIC_LIST, music);
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public View onCreateView(...) { 
    ...
    Bundle bundle = intent.getArguments();
    List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);
    ...
}

jQuery "on create" event for dynamically-created elements

create a <select> with id , append it to document.. and call .combobox

  var dynamicScript='<select id="selectid"><option value="1">...</option>.....</select>'
  $('body').append(dynamicScript); //append this to the place your wanted.
  $('#selectid').combobox();  //get the id and add .combobox();

this should do the trick.. you can hide the select if you want and after .combobox show it..or else use find..

 $(document).find('select').combobox() //though this is not good performancewise

Refresh or force redraw the fragment

Use the following code for refreshing fragment again:

FragmentTransaction ftr = getFragmentManager().beginTransaction();                          
ftr.detach(EnterYourFragmentName.this).attach(EnterYourFragmentName.this).commit();

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

I had this issue and realized it was because I was calling setContentView(int id) twice in my Activity's onCreate

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

In my experience, to use wmic in a script, you need to get the nested quoting right:

wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive 

quoting both the query and the name. But wmic will only uninstall things installed via windows installer.

How to dismiss AlertDialog in android

There are two ways of closing an alert dialog.

Option 1:

AlertDialog#create().dismiss();

Option 2:

The DialogInterface#dismiss();

Out of the box, the framework calls DialogInterface#dismiss(); when you define event listeners for the buttons:

  1. AlertDialog#setNegativeButton();
  2. AlertDialog#setPositiveButton();
  3. AlertDialog#setNeutralButton();

for the Alert dialog.

Android getActivity() is undefined

If you want to call your activity, just use this . You use the getActivity method when you are inside a fragment.

Call fragment from fragment

I would use a listener. Fragment1 calling the listener (main activity)

Pandas - How to flatten a hierarchical index in columns

I'll share a straight-forward way that worked for me.

[" ".join([str(elem) for elem in tup]) for tup in df.columns.tolist()]
#df = df.reset_index() if needed

Android ListView not refreshing after notifyDataSetChanged

Try this

@Override
public void onResume() {
super.onResume();
items.clear();
items = dbHelper.getItems(); //reload the items from database
adapter = new ItemAdapter(getActivity(), items);//reload the items from database
adapter.notifyDataSetChanged();
}

Redirect output of mongo query to a csv file

Here is what you can try:

print("id,name,startDate")
cursor = db.<collection_name>.find();
while (cursor.hasNext()) {
    jsonObject = cursor.next();
    print(jsonObject._id.valueOf() + "," + jsonObject.name + ",\"" + jsonObject.stateDate.toUTCString() +"\"")

}

Save that in a file, say "export.js". Run the following command:

mongo <host>/<dbname> -u <username> -p <password> export.js > out.csv

"Large data" workflows using pandas

I routinely use tens of gigabytes of data in just this fashion e.g. I have tables on disk that I read via queries, create data and append back.

It's worth reading the docs and late in this thread for several suggestions for how to store your data.

Details which will affect how you store your data, like:
Give as much detail as you can; and I can help you develop a structure.

  1. Size of data, # of rows, columns, types of columns; are you appending rows, or just columns?
  2. What will typical operations look like. E.g. do a query on columns to select a bunch of rows and specific columns, then do an operation (in-memory), create new columns, save these.
    (Giving a toy example could enable us to offer more specific recommendations.)
  3. After that processing, then what do you do? Is step 2 ad hoc, or repeatable?
  4. Input flat files: how many, rough total size in Gb. How are these organized e.g. by records? Does each one contains different fields, or do they have some records per file with all of the fields in each file?
  5. Do you ever select subsets of rows (records) based on criteria (e.g. select the rows with field A > 5)? and then do something, or do you just select fields A, B, C with all of the records (and then do something)?
  6. Do you 'work on' all of your columns (in groups), or are there a good proportion that you may only use for reports (e.g. you want to keep the data around, but don't need to pull in that column explicity until final results time)?

Solution

Ensure you have pandas at least 0.10.1 installed.

Read iterating files chunk-by-chunk and multiple table queries.

Since pytables is optimized to operate on row-wise (which is what you query on), we will create a table for each group of fields. This way it's easy to select a small group of fields (which will work with a big table, but it's more efficient to do it this way... I think I may be able to fix this limitation in the future... this is more intuitive anyhow):
(The following is pseudocode.)

import numpy as np
import pandas as pd

# create a store
store = pd.HDFStore('mystore.h5')

# this is the key to your storage:
#    this maps your fields to a specific group, and defines 
#    what you want to have as data_columns.
#    you might want to create a nice class wrapping this
#    (as you will want to have this map and its inversion)  
group_map = dict(
    A = dict(fields = ['field_1','field_2',.....], dc = ['field_1',....,'field_5']),
    B = dict(fields = ['field_10',......        ], dc = ['field_10']),
    .....
    REPORTING_ONLY = dict(fields = ['field_1000','field_1001',...], dc = []),

)

group_map_inverted = dict()
for g, v in group_map.items():
    group_map_inverted.update(dict([ (f,g) for f in v['fields'] ]))

Reading in the files and creating the storage (essentially doing what append_to_multiple does):

for f in files:
   # read in the file, additional options may be necessary here
   # the chunksize is not strictly necessary, you may be able to slurp each 
   # file into memory in which case just eliminate this part of the loop 
   # (you can also change chunksize if necessary)
   for chunk in pd.read_table(f, chunksize=50000):
       # we are going to append to each table by group
       # we are not going to create indexes at this time
       # but we *ARE* going to create (some) data_columns

       # figure out the field groupings
       for g, v in group_map.items():
             # create the frame for this group
             frame = chunk.reindex(columns = v['fields'], copy = False)    

             # append it
             store.append(g, frame, index=False, data_columns = v['dc'])

Now you have all of the tables in the file (actually you could store them in separate files if you wish, you would prob have to add the filename to the group_map, but probably this isn't necessary).

This is how you get columns and create new ones:

frame = store.select(group_that_I_want)
# you can optionally specify:
# columns = a list of the columns IN THAT GROUP (if you wanted to
#     select only say 3 out of the 20 columns in this sub-table)
# and a where clause if you want a subset of the rows

# do calculations on this frame
new_frame = cool_function_on_frame(frame)

# to 'add columns', create a new group (you probably want to
# limit the columns in this new_group to be only NEW ones
# (e.g. so you don't overlap from the other tables)
# add this info to the group_map
store.append(new_group, new_frame.reindex(columns = new_columns_created, copy = False), data_columns = new_columns_created)

When you are ready for post_processing:

# This may be a bit tricky; and depends what you are actually doing.
# I may need to modify this function to be a bit more general:
report_data = store.select_as_multiple([groups_1,groups_2,.....], where =['field_1>0', 'field_1000=foo'], selector = group_1)

About data_columns, you don't actually need to define ANY data_columns; they allow you to sub-select rows based on the column. E.g. something like:

store.select(group, where = ['field_1000=foo', 'field_1001>0'])

They may be most interesting to you in the final report generation stage (essentially a data column is segregated from other columns, which might impact efficiency somewhat if you define a lot).

You also might want to:

  • create a function which takes a list of fields, looks up the groups in the groups_map, then selects these and concatenates the results so you get the resulting frame (this is essentially what select_as_multiple does). This way the structure would be pretty transparent to you.
  • indexes on certain data columns (makes row-subsetting much faster).
  • enable compression.

Let me know when you have questions!

Android Button click go to another xml page

Write below code in your MainActivity.java file instead of your code.

public class MainActivity extends Activity implements OnClickListener {

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

        Button mBtn1 = (Button) findViewById(R.id.mBtn1);
        mBtn1.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        Log.i("clicks","You Clicked B1");
        Intent i=new Intent(MainActivity.this, MainActivity2.class);
        startActivity(i);
    }
}

And Declare MainActivity2 into your Androidmanifest.xml file using below code.

<activity
    android:name=".MainActivity2"
    android:label="@string/title_activity_main">
</activity>

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

I had a similar problem which I fixed by moving some fragment transaction code from onResume() into onStart().

To be more precise: My app is a launcher. After pressing the Android Home button, the user can choose a launcher until his/her decision is remembered. When going "back" at this point (e. g. by tapping in the greyish area) the app crashed.

Maybe this helps somebody.

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

If you will use only Vidar Wahlberg answer, you get error when you open other activity (for example) and back to map. Or in my case open other activity and then from new activity open map again( without use back button). But when you combine Vidar Wahlberg solution and Matt solution you will have not exceptions.

layout

<com.example.ui.layout.MapWrapperLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/map_relative_layout">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/root">

        <fragment xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.SupportMapFragment" />
    </RelativeLayout>
</<com.example.ui.layout.MapWrapperLayout>

Fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null){
            parent.removeView(view);
        }
    }
    try {
        view = inflater.inflate(R.layout.map_view, null);
        if(view!=null){
            ViewGroup root = (ViewGroup) view.findViewById(R.id.root);
...

@Override
public void onDestroyView() {
    super.onDestroyView();
    Fragment fragment = this.getSherlockActivity().getSupportFragmentManager().findFragmentById(R.id.map);
    if (fragment != null)
        getFragmentManager().beginTransaction().remove(fragment).commit();
}

Unable instantiate android.gms.maps.MapFragment

Apart from many of the things mentioned before, to me it was important to mark the .jar also in Order and Export. As far as I can tell, is not usually mentioned and to me it was crucial.

Mark the lib in Order and Export

Google Maps Android API v2 Authorization failure

For me, everything was working both in an emulator and on a physical device.

However, it stopped working for me when I set up a second machine to debug the same app in an emulator with a newer API level.

I did not realize that the fingerprint for that machine changed. After seeing the authentication failure error log in the Device Log I closely compared the fingerprint in my Google Developer Console with the one in the error message. That's when I saw the difference. After adding the new fingerprint to the Developer Console (in combination with the package name) my app started working as expected in the emulator on the new system.

So if you set up a new system, check your fingerprints again!

This app won't run unless you update Google Play Services (via Bazaar)

I have found a nice solution which let you test your app in the emulator and also doesn't require you to revert to the older version of the library. See an answer to Stack Overflow question Running Google Maps v2 on the Android emulator.

Access iframe elements in JavaScript

window.frames['myIFrame'].document.getElementById('myIFrameElemId')

not working for me but I found another solution. Use:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

I checked it on Firefox and Chrome.

pip: no module named _internal

This solution works for me:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py --force-reinstall

or use sudo for elevated permissions (sudo python3 get-pip.py --force-reinstall).

Of course, you can also use python instead of python3 ;)

Source

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

How to send and retrieve parameters using $state.go toParams and $stateParams?

I'd faced a similar problem. I ended up with a working solution after a lot of googling and trial and test. Here is my solution which would work for you.

I have two controllers - searchBoxController and stateResultController and a parameter named searchQuery to be passed from a view having a search box to a view showing the results fetched from a remote server. This is how you do it:

Below is the controller from which you call the next view using $state.go()

.controller('searchBoxController', function ($scope, $state) {
        $scope.doSearch = function(){
            var searchInputRaw = $scope.searchQueryInput;
            $state.go('app.searchResults', { searchQuery: searchInput });
        }
    })

Below is the state that would be called when the $state.go() gets executed:

.state('app.searchResults', 
            {
                url: '/searchResults',
                views:
                {
                    'menuContent': { templateUrl: 'templates/searchResult.html', controller: 'stateResultController' }
                },
                params: 
                {
                    'searchQuery': ''
                }
            })

And finally, the controller associated with the app.searchResults state:

.controller('stateResultController', function ($scope, $state, $stateParams, $http) {
        $scope.searchQueryInput = $stateParams.searchQuery;
    });

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

Is it possible to make abstract classes in Python?

I find the accepted answer, and all the others strange, since they pass self to an abstract class. An abstract class is not instantiated so can't have a self.

So try this, it works.

from abc import ABCMeta, abstractmethod


class Abstract(metaclass=ABCMeta):
    @staticmethod
    @abstractmethod
    def foo():
        """An abstract method. No need to write pass"""


class Derived(Abstract):
    def foo(self):
        print('Hooray!')


FOO = Derived()
FOO.foo()

error LNK2038: mismatch detected for '_ITERATOR_DEBUG_LEVEL': value '0' doesn't match value '2' in main.obj

The error can be caused by mixing together debug builds and release builds in same executable or dll.

  1. in the vs configuration manager, are some of your projects in debug mode and some in release mode?
  2. is one of your release projects has the preprocessor symbol DEBUG or _DEBUG defined?
  3. is one of your debug projects has the preprocessor symbol NDEBUG defined?

Pass arguments to Constructor in VBA

Another approach

Say you create a class clsBitcoinPublicKey

In the class module create an ADDITIONAL subroutine, that acts as you would want the real constructor to behave. Below I have named it ConstructorAdjunct.

Public Sub ConstructorAdjunct(ByVal ...)

 ...

End Sub

From the calling module, you use an additional statement

Dim loPublicKey AS clsBitcoinPublicKey

Set loPublicKey = New clsBitcoinPublicKey

Call loPublicKey.ConstructorAdjunct(...)

The only penalty is the extra call, but the advantage is that you can keep everything in the class module, and debugging becomes easier.

TypeError: Image data can not convert to float

The error occurred when I unknowingly tried plotting the image path instead of the image.

My code :

import cv2 as cv
from matplotlib import pyplot as plt
import pytesseract
from resizeimage import resizeimage

img = cv.imread("D:\TemplateMatch\\fitting.png") ------>"THIS IS THE WRONG USAGE"
#cv.rectangle(img,(29,2496),(604,2992),(255,0,0),5)
plt.imshow(img)

Correction: img = cv.imread("fitting.png") --->THIS IS THE RIGHT USAGE"

Transpose a matrix in Python

Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)

import numpy as np

a = np.array([(1,2,3), (4,5,6)])

b = a.transpose()

How can I delete Docker's images?

Possible reason: The reason can be that this image is currently used by a running container. In such case, you can list running containers, stop the relevant container and then remove the image:

docker ps
docker stop <containerid>
docker rm <containerid>
docker rmi <imageid>

If you cannnot find container by docker ps, you can use this to list all already exited containers and remove them.

docker ps -a | grep 60afe4036d97
docker rm <containerid>

Note: Be careful of deleting all exited containers at once in case you use Volume-Only containers. These stay in Exit state, but contains useful data.

How to use ClassLoader.getResources() correctly?

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

How do I Validate the File Type of a File Upload?

Client Side Validation Checking:-

HTML:

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClientClick = "return ValidateFile()"  OnClick="btnUpload_Click"  />
<br />
<asp:Label ID="Label1" runat="server" Text="" />

Javascript:

<script type ="text/javascript">

    var validFilesTypes=["bmp","gif","png","jpg","jpeg","doc","xls"];

    function ValidateFile()

    {

      var file = document.getElementById("<%=FileUpload1.ClientID%>");

      var label = document.getElementById("<%=Label1.ClientID%>");

      var path = file.value;

      var ext=path.substring(path.lastIndexOf(".")+1,path.length).toLowerCase();

      var isValidFile = false;

      for (var i=0; i<validFilesTypes.length; i++)    
      {    
        if (ext==validFilesTypes[i])    
        {    
            isValidFile=true;    
            break;    
        }    
      }

      if (!isValidFile)    
      {    
        label.style.color="red";    
        label.innerHTML="Invalid File. Please upload a File with" +    
         " extension:\n\n"+validFilesTypes.join(", ");    
      }    
      return isValidFile;    
     }    
</script>

Internal and external fragmentation

First of all the term fragmentation cues there's an entity divided into parts — fragments.

  • Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"

  • External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous

System.Collections.Generic.List does not contain a definition for 'Select'

You need to have the System.Linq namespace included in your view since Select is an extension method. You have a couple of options on how to do this:

Add @using System.Linq to the top of your cshtml file.

If you find that you will be using this namespace often in many of your views, you can do this for all views by modifying the web.config inside of your Views folder (not the one at the root). You should see a pages/namespace XML element, create a new add child that adds System.Linq. Here is an example:

<configuration>
    <system.web.webPages.razor>
        <pages>
            <namespaces>
                <add namespace="System.Linq" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>
</configuration>

Is it possible to use if...else... statement in React render function?

If you need more than one condition, so you can try this out

https://www.npmjs.com/package/react-if-elseif-else-render

import { If, Then, ElseIf, Else } from 'react-if-elseif-else-render';

class Example extends Component {

  render() {
    var i = 3; // it will render '<p>Else</p>'
    return (
      <If condition={i == 1}>
        <Then>
          <p>Then: 1</p>
        </Then>
        <ElseIf condition={i == 2}>
          <p>ElseIf: 2</p>
        </ElseIf>
        <Else>
          <p>Else</p>
        </Else>
      </If>
    );
  }
}

What is the difference between IEnumerator and IEnumerable?

An Enumerator shows you the items in a list or collection. Each instance of an Enumerator is at a certain position (the 1st element, the 7th element, etc) and can give you that element (IEnumerator.Current) or move to the next one (IEnumerator.MoveNext). When you write a foreach loop in C#, the compiler generates code that uses an Enumerator.

An Enumerable is a class that can give you Enumerators. It has a method called GetEnumerator which gives you an Enumerator that looks at its items. When you write a foreach loop in C#, the code that it generates calls GetEnumerator to create the Enumerator used by the loop.

Different ways of adding to Dictionary

The performance is almost a 100% identical. You can check this out by opening the class in Reflector.net

This is the This indexer:

public TValue this[TKey key]
{
    get
    {
        int index = this.FindEntry(key);
        if (index >= 0)
        {
            return this.entries[index].value;
        }
        ThrowHelper.ThrowKeyNotFoundException();
        return default(TValue);
    }
    set
    {
        this.Insert(key, value, false);
    }
}

And this is the Add method:

public void Add(TKey key, TValue value)
{
    this.Insert(key, value, true);
}

I won't post the entire Insert method as it's rather long, however the method declaration is this:

private void Insert(TKey key, TValue value, bool add)

And further down in the function, this happens:

if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key))
{
    if (add)
    {
        ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
    }

Which checks if the key already exists, and if it does and the parameter add is true, it throws the exception.

So for all purposes and intents the performance is the same.

Like a few other mentions, it's all about whether you need the check, for attempts at adding the same key twice.

Sorry for the lengthy post, I hope it's okay.

Update GCC on OSX

in /usr/bin type

sudo ln -s -f g++-4.2 g++

sudo ln -s -f gcc-4.2 gcc

That should do it.

Undefined Reference to

I had this issue when I forgot to add the new .h/.c file I created to the meson recipe so this is just a friendly reminder.

How to take the nth digit of a number in python

I would recommend adding a boolean check for the magnitude of the number. I'm converting a high milliseconds value to datetime. I have numbers from 2 to 200,000,200 so 0 is a valid output. The function as @Chris Mueller has it will return 0 even if number is smaller than 10**n.

def get_digit(number, n):
    return number // 10**n % 10

get_digit(4231, 5)
# 0

def get_digit(number, n):
    if number - 10**n < 0:
        return False
    return number // 10**n % 10

get_digit(4321, 5)
# False

You do have to be careful when checking the boolean state of this return value. To allow 0 as a valid return value, you cannot just use if get_digit:. You have to use if get_digit is False: to keep 0 from behaving as a false value.

React Router with optional path parameter

If you are looking to do an exact match, use the following syntax: (param)?.

Eg.

<Route path={`my/(exact)?/path`} component={MyComponent} />

The nice thing about this is that you'll have props.match to play with, and you don't need to worry about checking the value of the optional parameter:

{ props: { match: { "0": "exact" } } }

Xcode Simulator: how to remove older unneeded devices?

following some of the answers here, deleting some simulators from my Xcode Menu > Window > Devices > Simulators did nothing to help my dying disk space: enter image description here

however, cd ~/Library/Developer/Xcode/iOS\ DeviceSupport and running du -sh * I got all of these guys:

2.9G    10.0.1 (14A403)
1.3G    10.1.1 (14B100)
2.9G    10.3.2 (14F89)
1.3G    10.3.3 (14G60)
1.9G    11.0.1 (15A402)
1.9G    11.0.3 (15A432)
2.0G    11.1.2 (15B202)
2.0G    11.2 (15C114)
2.0G    11.2.1 (15C153)
2.0G    11.2.2 (15C202)
2.0G    11.2.6 (15D100)
2.0G    11.4 (15F79)
2.0G    11.4.1 (15G77)
2.3G    12.0 (16A366)
2.3G    12.0.1 (16A404)
2.3G    12.1 (16B92)

All together that's 33 GB!

A blood bath ensued

see more details here

MsgBox "" vs MsgBox() in VBScript

To my knowledge these are the rules for calling subroutines and functions in VBScript:

  • When calling a subroutine or a function where you discard the return value don't use parenthesis
  • When calling a function where you assign or use the return value enclose the arguments in parenthesis
  • When calling a subroutine using the Call keyword enclose the arguments in parenthesis

Since you probably wont be using the Call keyword you only need to learn the rule that if you call a function and want to assign or use the return value you need to enclose the arguments in parenthesis. Otherwise, don't use parenthesis.

Here are some examples:

  • WScript.Echo 1, "two", 3.3 - calling a subroutine

  • WScript.Echo(1, "two", 3.3) - syntax error

  • Call WScript.Echo(1, "two", 3.3) - keyword Call requires parenthesis

  • MsgBox "Error" - calling a function "like" a subroutine

  • result = MsgBox("Continue?", 4) - calling a function where the return value is used

  • WScript.Echo (1 + 2)*3, ("two"), (((3.3))) - calling a subroutine where the arguments are computed by expressions involving parenthesis (note that if you surround a variable by parenthesis in an argument list it changes the behavior from call by reference to call by value)

  • WScript.Echo(1) - apparently this is a subroutine call using parenthesis but in reality the argument is simply the expression (1) and that is what tends to confuse people that are used to other programming languages where you have to specify parenthesis when calling subroutines

  • I'm not sure how to interpret your example, Randomize(). Randomize is a subroutine that accepts a single optional argument but even if the subroutine didn't have any arguments it is acceptable to call it with an empty pair of parenthesis. It seems that the VBScript parser has a special rule for an empty argument list. However, my advice is to avoid this special construct and simply call any subroutine without using parenthesis.

I'm quite sure that these syntactic rules applies across different versions of operating systems.

You don't have permission to access / on this server

Try to use the following: chmod +rx /home/*

Set System.Drawing.Color values

You must use Color.FromArgb method to create new color structure

var newColor = Color.FromArgb(0xCC,0xBB,0xAA);

webpack command not working

webpack is not only in your node-modules/webpack/bin/ directory, it's also linked in node_modules/.bin.

You have the npm bin command to get the folder where npm will install executables.

You can use the scripts property of your package.json to use webpack from this directory which will be exported.

"scripts": {
  "scriptName": "webpack --config etc..."
}

For example:

"scripts": {
  "build": "webpack --config webpack.config.js"
}

You can then run it with:

npm run build

Or even with arguments:

npm run build -- <args>

This allow you to have you webpack.config.js in the root folder of your project without having webpack globally installed or having your webpack configuration in the node_modules folder.

Join vs. sub-query

These days, many dbs can optimize subqueries and joins. Thus, you just gotto examine your query using explain and see which one is faster. If there is not much difference in performance, I prefer to use subquery as they are simple and easier to understand.

How to customize the configuration file of the official PostgreSQL Docker image?

I looked through all answers and there is another option left. You can change your CMD value in docker file (it is not the best one, but still possible way to achieve your goal).

Basically we need to

  • Copy config file in docker container
  • Override postgres start options

Docker file example:

FROM postgres:9.6
USER postgres

# Copy postgres config file into container
COPY postgresql.conf /etc/postgresql

# Override default postgres config file
CMD ["postgres", "-c", "config_file=/etc/postgresql/postgresql.conf"]

Though I think using command: postgres -c config_file=/etc/postgresql/postgresql.confin your docker-compose.yml file proposed by Matthias Braun is the best option.

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

Sort an array of objects in React and render them

Chrome browser considers integer value as return type not boolean value so,

this.state.data.sort((a, b) => a.item.timeM > b.item.timeM ? 1:-1).map(
    (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)

How do I encode a JavaScript object as JSON?

All major browsers now include native JSON encoding/decoding.

// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject); 

// To decode (This produces an object)
var obj = JSON.parse(json_str);

Note that only valid JSON data will be encoded. For example:

var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"

Valid JSON types are: objects, strings, numbers, arrays, true, false, and null.

Some JSON resources:

What are the different types of keys in RDBMS?

Ólafur forgot the surrogate key:

A surrogate key in a database is a unique identifier for either an entity in the modeled world or an object in the database. The surrogate key is not derived from application data.

How to create materialized views in SQL Server?

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

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

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

schedule daily/nightly/weekly/whatnot refresh like

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

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

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

You have enabled CORS and enabled Access-Control-Allow-Origin : * in the server.If still you get GET method working and POST method is not working then it might be because of the problem of Content-Type and data problem.

First AngularJS transmits data using Content-Type: application/json which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded

Example :-

        $scope.formLoginPost = function () {
            $http({
                url: url,
                method: "POST",
                data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(function (response) {
                // success
                console.log('success');
                console.log("then : " + JSON.stringify(response));
            }, function (response) { // optional
                // failed
                console.log('failed');
                console.log(JSON.stringify(response));
            });
        };

Note : I am using $.params to serialize the data to use Content-Type: x-www-form-urlencoded. Alternatively you can use the following javascript function

function params(obj){
    var str = "";
    for (var key in obj) {
        if (str != "") {
            str += "&";
        }
        str += key + "=" + encodeURIComponent(obj[key]);
    }
    return str;
}

and use params({ 'username': $scope.username, 'Password': $scope.Password }) to serialize it as the Content-Type: x-www-form-urlencoded requests only gets the POST data in username=john&Password=12345 form.

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

Adding files to a GitHub repository

Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.

Gradle error: could not execute build using gradle distribution

I had this issue as well and jaywhy13 answer was good but not enough.

I had to change a setting: Settings -> Gradle -> MyProject

There you need to check the "auto import" and select "use customizable gradle wrapper". After that it should refresh gradle and you can build again. If not try a reboot of Android Studio.

How can I get the values of data attributes in JavaScript code?

Circa 2019, using jquery, this can be accessed using $('#DOMId').data('typeId') where $('#DOMId') is the jquery selector for your span element.

How can I print a quotation mark in C?

Besides escaping the character, you can also use the format %c, and use the character literal for a quotation mark.

printf("And I quote, %cThis is a quote.%c\n", '"', '"');

Duplicate AssemblyVersion Attribute

My error was that I was also referencing another file in my project, which was also containing a value for the attribute "AssemblyVersion". I removed that attribute from one of the file and it is now working properly.

The key is to make sure that this value is not declared more than once in any file in your project.

How to recognize vehicle license / number plate (ANPR) from an image?

I coded a C# version based on JAVA ANPR, but I changed the awt library functions with OpenCV. You can check it at http://anprmx.codeplex.com

Passing just a type as a parameter in C#

foo.GetColumnValues(dm.mainColumn, typeof(string))

Alternatively, you could use a generic method:

public void GetColumnValues<T>(object mainColumn)
{
    GetColumnValues(mainColumn, typeof(T));
}

and you could then use it like:

foo.GetColumnValues<string>(dm.mainColumn);

How do I create a link to add an entry to a calendar?

You can have the program create an .ics (iCal) version of the calendar and then you can import this .ics into whichever calendar program you'd like: Google, Outlook, etc.

I know this post is quite old, so I won't bother inputting any code. But please comment on this if you'd like me to provide an outline of how to do this.

How To Add An "a href" Link To A "div"?

I'd say:

 <a href="#"id="buttonOne">
            <div id="linkedinB">
                <img src="img/linkedinB.png" width="40" height="40">
            </div>
      </div> 

However, it will still be a link. If you want to change your link into a button, you should rename the #buttonone to #buttonone a { your css here }.

Google Maps API 3 - Custom marker color for default (dot) marker

Here is a nice solution using the Gooogle Maps API itself. No external service, no extra library. And it enables custom shapes and multiple colors and styles. The solution uses vectorial markers, which googlemaps api calls Symbols.

Besides the few and limited predefined symbols, you can craft any shape of any color by specifying an SVG path string (Spec).

To use it, instead of setting the 'icon' marker option to the image url, you set it to a dictionary containing the symbol options. As example, I managed to craft one symbol that is quite similar to the standard marker:

function pinSymbol(color) {
    return {
        path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z M -2,-30 a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0',
        fillColor: color,
        fillOpacity: 1,
        strokeColor: '#000',
        strokeWeight: 2,
        scale: 1,
   };
}

var marker = new google.maps.Marker({
   map: map,
   position: new google.maps.LatLng(latitude, longitude),
   icon: pinSymbol("#FFF"),
});

Vector Marker

I you are careful to keep the shape key point at 0,0 you avoid having to define marker icon centering parameters. Another path example, the same marker without the dot:

    path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',

Dotless Vector Marker

And here you have a very simple and ugly coloured flag:

    path: 'M 0,0 -1,-2 V -43 H 1 V -2 z M 1,-40 H 30 V -20 H 1 z',

Vector Flag

You can also create the paths using a visual tool like Inkscape (GNU-GPL, multiplatform). Some useful hints:

  • Google API just accepts a single path, so you have to turn any other object (square, cercle...) into a path and join them as a single one. Both commands at the Path menu.
  • To move the path to the (0,0), go to the Path Edit mode (F2) select all the control nodes and drag them. Moving the object with F1, won't change the path node coords.
  • To ensure the reference point is at (0,0), you can select it alone and edit the coords by hand on the top toolbar.
  • After saving the SVG file, which is an XML, open it with an editor, look for the svg:path element and copy the content of the 'd' attribute.

Excel 2010: how to use autocomplete in validation list

As other people suggested, you need to use a combobox. However, most tutorials show you how to set up just one combobox and the process is quite tedious.

As I faced this problem before when entering a large amount of data from a list, I can suggest you use this autocomplete add-in . It helps you create the combobox on any cells you select and you can define a list to appear in the dropdown.

How to convert an integer to a character array using C

Use itoa, as is shown here.

char buf[5];
// Convert 123 to string [buf]
itoa(123, buf, 10);

buf will be a string array as you documented. You might need to increase the size of the buffer.

How do I undo the most recent local commits in Git?

Just reset it doing the command below using git:

git reset --soft HEAD~1

Explain: what git reset does, it's basically reset to any commit you'd like to go back to, then if you combine it with --soft key, it will go back, but keep the changes in your file(s), so you get back to the stage which the file was just added, HEAD is the head of the branch and if you combine with ~1 (in this case you also use HEAD^), it will go back only one commit which what you want...

I create the steps in the image below in more details for you, including all steps that may happens in real situations and committing the code:

How to undo the last commits in Git?

Easily measure elapsed time

From what is see, tv_sec stores the seconds elapsed while tv_usec stored the microseconds elapsed separately. And they aren't the conversions of each other. Hence, they must be changed to proper unit and added to get the total time elapsed.

struct timeval startTV, endTV;

gettimeofday(&startTV, NULL); 

doSomething();
doSomethingLong();

gettimeofday(&endTV, NULL); 

printf("**time taken in microseconds = %ld\n",
    (endTV.tv_sec * 1e6 + endTV.tv_usec - (startTV.tv_sec * 1e6 + startTV.tv_usec))
    );

ITextSharp HTML to PDF?

If you are converting html to pdf on the html server side you can use Rotativa :

Install-Package Rotativa

This is based on wkhtmltopdf but it has better css support than iTextSharp has and is very simple to integrate with MVC (which is mostly used) as you can simply return the view as pdf:

public ActionResult GetPdf()
{
    //...
    return new ViewAsPdf(model);// and you are done!
} 

Find if a textbox is disabled or not using jquery

.prop('disabled') will return a Boolean:

var isDisabled = $('textbox').prop('disabled');

Here's the fiddle: http://jsfiddle.net/unhjM/

Invalidating JSON Web Tokens

I am going to answer If we need to provide logout from all devices feature when we are using JWT. This approach will use database look-ups for each requests. Because we need a persistence security state even if there is a server crash. In the user table we will have two columns

  1. LastValidTime (default: creation time)
  2. Logged-In (default: true)

Whenever there is a log out request from the user we will update the LastValidTime to current time and Logged-In to false. If there is a log in request we wont change LastValidTime but Logged-In will be set to true.

When we create the JWT we will have the JWT creation time in the payload. When we authorize for a service we will check 3 conditions

  1. Is JWT valid
  2. Is JWT payload creation time is greater than User LastValidTime
  3. Is user Logged-In

Lets see a practical scenario.

User X has two devices A, B. He logged in to our server at 7 pm using device A and device B. (lets say JWT expire time is 12 hrs). A and B both have JWT with createdTime : 7pm

At 9 pm he lost his device B. He immediately log out from the device A. That means Now our database X user entry has LastValidTime as "ThatDate:9:00:xx:xxx" and Logged-In as "false".

At 9:30 the Mr.Thief tries to log in using device B. We will check the database even the Logged-In is false so we wont allow.

At 10 pm Mr.X log in from his device A. Now device A has JWT with created time : 10pm. Now database Logged-In is set to "true"

At 10:30 pm Mr.Thief tries to log in. Even though the Logged-In is true. The LastValidTime is 9 pm in the database but B's JWT has created time as 7pm. So he wont be allowed to access the service. So using device B without having the password he cannot use already created JWT after one device log out.

How to remove array element in mongodb?

If you use the Mongoose API and looking to pull a sub/child object: Read this document Don't forget to use save() when you're done editing otherwise the changes won't be saved to the database.

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

How to disassemble a binary executable in Linux to get the assembly code?

You might find ODA useful. It's a web-based disassembler that supports tons of architectures.

http://onlinedisassembler.com/

How to create an empty DataFrame with a specified schema?

Here you can create schema using StructType in scala and pass the Empty RDD so you will able to create empty table. Following code is for the same.

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.sql._
import org.apache.spark.sql.Row
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.StructField
import org.apache.spark.sql.types.IntegerType
import org.apache.spark.sql.types.BooleanType
import org.apache.spark.sql.types.LongType
import org.apache.spark.sql.types.StringType



//import org.apache.hadoop.hive.serde2.objectinspector.StructField

object EmptyTable extends App {
  val conf = new SparkConf;
  val sc = new SparkContext(conf)
  //create sparksession object
  val sparkSession = SparkSession.builder().enableHiveSupport().getOrCreate()

  //Created schema for three columns 
   val schema = StructType(
    StructField("Emp_ID", LongType, true) ::
      StructField("Emp_Name", StringType, false) ::
      StructField("Emp_Salary", LongType, false) :: Nil)

      //Created Empty RDD 

  var dataRDD = sc.emptyRDD[Row]

  //pass rdd and schema to create dataframe
  val newDFSchema = sparkSession.createDataFrame(dataRDD, schema)

  newDFSchema.createOrReplaceTempView("tempSchema")

  sparkSession.sql("create table Finaltable AS select * from tempSchema")

}

Eclipse CDT: no rule to make target all

Project -> Clean -> Clean all Projects and then Project -> Build Project worked for me (I did the un-checking generate make-file automatically and then rechecking it before doing this). This was for an AVR (micro-processor programming) project through the AVR CDT plugin in eclipse Juno though.

Difference between MongoDB and Mongoose

Mongodb and Mongoose are two completely different things!

Mongodb is the database itself, while Mongoose is an object modeling tool for Mongodb

EDIT: As pointed out MongoDB is the npm package, thanks!

How to return a table from a Stored Procedure?

Where is your problem??

For the stored procedure, just create:

CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
AS
   SELECT *  -- I would *strongly* recommend specifying the columns EXPLICITLY
   FROM dbo.Emp
   WHERE ID = @EmpID

That's all there is.

From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)

DataTable tblEmployees = new DataTable();

using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
{
    _cmd.CommandType = CommandType.StoredProcedure;

    _cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
    _cmd.Parameters["@EmpID"].Value = 42;

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);

    _dap.Fill(tblEmployees);
}

YourGridView.DataSource = tblEmployees;
YourGridView.DataBind();

and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.

Conda command is not recognized on Windows 10

If you want to use Anaconda in regular cmd on windows you need to add several paths to your Path env variable.

Those paths are (instead of Anaconda3 the folder may be Anaconda2 depending on the Anaconda version on your PC):

\Users\YOUR_USER\Anaconda3
\Users\YOUR_USER\Anaconda3\Library\mingw-w64\bin
\Users\YOUR_USER\Anaconda3\Library\usr\bin
\Users\YOUR_USER\Anaconda3\Library\bin
\Users\YOUR_USER\Anaconda3\Scripts
\Users\YOUR_USER\Anaconda3\bin

Regex select all text between tags

preg_match_all(/<pre>([^>]*?)<\/pre>/,$content,$matches) this regex will select everyting between tag. no matter is it in new line(work with multiline.

Multiple aggregate functions in HAVING clause

GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2

How to find the kth largest element in an unsorted array of length n in O(n)?

I implemented finding kth minimimum in n unsorted elements using dynamic programming, specifically tournament method. The execution time is O(n + klog(n)). The mechanism used is listed as one of methods on Wikipedia page about Selection Algorithm (as indicated in one of the posting above). You can read about the algorithm and also find code (java) on my blog page Finding Kth Minimum. In addition the logic can do partial ordering of the list - return first K min (or max) in O(klog(n)) time.

Though the code provided result kth minimum, similar logic can be employed to find kth maximum in O(klog(n)), ignoring the pre-work done to create tournament tree.

List(of String) or Array or ArrayList

You can use IList(Of String) in the function :

Private Function getWriteBits() As IList(Of String)


Dim temp1 As String
Dim temp2 As Boolean
Dim temp3 As Boolean


'Pallet Destination Unique
Dim temp4 As Boolean
Dim temp5 As Boolean
Dim temp6 As Boolean

Dim lstWriteBits As Ilist = {temp1, temp2, temp3, temp4, temp5, temp6}

Return lstWriteBits
End Function

use list1.AddRange(list2) to add lists

Hope it helps.

How to bind inverse boolean properties in WPF?

This one also works for nullable bools.

 [ValueConversion(typeof(bool?), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType != typeof(bool?))
        {
            throw new InvalidOperationException("The target must be a nullable boolean");
        }
        bool? b = (bool?)value;
        return b.HasValue && !b.Value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !(value as bool?);
    }

    #endregion
}

Location Services not working in iOS 8

My solution which can be compiled in Xcode 5:

#ifdef __IPHONE_8_0
    NSUInteger code = [CLLocationManager authorizationStatus];
    if (code == kCLAuthorizationStatusNotDetermined && ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)] || [self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])) {
        // choose one request according to your business.
        if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationAlwaysUsageDescription"]){
            [self.locationManager requestAlwaysAuthorization];
        } else if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSLocationWhenInUseUsageDescription"]) {
            [self.locationManager  requestWhenInUseAuthorization];
        } else {
            NSLog(@"Info.plist does not contain NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription");
        }
    }
#endif
    [self.locationManager startUpdatingLocation];

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

What is a PDB file?

I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.

Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace string. I included the PDB file in the executable folder and now all is fine.

Update Rows in SSIS OLEDB Destination

Use Lookupstage to decide whether to insert or update. Check this link for more info - http://beingoyen.blogspot.com/2010/03/ssis-how-to-update-instead-of-insert.html

Steps to do update:

  1. Drag OLEDB Command [instead of oledb destination]
  2. Go to properties window
  3. Under Custom properties select SQLCOMMAND and insert update command ex:

    UPDATE table1 SET col1 = ?, col2 = ? where id = ?

  4. map columns in exact order from source to output as in update command

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Import multiple csv files into pandas and concatenate into one DataFrame

If you have same columns in all your csv files then you can try the code below. I have added header=0 so that after reading csv first row can be assigned as the column names.

import pandas as pd
import glob

path = r'C:\DRO\DCL_rawdata_files' # use your path
all_files = glob.glob(path + "/*.csv")

li = []

for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0)
    li.append(df)

frame = pd.concat(li, axis=0, ignore_index=True)

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

Getting the ID of the element that fired an event

For all events, not limited to just jQuery you can use

var target = event.target || event.srcElement;
var id = target.id

Where event.target fails it falls back on event.srcElement for IE. To clarify the above code does not require jQuery but also works with jQuery.

What Are Some Good .NET Profilers?

If Licensing is an issue you could try WINDBG for memory profiling

css selector to match an element without attribute x

Just wanted to add to this, you can have the :not selector in oldIE using selectivizr: http://selectivizr.com/

Reload browser window after POST without prompting user to resend POST data

You could try to create an empty form, method=get, and submitting it.

<form id='reloader' method='get' action="enter url here"> </form>
<script>
// to reload the page, try
document.getElementById('reloader').submit();
</script>

Converting HTML files to PDF

If you have the funding, nothing beats Prince XML as this video shows

C#: calling a button event handler method without actually clicking the button

If the method isn't using either sender or e you could call:

btnTest_Click(null, null);

What you probably should consider doing is extracting the code from within that method into its own method, which you could call from both the button click event handler, and any other places in code that the functionality is required.

What does git rev-parse do?

Just to elaborate on the etymology of the command name rev-parse, Git consistently uses the term rev in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list for example prints a list of 40-char commit hashes for a branch or whatever.

In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.

I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)

Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.

Float a DIV on top of another DIV

.close-image {
    cursor: pointer;
    display: block;
    float: right;
    position: relative;
    top: 22px;
    z-index: 1;
}

I think this might be what you are looking for.

Multiple returns from a function

Languages which allow multiple returns usually just convert the multiple values into a data structure.

For example, in Python you can return multiple values. However, they're actually just being returned as one tuple.

So you can return multiple values in PHP by just creating a simple array and returning that.

java - path to trustStore - set property doesn't work?

Both

-Djavax.net.ssl.trustStore=path/to/trustStore.jks

and

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");

do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore in javax.net.ssl.trustStore.

Count textarea characters

They say IE has issues with the input event but other than that, the solution is rather straightforward.

_x000D_
_x000D_
ta = document.querySelector("textarea");_x000D_
count = document.querySelector("label");_x000D_
_x000D_
ta.addEventListener("input", function (e) {_x000D_
  count.innerHTML = this.value.length;_x000D_
});
_x000D_
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">_x000D_
</textarea>_x000D_
<label for="my-textarea"></label>
_x000D_
_x000D_
_x000D_

HTML select dropdown list

Try this:

_x000D_
_x000D_
<select>_x000D_
    <option value="" disabled="disabled" selected="selected">Please select a name</option>_x000D_
    <option value="1">One</option>_x000D_
    <option value="2">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

When the page loads, this option will be selected by default. However, as soon as the drop-down is clicked, the user won't be able to re-select this option.

Hope this helps.

Shortcut for changing font size

Ctrl + Alt + MouseWheel will work in Visual Studio 2015.

Get week of year in JavaScript like in PHP

This adds "getWeek" method to Date.prototype which returns number of week from the beginning of the year. The argument defines which day of the week to consider the first. If no argument passed, first day is assumed Sunday.

/**
 * Get week number in the year.
 * @param  {Integer} [weekStart=0]  First day of the week. 0-based. 0 for Sunday, 6 for Saturday.
 * @return {Integer}                0-based number of week.
 */
Date.prototype.getWeek = function(weekStart) {
    var januaryFirst = new Date(this.getFullYear(), 0, 1);
    if(weekStart !== undefined && (typeof weekStart !== 'number' || weekStart % 1 !== 0 || weekStart < 0 || weekStart > 6)) {
      throw new Error('Wrong argument. Must be an integer between 0 and 6.');
    }
    weekStart = weekStart || 0;
    return Math.floor((((this - januaryFirst) / 86400000) + januaryFirst.getDay() - weekStart) / 7);
};

How to fire a button click event from JavaScript in ASP.NET

I can make things work this way:

inside javascript junction that is executed by the html button:

document.getElementById("<%= Button2.ClientID %>").click();

ASP button inside div:

<div id="submitBtn" style="display: none;">
   <asp:Button ID="Button2" runat="server" Text="Submit" ValidationGroup="AllValidators" OnClick="Button2_Click" />
</div>

Everything runs from the .cs file except that the code below doesn't execute. There is no message box and redirect to the same page (refresh all boxes):

 int count = cmd.ExecuteNonQuery();
 if (count > 0)
 {
   cmd2.CommandText = insertSuperRoster;
   cmd2.Connection = con;
   cmd2.ExecuteNonQuery();
   string url = "VaccineRefusal.aspx";
   ClientScript.RegisterStartupScript(this.GetType(), "callfunction", "alert('Data Inserted Successfully!');window.location.href = '" + url + "';", true);
  }

Any ideas why these lines won't execute?

Python speed testing - Time Difference - milliseconds

datetime.timedelta is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds

>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a

>>> c
datetime.timedelta(0, 4, 316543)
>>> c.days
0
>>> c.seconds
4
>>> c.microseconds
316543

Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().

You can do all sorts of maths with datetime.timedelta, eg:

>>> c / 10
datetime.timedelta(0, 0, 431654)

It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

The simplest way to resize an UIImage?

@Paul Lynch's answer is great, but it would change the image ratio. if you don`t want to change the image ratio, and still want the new image fit for new size, try this.

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

// calculate a new size which ratio is same to original image
CGFloat ratioW = image.size.width / newSize.width;
CGFloat ratioH = image.size.height / newSize.height;

CGFloat ratio = image.size.width / image.size.height;

CGSize showSize = CGSizeZero;
if (ratioW > 1 && ratioH > 1) { 

    if (ratioW > ratioH) { 
        showSize.width = newSize.width;
        showSize.height = showSize.width / ratio;
    } else {
        showSize.height = newSize.height;
        showSize.width = showSize.height * ratio;
    }

} else if (ratioW > 1) {

    showSize.width = showSize.width;
    showSize.height = showSize.width / ratio;

} else if (ratioH > 1) {

    showSize.height = showSize.height;
    showSize.width = showSize.height * ratio;

}

//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(showSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, showSize.width, showSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;}

Find where python is installed (if it isn't default dir)

You should be able to type "which python" and it will print out a path to python.

or you can type:

python
>>> import re
>>> re.__file__

and it will print a path to the re module and you'll see where python is that way.

Determine what user created objects in SQL Server

The answer is "no, you probably can't".

While there is stuff in there that might say who created a given object, there are a lot of "ifs" behind them. A quick (and not necessarily complete) review:

sys.objects (and thus sys.tables, sys.procedures, sys.views, etc.) has column principal_id. This value is a foreign key that relates to the list of database users, which in turn can be joined with the list of SQL (instance) logins. (All of this info can be found in further system views.)

But.

A quick check on our setup here and a cursory review of BOL indicates that this value is only set (i.e. not null) if it is "different from the schema owner". In our development system, and we've got dbo + two other schemas, everything comes up as NULL. This is probably because everyone has dbo rights within these databases.

This is using NT authentication. SQL authentication probably works much the same. Also, does everyone have and use a unique login, or are they shared? If you have employee turnover and domain (or SQL) logins get dropped, once again the data may not be there or may be incomplete.

You can look this data over (select * from sys.objects), but if principal_id is null, you are probably out of luck.

How to parse XML using vba

Add reference Project->References Microsoft XML, 6.0 and you can use example code:

    Dim xml As String

    xml = "<root><person><name>Me </name> </person> <person> <name>No Name </name></person></root> "
    Dim oXml As MSXML2.DOMDocument60
    Set oXml = New MSXML2.DOMDocument60
    oXml.loadXML xml
    Dim oSeqNodes, oSeqNode As IXMLDOMNode

    Set oSeqNodes = oXml.selectNodes("//root/person")
    If oSeqNodes.length = 0 Then
       'show some message
    Else
        For Each oSeqNode In oSeqNodes
             Debug.Print oSeqNode.selectSingleNode("name").Text
        Next
    End If 

be careful with xml node //Root/Person is not same with //root/person, also selectSingleNode("Name").text is not same with selectSingleNode("name").text

How, in general, does Node.js handle 10,000 concurrent requests?

I understand that Node.js uses a single-thread and an event loop to process requests only processing one at a time (which is non-blocking).

I could be misunderstanding what you've said here, but "one at a time" sounds like you may not be fully understanding the event-based architecture.

In a "conventional" (non event-driven) application architecture, the process spends a lot of time sitting around waiting for something to happen. In an event-based architecture such as Node.js the process doesn't just wait, it can get on with other work.

For example: you get a connection from a client, you accept it, you read the request headers (in the case of http), then you start to act on the request. You might read the request body, you will generally end up sending some data back to the client (this is a deliberate simplification of the procedure, just to demonstrate the point).

At each of these stages, most of the time is spent waiting for some data to arrive from the other end - the actual time spent processing in the main JS thread is usually fairly minimal.

When the state of an I/O object (such as a network connection) changes such that it needs processing (e.g. data is received on a socket, a socket becomes writable, etc) the main Node.js JS thread is woken with a list of items needing to be processed.

It finds the relevant data structure and emits some event on that structure which causes callbacks to be run, which process the incoming data, or write more data to a socket, etc. Once all of the I/O objects in need of processing have been processed, the main Node.js JS thread will wait again until it's told that more data is available (or some other operation has completed or timed out).

The next time that it is woken, it could well be due to a different I/O object needing to be processed - for example a different network connection. Each time, the relevant callbacks are run and then it goes back to sleep waiting for something else to happen.

The important point is that the processing of different requests is interleaved, it doesn't process one request from start to end and then move onto the next.

To my mind, the main advantage of this is that a slow request (e.g. you're trying to send 1MB of response data to a mobile phone device over a 2G data connection, or you're doing a really slow database query) won't block faster ones.

In a conventional multi-threaded web server, you will typically have a thread for each request being handled, and it will process ONLY that request until it's finished. What happens if you have a lot of slow requests? You end up with a lot of your threads hanging around processing these requests, and other requests (which might be very simple requests that could be handled very quickly) get queued behind them.

There are plenty of others event-based systems apart from Node.js, and they tend to have similar advantages and disadvantages compared with the conventional model.

I wouldn't claim that event-based systems are faster in every situation or with every workload - they tend to work well for I/O-bound workloads, not so well for CPU-bound ones.

Writing string to a file on a new line every time

You can do this in two ways:

f.write("text to write\n")

or, depending on your Python version (2 or 3):

print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.x

Getting attributes of a class

import re

class MyClass:
    a = "12"
    b = "34"

    def myfunc(self):
        return self.a

attributes = [a for a, v in MyClass.__dict__.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

For an instance of MyClass, such as

mc = MyClass()

use type(mc) in place of MyClass in the list comprehension. However, if one dynamically adds an attribute to mc, such as mc.c = "42", the attribute won't show up when using type(mc) in this strategy. It only gives the attributes of the original class.

To get the complete dictionary for a class instance, you would need to COMBINE the dictionaries of type(mc).__dict__ and mc.__dict__.

mc = MyClass()
mc.c = "42"

# Python 3.5
combined_dict = {**type(mc).__dict__, **mc.__dict__}

# Or Python < 3.5
def dict_union(d1, d2):
    z = d1.copy()
    z.update(d2)
    return z

combined_dict = dict_union(type(mc).__dict__, mc.__dict__)

attributes = [a for a, v in combined_dict.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

Random number from a range in a Bash Script

Here's another one. I thought it would work on just about anything, but sort's random option isn't available on my centos box at work.

 seq 2000 65000 | sort -R | head -n 1

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

Print last query

DB::enableQueryLog();

$query        = DB::getQueryLog();
$lastQuery    = end($query);
print_r($lastQuery);

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

Upload video files via PHP and save them in appropriate folder and have a database entry

"Could you suggest a simpler code main thing is uploading the file Data base entry is secondary"

^--- As per OP's request. ---^

Image and video uploading code (tested with PHP Version 5.4.17)

HTML form

<!DOCTYPE html>

<head>
<title></title>
</head>

<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

PHP handler (upload_file.php)

Change upload folder to preferred name. Presently saves to upload/

<?php

$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))

&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))

  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Is there a "null coalescing" operator in JavaScript?

After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.

@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in == versus === in JavaScript especially when it comes to issues of checking for undefined and/or null.

There's a really good article about the difference in two terms here. Basically, understand that if you use == instead of ===, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.

How to check whether a pandas DataFrame is empty?

To see if a dataframe is empty, I argue that one should test for the length of a dataframe's columns index:

if len(df.columns) == 0: 1

Reason:

According to the Pandas Reference API, there is a distinction between:

  • an empty dataframe with 0 rows and 0 columns
  • an empty dataframe with rows containing NaN hence at least 1 column

Arguably, they are not the same. The other answers are imprecise in that df.empty, len(df), or len(df.index) make no distinction and return index is 0 and empty is True in both cases.

Examples

Example 1: An empty dataframe with 0 rows and 0 columns

In [1]: import pandas as pd
        df1 = pd.DataFrame()
        df1
Out[1]: Empty DataFrame
        Columns: []
        Index: []

In [2]: len(df1.index)  # or len(df1)
Out[2]: 0

In [3]: df1.empty
Out[3]: True

Example 2: A dataframe which is emptied to 0 rows but still retains n columns

In [4]: df2 = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
        df2
Out[4]:    AA  BB
        0   1  11
        1   2  22
        2   3  33

In [5]: df2 = df2[df2['AA'] == 5]
        df2
Out[5]: Empty DataFrame
        Columns: [AA, BB]
        Index: []

In [6]: len(df2.index)  # or len(df2)
Out[6]: 0

In [7]: df2.empty
Out[7]: True

Now, building on the previous examples, in which the index is 0 and empty is True. When reading the length of the columns index for the first loaded dataframe df1, it returns 0 columns to prove that it is indeed empty.

In [8]: len(df1.columns)
Out[8]: 0

In [9]: len(df2.columns)
Out[9]: 2

Critically, while the second dataframe df2 contains no data, it is not completely empty because it returns the amount of empty columns that persist.

Why it matters

Let's add a new column to these dataframes to understand the implications:

# As expected, the empty column displays 1 series
In [10]: df1['CC'] = [111, 222, 333]
         df1
Out[10]:    CC
         0 111
         1 222
         2 333
In [11]: len(df1.columns)
Out[11]: 1

# Note the persisting series with rows containing `NaN` values in df2
In [12]: df2['CC'] = [111, 222, 333]
         df2
Out[12]:    AA  BB   CC
         0 NaN NaN  111
         1 NaN NaN  222
         2 NaN NaN  333
In [13]: len(df2.columns)
Out[13]: 3

It is evident that the original columns in df2 have re-surfaced. Therefore, it is prudent to instead read the length of the columns index with len(pandas.core.frame.DataFrame.columns) to see if a dataframe is empty.

Practical solution

# New dataframe df
In [1]: df = pd.DataFrame({'AA' : [1, 2, 3], 'BB' : [11, 22, 33]})
        df
Out[1]:    AA  BB
        0   1  11
        1   2  22
        2   3  33

# This data manipulation approach results in an empty df
# because of a subset of values that are not available (`NaN`)
In [2]: df = df[df['AA'] == 5]
        df
Out[2]: Empty DataFrame
        Columns: [AA, BB]
        Index: []

# NOTE: the df is empty, BUT the columns are persistent
In [3]: len(df.columns)
Out[3]: 2

# And accordingly, the other answers on this page
In [4]: len(df.index)  # or len(df)
Out[4]: 0

In [5]: df.empty
Out[5]: True
# SOLUTION: conditionally check for empty columns
In [6]: if len(df.columns) != 0:  # <--- here
            # Do something, e.g. 
            # drop any columns containing rows with `NaN`
            # to make the df really empty
            df = df.dropna(how='all', axis=1)
        df
Out[6]: Empty DataFrame
        Columns: []
        Index: []

# Testing shows it is indeed empty now
In [7]: len(df.columns)
Out[7]: 0

Adding a new data series works as expected without the re-surfacing of empty columns (factually, without any series that were containing rows with only NaN):

In [8]: df['CC'] = [111, 222, 333]
         df
Out[8]:    CC
         0 111
         1 222
         2 333
In [9]: len(df.columns)
Out[9]: 1

Pretty printing JSON from Jackson 2.2's ObjectMapper

You can enable pretty-printing by setting the SerializationFeature.INDENT_OUTPUT on your ObjectMapper like so:

mapper.enable(SerializationFeature.INDENT_OUTPUT);

Parse JSON String into a Particular Object Prototype in JavaScript

While, this is not technically what you want, if you know before hand the type of object you want to handle you can use the call/apply methods of the prototype of your known object.

you can change this

alert(fooJSON.test() ); //Prints 12

to this

alert(Foo.prototype.test.call(fooJSON); //Prints 12

What is difference between cacerts and keystore?

cacerts is where Java stores public certificates of root CAs. Java uses cacerts to authenticate the servers.

Keystore is where Java stores the private keys of the clients so that it can share it to the server when the server requests client authentication.

Uncaught TypeError: .indexOf is not a function

I ran across this error recently using a javascript library which changes the parameters of a function based on conditions.

You can test an object to see if it has the function. I would only do this in scenarios where you don't control what is getting passed to you.

if( param.indexOf != undefined ) {
   // we have a string or other object that 
   // happens to have a function named indexOf
}

You can test this in your browser console:

> (3).indexOf == undefined;
true

> "".indexOf == undefined;
false

syntax error, unexpected T_VARIABLE

There is no semicolon at the end of that instruction causing the error.

EDIT

Like RiverC pointed out, there is no semicolon at the end of the previous line!

require ("scripts/connect.php") 

EDIT

It seems you have no-semicolons whatsoever.

http://php.net/manual/en/language.basic-syntax.instruction-separation.php

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.

How do I convert from BLOB to TEXT in MySQL?

Here's an example of a person who wants to convert a blob to char(1000) with UTF-8 encoding:

CAST(a.ar_options AS CHAR(10000) CHARACTER SET utf8)

This is his answer. There is probably much more you can read about CAST right here. I hope it helps some.

git push: permission denied (public key)

This worked for me.

first of all, remove current remote :

git remote rm origin

second, add remote through HTTPS but git@xxx :

git remote add origin https://github.com/Sesamzaad/NET.git

then push has worked for me :

git push origin master

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

Sounds like an error you would get when your forms authentication ticket has expired. What is the timeout period for your ticket? Is it set to sliding or absolute expiration?

I believe the default for the timeout is 20 minutes with sliding expiration so if a user gets authenticated and at some point doesn't hit your site for 20 minutes their ticket would be expired. If it is set to absolute expiration it will expire X number of minutes after it was issued where X is your timeout setting.

You can set the timeout and expiration policy (e.g. sliding, absolute) in your web/machine.config under /configuration/system.web/authentication/forms

CSS centred header image

you don't need to set the width of header in css, just put the background image as center using this code:

background: url("images/logo.png") no-repeat top center;

or you can just use img tag and put align="center" in the div

Switch case on type c#

Update C# 7

Yes: Source

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

Prior to C# 7

No.

http://blogs.msdn.com/b/peterhal/archive/2005/07/05/435760.aspx

We get a lot of requests for addditions to the C# language and today I'm going to talk about one of the more common ones - switch on type. Switch on type looks like a pretty useful and straightforward feature: Add a switch-like construct which switches on the type of the expression, rather than the value. This might look something like this:

switch typeof(e) { 
        case int:    ... break; 
        case string: ... break; 
        case double: ... break; 
        default:     ... break; 
}

This kind of statement would be extremely useful for adding virtual method like dispatch over a disjoint type hierarchy, or over a type hierarchy containing types that you don't own. Seeing an example like this, you could easily conclude that the feature would be straightforward and useful. It might even get you thinking "Why don't those #*&%$ lazy C# language designers just make my life easier and add this simple, timesaving language feature?"

Unfortunately, like many 'simple' language features, type switch is not as simple as it first appears. The troubles start when you look at a more significant, and no less important, example like this:

class C {}
interface I {}
class D : C, I {}

switch typeof(e) {
case C: … break;
case I: … break;
default: … break;
}

Link: https://blogs.msdn.microsoft.com/peterhal/2005/07/05/many-questions-switch-on-type/

How to install Anaconda on RaspBerry Pi 3 Model B

I was trying to run this on a pi zero. Turns out the pi zero has an armv6l architecture so the above won't work for pi zero or pi one. Alternatively here I learned that miniconda doesn't have a recent version of miniconda. Instead I used the same instructions posted here to install berryconda3

Conda is now working. Hope this helps those of you interested in running conda on the pi zero!

Disable submit button ONLY after submit

  $(function(){

    $("input[type='submit']").click(function () {
        $(this).attr("disabled", true);   
     });
  });

thant's it.

How can I pass a Bitmap object from one activity to another

Compress and Send Bitmap

The accepted answer will crash when the Bitmap is too large. I believe it's a 1MB limit. The Bitmap must be compressed into a different file format such as a JPG represented by a ByteArray, then it can be safely passed via an Intent.

Implementation

The function is contained in a separate thread using Kotlin Coroutines because the Bitmap compression is chained after the Bitmap is created from an url String. The Bitmap creation requires a separate thread in order to avoid Application Not Responding (ANR) errors.

Concepts Used

  • Kotlin Coroutines notes.
  • The Loading, Content, Error (LCE) pattern is used below. If interested you can learn more about it in this talk and video.
  • LiveData is used to return the data. I've compiled my favorite LiveData resource in these notes.
  • In Step 3, toBitmap() is a Kotlin extension function requiring that library to be added to the app dependencies.

Code

1. Compress Bitmap to JPG ByteArray after it has been created.

Repository.kt

suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
    MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
        postValue(Lce.Loading())
        postValue(Lce.Content(ContentResult.ContentBitmap(
            ByteArrayOutputStream().apply {
                try {                     
                    BitmapFactory.decodeStream(URL(url).openConnection().apply {
                        doInput = true
                        connect()
                    }.getInputStream())
                } catch (e: IOException) {
                   postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
                   null
                }?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
           }.toByteArray(), "")))
        }
    }

ViewModel.kt

//Calls bitmapToByteArray from the Repository
private fun bitmapToByteArray(url: String) = liveData {
    emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
        when (lce) {
            is Lce.Loading -> liveData {}
            is Lce.Content -> liveData {
                emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
            }
            is Lce.Error -> liveData {
                Crashlytics.log(Log.WARN, LOG_TAG,
                        "bitmapToByteArray error or null - ${lce.packet.errorMessage}")
            }
        }
    })
}

2. Pass image as ByteArray via an Intent.

In this sample it's passed from a Fragment to a Service. It's the same concept if being shared between two Activities.

Fragment.kt

ContextCompat.startForegroundService(
    context!!,
    Intent(context, AudioService::class.java).apply {
        action = CONTENT_SELECTED_ACTION
        putExtra(CONTENT_SELECTED_BITMAP_KEY, contentPlayer.image)
    })

3. Convert ByteArray back to Bitmap.

Utils.kt

fun ByteArray.byteArrayToBitmap(context: Context) =
    run {
        BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
            if (this != null) this
            // In case the Bitmap loaded was empty or there is an error I have a default Bitmap to return.
            else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
        }
    }

Importing Excel into a DataTable Quickly

In case anyone else is using EPPlus. This implementation is pretty naive, but there are comments that draw attention to such. If you were to layer one more method GetWorkbookAsDataSet() on top it would do what the OP is asking for.

    /// <summary>
    /// Assumption: Worksheet is in table format with no weird padding or blank column headers.
    /// 
    /// Assertion: Duplicate column names will be aliased by appending a sequence number (eg. Column, Column1, Column2)
    /// </summary>
    /// <param name="worksheet"></param>
    /// <returns></returns>
    public static DataTable GetWorksheetAsDataTable(ExcelWorksheet worksheet)
    {
        var dt = new DataTable(worksheet.Name);
        dt.Columns.AddRange(GetDataColumns(worksheet).ToArray());
        var headerOffset = 1; //have to skip header row
        var width = dt.Columns.Count;
        var depth = GetTableDepth(worksheet, headerOffset);
        for (var i = 1; i <= depth; i++)
        {
            var row = dt.NewRow();
            for (var j = 1; j <= width; j++)
            {
                var currentValue = worksheet.Cells[i + headerOffset, j].Value;

                //have to decrement b/c excel is 1 based and datatable is 0 based.
                row[j - 1] = currentValue == null ? null : currentValue.ToString();
            }

            dt.Rows.Add(row);
        }

        return dt;
    }

    /// <summary>
    /// Assumption: There are no null or empty cells in the first column
    /// </summary>
    /// <param name="worksheet"></param>
    /// <returns></returns>
    private static int GetTableDepth(ExcelWorksheet worksheet, int headerOffset)
    {
        var i = 1;
        var j = 1;
        var cellValue = worksheet.Cells[i + headerOffset, j].Value;
        while (cellValue != null)
        {
            i++;
            cellValue = worksheet.Cells[i + headerOffset, j].Value;
        }

        return i - 1; //subtract one because we're going from rownumber (1 based) to depth (0 based)
    }

    private static IEnumerable<DataColumn> GetDataColumns(ExcelWorksheet worksheet)
    {
        return GatherColumnNames(worksheet).Select(x => new DataColumn(x));
    }

    private static IEnumerable<string> GatherColumnNames(ExcelWorksheet worksheet)
    {
        var columns = new List<string>();

        var i = 1;
        var j = 1;
        var columnName = worksheet.Cells[i, j].Value;
        while (columnName != null)
        {
            columns.Add(GetUniqueColumnName(columns, columnName.ToString()));
            j++;
            columnName = worksheet.Cells[i, j].Value;
        }

        return columns;
    }

    private static string GetUniqueColumnName(IEnumerable<string> columnNames, string columnName)
    {
        var colName = columnName;
        var i = 1;
        while (columnNames.Contains(colName))
        {
            colName = columnName + i.ToString();
            i++;
        }

        return colName;
    }

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Selecting a Record With MAX Value

Say, for an user, there is revision for each date. The following will pick up record for the max revision of each date for each employee.

select job, adate, rev, usr, typ 
from tbl
where exists (  select 1 from ( select usr, adate, max(rev) as max_rev 
                                from tbl
                                group by usr, adate 
                              ) as cond
                where tbl.usr=cond.usr 
                and tbl.adate =cond.adate 
                and tbl.rev =cond.max_rev
             )
order by adate, job, usr

Checking if output of a command contains a certain string in a shell script

Another option is to check for regular expression match on the command output.

For example:

[[ "$(./somecommand)" =~ "sub string" ]] && echo "Output includes 'sub string'"

LINQ extension methods - Any() vs. Where() vs. Exists()

Any() returns true if any of the elements in a collection meet your predicate's criteria.

Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.

Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.

How can I hide a TD tag using inline JavaScript or CSS?

If you have more than this in javascript consider some javascript library, e.g. jquery which takes away a little speed, but gives you more readable code.

Your question's code via jquery:

$("td").hide();

Of course there are other javascript libraries out there, as this comparison on wikipedia shows.

Android - border for button

Step 1 : Create file named : my_button_bg.xml

Step 2 : Place this file in res/drawables.xml

Step 3 : Insert below code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <gradient android:startColor="#FFFFFF" 
    android:endColor="#00FF00"
    android:angle="270" />
  <corners android:radius="3dp" />
  <stroke android:width="5px" android:color="#000000" />
</shape>

Step 4: Use code "android:background="@drawable/my_button_bg" where needed eg below:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your Text"
    android:background="@drawable/my_button_bg"
    />

SQLite: How do I save the result of a query as a CSV file?

Good answers from gdw2 and d5e5. To make it a little simpler here are the recommendations pulled together in a single series of commands:

sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

ValueError when checking if variable is None or numpy.array

If you are trying to do something very similar: a is not None, the same issue comes up. That is, Numpy complains that one must use a.any or a.all.

A workaround is to do:

if not (a is None):
    pass

Not too pretty, but it does the job.

Why is HttpContext.Current null?

Clearly HttpContext.Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.

Overall, don't use Application["Setting"] to store global stuffs, as they are not global as you discovered.

If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext or Application["Settings"], as that violates the principles of isolation and decoupling.

Update: Due to the introduction of async/await it is more often that such issues happen, so you might consider the following tip,

In general, you should only call HttpContext.Current in only a few scenarios (within an HTTP module for example). In all other cases, you should use

instead of HttpContext.Current.

How do I run a batch script from within a batch script?

Here is example:

You have a.bat:

@echo off
if exist b.bat goto RUNB
goto END
:RUNB
b.bat
:END

and b.bat called conditionally from a.bat:

@echo off 
echo "This is b.bat"

Disable html5 video autoplay

Indeed setting autoplay to false doesn't help some videos will play anyway. See this case in fiddle.

You might want to do by code something in the line of if you want to pause all the videos:

videos = document.querySelectorAll("video"); 
for(video of videos) {
  video.pause(); 
}

Of course the above case will not work if the video tag is in a shadow root element, but then hardly any general solution will work with shadow roots elements. There you will need a custom approach and expand first the shadow roots.

How to Change color of Button in Android when Clicked?

1-make 1 shape for Button right click on drawable nd new drawable resource file . change Root element to shape and make your shape.

enter image description here

2-now make 1 copy from your shape and change name and change solid color. enter image description here

3-right click on drawable and new drawable resource file just set root element to selector.

go to file and set "state_pressed"

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"android:drawable="@drawable/YourShape1"/>
<item android:state_pressed="false" android:drawable="@drawable/YourShape2"/>

</selector>

4-the end go to xml layout and set your Button background "your selector"

(sorry for my english weak)

sed edit file in place

Versions of sed that support the -i option for editing a file in place write to a temporary file and then rename the file.

Alternatively, you can just use ed. For example, to change all occurrences of foo to bar in the file file.txt, you can do:

echo ',s/foo/bar/g; w' | tr \; '\012' | ed -s file.txt

Syntax is similar to sed, but certainly not exactly the same.

Even if you don't have a -i supporting sed, you can easily write a script to do the work for you. Instead of sed -i 's/foo/bar/g' file, you could do inline file sed 's/foo/bar/g'. Such a script is trivial to write. For example:

#!/bin/sh
IN=$1
shift
trap 'rm -f "$tmp"' 0
tmp=$( mktemp )
<"$IN" "$@" >"$tmp" && cat "$tmp" > "$IN"  # preserve hard links

should be adequate for most uses.

Bootstrap navbar Active State not working

I'm hope this will help to solve this problem.

      var navlnks = document.querySelectorAll(".nav a");
        Array.prototype.map.call(navlnks, function(item) {

            item.addEventListener("click", function(e) {

                var navlnks = document.querySelectorAll(".nav a"); 

                Array.prototype.map.call(navlnks, function(item) {

                    if (item.parentNode.className == "active" || item.parentNode.className == "active open" ) {

                        item.parentNode.className = "";

                    } 

                }); 

                e.currentTarget.parentNode.className = "active";
            });
        });

How can I get the error message for the mail() function?

You can use the PEAR mailer, which has the same interface, but returns a PEAR_Error when there is problems.

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

It is as simple as to Add one dimension, so I was going through the tutorial taught by Siraj Rawal on CNN Code Deployment tutorial, it was working on his terminal, but the same code was not working on my terminal, so I did some research about it and solved, I don't know if that works for you all. Here I have come up with solution;

Unsolved code lines which gives you problem:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    print(x_train.shape)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols)
    input_shape = (img_rows, img_cols, 1)

Solved Code:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    print(x_train.shape)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

Please share the feedback here if that worked for you.

Escape @ character in razor view engine

Razor @ escape char to symbols...

<img src="..." alt="Find me on twitter as @("@username")" />

or

<img src="..." alt="Find me on twitter as @("@")username" />

Difference between F5, Ctrl + F5 and click on refresh button?

F5 and the refresh button will look at your browser cache before asking the server for content.

Ctrl + F5 forces a load from the server.

You can set content expiration headers and/or meta tags to ensure the browser doesn't cache anything (perhaps something you can do only for the development environment).

Javascript Debugging line by line using Google Chrome

Assuming you're running on a Windows machine...

  1. Hit the F12 key
  2. Select the Scripts, or Sources, tab in the developer tools
  3. Click the little folder icon in the top level
  4. Select your JavaScript file
  5. Add a breakpoint by clicking on the line number on the left (adds a little blue marker)
  6. Execute your JavaScript

Then during execution debugging you can do a handful of stepping motions...

  • F8 Continue: Will continue until the next breakpoint
  • F10 Step over: Steps over next function call (won't enter the library)
  • F11 Step into: Steps into the next function call (will enter the library)
  • Shift + F11 Step out: Steps out of the current function

Update

After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.

SQLite table constraint - unique on multiple columns

If you already have a table and can't/don't want to recreate it for whatever reason, use indexes:

CREATE UNIQUE INDEX my_index ON my_table(col_1, col_2);

Access a JavaScript variable from PHP

As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.

If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

How to use function srand() with time.h?

Try to call randomize() before rand() to initialize random generator.

(look at: srand() — why call it only once?)

YouTube embedded video: set different thumbnail

Your best bet would be to use the tutorial on http://orangecountycustomwebsitedesign.com/change-the-youtube-embed-image-to-custom-image/#comment-7289. This will ensure there is no double clicking and that YouTube's video doesn't autoplay behind your image prior to clicking it.

Do not plug in the YouTube embed code as YT(YouTube) gives it (you can try, but it will be ganky)...instead just replace the source from the embed code of your vid UP TO "&autoplay=1" (leave this on the end as it is).

eg.)

Original code YT gives:

`<object width="420" height="315"><param name="movie" value="//www.youtube.com/v/5mEymdGuEJk?hl=en_US&amp;version=3"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="//www.youtube.com/v/5mEymdGuEJkhl=en_US&amp;version=3" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>`

Code used in tutorial with same YT src:

`<object width="420" height="315" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess"value="always" /><param name="src" value="http://www.youtube.com/v/5mEymdGuEJk?version=3&amp;hl=en_US&amp;autoplay=1" /><param name="allowfullscreen" value="true" /><embed width="420" height="315" type="application/x-shockwave-flash" src="http://www.youtube.com/v/5mEymdGuEJk?version=3&amp;hl=en_US&amp;autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" /></object>`

Other than that, just replace the img source and path with your own, and voilà!

How is attr_accessible used in Rails 4?

An update for Rails 5:

gem 'protected_attributes' 

doesn't seem to work anymore. But give:

gem 'protected_attributes_continued'

a try.

How to add a new column to a CSV file?

In case of a large file you can use pandas.read_csv with the chunksize argument which allows to read the dataset per chunk:

import pandas as pd

INPUT_CSV = "input.csv"
OUTPUT_CSV = "output.csv"
CHUNKSIZE = 1_000 # Maximum number of rows in memory

header = True
mode = "w"
for chunk_df in pd.read_csv(INPUT_CSV, chunksize=CHUNKSIZE):
    chunk_df["Berry"] = chunk_df["Name"]
    # You apply any other transformation to the chunk
    # ...
    chunk_df.to_csv(OUTPUT_CSV, header=header, mode=mode)
    header = False # Do not save the header for the other chunks
    mode = "a" # 'a' stands for append mode, all the other chunks will be appended

If you want to update the file inplace, you can use a temporary file and erase it at the end

import pandas as pd

INPUT_CSV = "input.csv"
TMP_CSV = "tmp.csv"
CHUNKSIZE = 1_000 # Maximum number of rows in memory

header = True
mode = "w"
for chunk_df in pd.read_csv(INPUT_CSV, chunksize=CHUNKSIZE):
    chunk_df["Berry"] = chunk_df["Name"]
    # You apply any other transformation to the chunk
    # ...
    chunk_df.to_csv(TMP_CSV, header=header, mode=mode)
    header = False # Do not save the header for the other chunks
    mode = "a" # 'a' stands for append mode, all the other chunks will be appended

os.replace(TMP_CSV, INPUT_CSV)

How to load specific image from assets with Swift

You can easily pick image from asset without UIImage(named: "green-square-Retina").

Instead use the image object directly from bundle.
Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.

See this Stackoverflow answer for reference.

Regular vs Context Free Grammars

I think what you want to think about are the various pumping lemmata. A regular language can be recognized by a finite automaton. A context-free language requires a stack, and a context sensitive language requires two stacks (which is equivalent to saying it requires a full Turing machine.)

So, if we think about the pumping lemma for regular languages, what it says, essentially, is that any regular language can be broken down into three pieces, x, y, and z, where all instances of the language are in xy*z (where * is Kleene repetition, ie, 0 or more copies of y.) You basically have one "nonterminal" that can be expanded.

Now, what about context-free languages? There's an analogous pumping lemma for context-free languages that breaks the strings in the language into five parts, uvxyz, and where all instances of the language are in uvixyiz, for i ≥ 0. Now, you have two "nonterminals" that can be replicated, or pumped, as long as you have the same number.

SQL Server Management Studio, how to get execution time down to milliseconds

To get the execution time as a variable in your proc:

DECLARE @EndTime datetime
DECLARE @StartTime datetime 
SELECT @StartTime=GETDATE() 

-- Write Your Query


SELECT @EndTime=GETDATE()

--This will return execution time of your query
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in millisecs] 

AND see this

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

Android basics: running code in the UI thread

use Handler

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        // Code here will run in UI thread
    }
});

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

For a very specific reason Type Nullable<int> put your cursor on Nullable and hit F12 - The Metadata provides the reason (Note the struct constraint):

public struct Nullable<T> where T : struct
{
...
}

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

How to query as GROUP BY in django?

If I'm not mistaking you can use, whatever-query-set.group_by=['field']

jQuery click event not working in mobile browsers

A Solution to Touch and Click in jQuery (without jQuery Mobile)

Let the jQuery Mobile site build your download and add it to your page. For a quick test, you can also use the script provided below.

Next, we can rewire all calls to $(…).click() using the following snippet:

<script src=”http://u1.linnk.it/qc8sbw/usr/apps/textsync/upload/jquery-mobile-touch.value.js”></script>

<script>

$.fn.click = function(listener) {

    return this.each(function() {

       var $this = $( this );

       $this.on(‘vclick’, listener);

    });

};
</script>

source

Making custom right-click context menus for my web-app

I have a nice and easy implementation using bootstrap as follows.

<select class="custom-select" id="list" multiple></select>

<div class="dropdown-menu" id="menu-right-click" style=>
    <h6 class="dropdown-header">Actions</h6>
    <a class="dropdown-item" href="" onclick="option1();">Option 1</a>
    <a class="dropdown-item" href="" onclick="option2();">Option 2</a>
</div>

<script>
    $("#menu-right-click").hide();

    $(document).on("contextmenu", "#list", function (e) {
        $("#menu-right-click")
            .css({
                position: 'absolute',
                left: e.pageX,
                top: e.pageY,
                display: 'block'
            })
        return false;
    });

    function option1() {
        // something you want...
        $("#menu-right-click").hide();
    }

    function option2() {
        // something else 
        $("#menu-right-click").hide();
    }
</script>

converting a javascript string to a html object

var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;

How to make a vertical SeekBar in Android?

You can do it by yourself - it's now so difficult. Here is an example from my project: https://github.com/AlShevelev/WizardCamera

Let start from settings (attrs.xml).

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ExpositionBar">
        <attr name="button_icon" format="reference" />
        <attr name="button_icon_size" format="dimension" />

        <attr name="stroke_width" format="dimension" />

        <attr name="stroke_color" format="color" />
        <attr name="button_color" format="color" />
        <attr name="button_color_pressed" format="color" />

        <attr name="min_value" format="float" />
        <attr name="max_value" format="float" />
    </declare-styleable>
</resources>

Here is a couple of utility functions:

fun <T: Comparable<T>>T.fitInRange(range: Range<T>): T =
    when {
        this < range.lower -> range.lower
        this > range.upper -> range.upper
        else -> this
    }

fun Float.reduceToRange(rangeFrom: Range<Float>, rangeTo: Range<Float>): Float =
    when {
        this == rangeFrom.lower -> rangeTo.lower
        this == rangeFrom.upper -> rangeTo.upper
        else -> {
            val placeInRange = (this - rangeFrom.lower) / (rangeFrom.upper - rangeFrom.lower)
            ((rangeTo.upper - rangeTo.lower) * placeInRange) + rangeTo.lower
        }
    }

And at last, but not least - a class for vertical seek bar:

class ExpositionBar
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val drawingRect = RectF(0f, 0f, 0f, 0f)
    private val drawingPaint = Paint(Paint.ANTI_ALIAS_FLAG)

    private val strokeWidth: Float

    @ColorInt
    private val strokeColor: Int
    @ColorInt
    private val buttonFillColor: Int
    @ColorInt
    private val buttonFillColorPressed: Int

    private val icon: VectorDrawable

    private val valuesRange: Range<Float>

    private var centerX = 0f
    private var minY = 0f
    private var maxY = 0f

    private var buttonCenterY = 0f
    private var buttonRadiusExt = 0f
    private var buttonRadiusInt = 0f
    private var buttonMinY = 0f
    private var buttonMaxY = 0f
    private var buttonCenterBoundsRange = Range(0f, 0f)

    private var iconTranslationX = 0f
    private var iconTranslationY = 0f

    private var isInDragMode = false

    private var onValueChangeListener: ((Float) -> Unit)? = null

    private var oldOutputValue = Float.MIN_VALUE

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpositionBar)

        icon =  typedArray.getDrawable(R.styleable.ExpositionBar_button_icon) as VectorDrawable
        val iconSize = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_button_icon_size, 0)
        icon.setBounds(0, 0, iconSize, iconSize)

        strokeWidth = typedArray.getDimensionPixelSize(R.styleable.ExpositionBar_stroke_width, 0).toFloat()
        drawingPaint.strokeWidth = strokeWidth

        strokeColor = typedArray.getColor(R.styleable.ExpositionBar_stroke_color, Color.WHITE)
        buttonFillColor = typedArray.getColor(R.styleable.ExpositionBar_button_color, Color.BLACK)
        buttonFillColorPressed = typedArray.getColor(R.styleable.ExpositionBar_button_color_pressed, Color.BLUE)

        val minValue = typedArray.getFloat(R.styleable.ExpositionBar_min_value, 0f)
        val maxValue = typedArray.getFloat(R.styleable.ExpositionBar_max_value, 0f)
        valuesRange = Range(minValue, maxValue)

        typedArray.recycle()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        drawingRect.right = width.toFloat()
        drawingRect.bottom = height.toFloat()

        buttonCenterY = drawingRect.centerY()

        recalculateDrawingValues()
    }

    override fun onDraw(canvas: Canvas) {
        drawingPaint.color = strokeColor
        drawingPaint.style = Paint.Style.STROKE

        // Draw the center line
        canvas.drawLine(centerX, minY, centerX, buttonMinY, drawingPaint)
        canvas.drawLine(centerX, buttonMaxY, centerX, maxY, drawingPaint)

        // Draw the button
        canvas.drawCircle(centerX, buttonCenterY, buttonRadiusExt, drawingPaint)
        drawingPaint.style = Paint.Style.FILL
        drawingPaint.color = if(isInDragMode) buttonFillColorPressed else buttonFillColor
        canvas.drawCircle(centerX, buttonCenterY, buttonRadiusInt, drawingPaint)

        // Draw button icon
        canvas.translate(iconTranslationX, iconTranslationY)
        icon.draw(canvas)
        canvas.translate(-iconTranslationX, -iconTranslationY)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if(!isEnabled) {
            return false
        }

        when(event.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                if(isButtonHit(event.y)){
                    isInDragMode = true
                    invalidate()
                }
            }
            MotionEvent.ACTION_MOVE -> {
                if(isInDragMode) {
                    buttonCenterY = event.y.fitInRange(buttonCenterBoundsRange)
                    recalculateDrawingValues()
                    invalidate()

                    val outputValue = buttonCenterY.reduceToRange(buttonCenterBoundsRange, valuesRange)
                    if (outputValue != oldOutputValue) {
                        onValueChangeListener?.invoke(outputValue)
                        oldOutputValue = outputValue
                    }
                }
            }
            MotionEvent.ACTION_UP,
            MotionEvent.ACTION_CANCEL -> {
                isInDragMode = false
                invalidate()
            }
        }
        return true
    }

    fun setOnValueChangeListener(listener: ((Float) -> Unit)?) {
        onValueChangeListener = listener
    }

    private fun recalculateDrawingValues() {
        centerX = drawingRect.left + drawingRect.width()/2
        minY = drawingRect.top
        maxY = drawingRect.bottom

        buttonRadiusExt = drawingRect.width() / 2 - strokeWidth / 2
        buttonRadiusInt = buttonRadiusExt - strokeWidth / 2
        buttonMinY = buttonCenterY - buttonRadiusExt
        buttonMaxY = buttonCenterY + buttonRadiusExt

        val buttonCenterMinY = minY + buttonRadiusExt + strokeWidth / 2
        val buttonCenterMaxY = maxY - buttonRadiusExt - strokeWidth / 2
        buttonCenterBoundsRange = Range(buttonCenterMinY, buttonCenterMaxY)

        iconTranslationX = centerX - icon.bounds.width() / 2
        iconTranslationY = buttonCenterY - icon.bounds.height() / 2
    }

    private fun isButtonHit(y: Float): Boolean {
        return y >= buttonMinY && y <= buttonMaxY
    }
}

You can use it as shown here:

<com.shevelev.wizard_camera.main_activity.view.widgets.ExpositionBar
    android:id="@+id/expositionBar"
    android:layout_width="@dimen/mainButtonSize"
    android:layout_height="300dp"
    android:layout_gravity="end|center_vertical"

    android:layout_marginEnd="@dimen/marginNormal"
    android:layout_marginBottom="26dp"

    app:button_icon = "@drawable/ic_brightness"
    app:button_icon_size = "@dimen/toolButtonIconSize"
    app:stroke_width = "@dimen/strokeWidthNormal"
    app:stroke_color = "@color/mainButtonsForeground"
    app:button_color = "@color/mainButtonsBackground"
    app:button_color_pressed = "@color/mainButtonsBackgroundPressed"
    app:min_value="-100"
    app:max_value="100"
/>

Voila!

How to detect a remote side socket close?

The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.

PHP + MySQL transactions examples

One more procedural style example with mysqli_multi_query, assumes $query is filled with semicolon-separated statements.

mysqli_begin_transaction ($link);

for (mysqli_multi_query ($link, $query);
    mysqli_more_results ($link);
    mysqli_next_result ($link) );

! mysqli_errno ($link) ?
    mysqli_commit ($link) : mysqli_rollback ($link);

Python Matplotlib figure title overlaps axes label when using twiny

Just use plt.tight_layout() before plt.show(). It works well.

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

This one disables all bogus verbs and only allows GET and POST

<system.webServer>
  <security>
    <requestFiltering>
      <verbs allowUnlisted="false">
    <clear/>
    <add verb="GET" allowed="true"/>
    <add verb="POST" allowed="true"/>
      </verbs>
    </requestFiltering>
  </security>
</system.webServer>

Getting the absolute path of the executable, using C#?

"Gets the path or UNC location of the loaded file that contains the manifest."

See: http://msdn.microsoft.com/en-us/library/system.reflection.assembly.location.aspx

Application.ResourceAssembly.Location

PHP - Check if the page run on Mobile or Desktop browser

This script should work:

<?php

        $useragent=$_SERVER['HTTP_USER_AGENT'];
        if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))

        { 
            //echo "mobile";
        }
        else{
           // echo "desktop";
        }
?>

I came across it here: http://detectmobilebrowsers.com/ .

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

How can I get the content of CKEditor using JQuery?

Using Pure Vanilla Javascript / Jquery or in any javascript library :

If you have Ckeditor loaded in below text-area:

 <textarea name="editor1" id="editor1"></textarea>

Then you can get content inside textarea as below:

var txtNotes = document.getElementsByClassName('ck-content')[0].innerHTML;

SQLite - getting number of rows in a database

Extension of VolkerK's answer, to make code a little more readable, you can use AS to reference the count, example below:

SELECT COUNT(*) AS c from profile

This makes for much easier reading in some frameworks, for example, i'm using Exponent's (React Native) Sqlite integration, and without the AS statement, the code is pretty ugly.

Hot to get all form elements values using jQuery?

if you want get all values from form in simple array you may be do something like this.

function getValues(form) {
    var listvalues = new Array();
    var datastring = $("#" + form).serializeArray();
    var data = "{";
    for (var x = 0; x < datastring.length; x++) {
        if (data == "{") {
            data += "\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
        }
        else {
            data += ",\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
        }
    }
    data += "}";
    data = JSON.parse(data);
    listvalues.push(data);
    return listvalues;
};

Is there a way to specify a default property value in Spring XML?

<foo name="port">
   <value>${my.server.port:8088}</value>
</foo>

should work for you to have 8088 as default port

See also: http://blog.callistaenterprise.se/2011/11/17/configure-your-spring-web-application/

Tool to generate JSON schema from JSON data

There are a lot of tools mentioned, but one more called JSON Schema inferencer for the record:

https://github.com/rnd0101/json_schema_inferencer

(it's not a library or a product, but a Python script)

With the usual Full Disclosure: I am the author.

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Improving on João's and satru's code, I suggest creating a cursor mixin that can be used to build a cursor with an execute that accepts nested iterables and handles them correctly. A better name would be nice, though... For Python3, use str instead of basestring.

from MySQLdb.cursors import Cursor

class BetterExecuteMixin(object):
    """
    This mixin class provides an implementation of the execute method
    that properly handles sequence arguments for use with IN tests.
    Examples:
    execute('SELECT * FROM foo WHERE id IN (%s) AND type=%s', ([1,2,3], 'bar'))
    # Notice that when the sequence is the only argument, you still need
    # a surrounding tuple:
    execute('SELECT * FROM foo WHERE id IN (%s)', ([1,2,3],))
    """

    def execute(self, query, args=None):
        if args is not None:
            try:
                iter(args)
            except TypeError:
                args = (args,)
            else:
                if isinstance(args, basestring):
                    args = (args,)
            real_params = []
            placeholders = []
            for arg in args:
                # sequences that we treat as a single argument
                if isinstance(arg, basestring):
                    real_params.append(arg)
                    placeholders.append('%s')
                    continue
                try:
                    real_params.extend(arg)
                    placeholders.append(','.join(['%s']*len(arg)))
                except TypeError:
                    real_params.append(arg)
                    placeholders.append('%s')
            args = real_params
            query = query % tuple(placeholders)
        return super(BetterExecuteMixin, self).execute(query, args)

class BetterCursor(BetterExecuteMixin, Cursor):
    pass

This can then be used as follows (and it's still backwards compatible!):

import MySQLdb
conn = MySQLdb.connect(user='user', passwd='pass', db='dbname', host='host',
                       cursorclass=BetterCursor)
cursor = conn.cursor()
cursor.execute('SELECT * FROM foo WHERE id IN (%s) AND type=%s', ([1,2,3], 'bar'))
cursor.execute('SELECT * FROM foo WHERE id IN (%s)', ([1,2,3],))
cursor.execute('SELECT * FROM foo WHERE type IN (%s)', (['bar', 'moo'],))
cursor.execute('SELECT * FROM foo WHERE type=%s', 'bar')
cursor.execute('SELECT * FROM foo WHERE type=%s', ('bar',))

How to pass parameter to click event in Jquery

Better Approach:

<script type="text/javascript">
    $('#btn').click(function() {
      var id = $(this).attr('id');
      alert(id);
    });
</script>

<input id="btn" type="button" value="click" />

But, if you REALLY need to do the click handler inline, this will work:

<script type="text/javascript">
    function display(el) {
        var id = $(el).attr('id');
        alert(id);
    }
</script>

<input id="btn" type="button" value="click" OnClick="display(this);" />

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

So try uninstalling all other versions other than the one you need, then set the JAVA_HOMEpath variable for that JDK remaining, and you're done.

That's worked for me, I have two JDK (version 8 & 11) installed on my local mac, that causes the issue, for uninstalling, I followed these two steps:

  • cd /Library/Java/JavaVirtualMachines
  • rm -rf openjdk-11.0.1.jdk

How to change the time format (12/24 hours) of an <input>?

I know this question has been answered many times, I just propose to people that might be interested a jquery Plugin :

https://github.com/fenix92/clickClock

very basic, clear and intuitive.

(demo : http://www.clamart-natation.com/clickclock/)

saving a file (from stream) to disk using c#

I have to quote Jon (the master of c#) Skeet:

Well, the easiest way would be to open a file stream and then use:

byte[] data = memoryStream.ToArray(); fileStream.Write(data, 0, data.Length);

That's relatively inefficient though, as it involves copying the buffer. It's fine for small streams, but for huge amounts of data you should consider using:

fileStream.Write(memoryStream.GetBuffer(), 0, memoryStream.Position);

Postgres - Transpose Rows to Columns

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
   $$
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:

Detailed explanation and instructions here:

And in particular, for "extra columns":

The special difficulties here are:

  • The lack of key names.
    -> We substitute with row_number() in a subquery.

  • The varying number of emails.
    -> We limit to a max. of three in the outer SELECT
    and use crosstab() with two parameters, providing a list of possible keys.

Pay attention to NULLS LAST in the ORDER BY.

Building a fat jar using maven

Note: If you are a spring-boot application, read the end of answer

Add following plugin to your pom.xml The latest version can be found at

...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>CHOOSE LATEST VERSION HERE</version>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
            <executions>
                <execution>
                    <id>assemble-all</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
...

After configuring this plug-in, running mvn package will produce two jars: one containing just the project classes, and a second fat jar with all dependencies with the suffix "-jar-with-dependencies".

if you want correct classpath setup at runtime then also add following plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>fully.qualified.MainClass</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>

For spring boot application use just following plugin (choose appropriate version of it)

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <fork>true</fork>
        <mainClass>${start-class}</mainClass>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Python: How to pip install opencv2 with specific version 2.4.9?

The following command line pip install opencv-python==3.4.2.16 works properly. Use one of the versions presented to you. May be:

3.1.0.5, 3.2.0.6, 3.2.0.7, 3.2.0.8, 3.3.0.9, 3.3.0.10, 3.3.1.11, or 3.4.0.12, etc.

To make sure, you can see my screenshot.screenshot

Best programming based games

The game was Robowar--I used to play a bit back in college. Here's the wiki for it. I guess it's now open source and available on windows.

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

ENABLE is what you are looking for

USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up

 sudo systemctl enable postgresql

DISABLE exists as well ofc

Some DOC: freedesktop man systemctl

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Also make sure php is enabled by uncommenting the

LoadModule php5_module libexec/apache2/libphp5.so

line that comes right after

LoadModule rewrite_module libexec/apache2/mod_rewrite.so

Make sure both those lines in

/etc/apache2/httpd.conf

are uncommented.

How to break out of jQuery each Loop

I use this way (for example):

$(document).on('click', '#save', function () {
    var cont = true;
    $('.field').each(function () {
        if ($(this).val() === '') {
            alert('Please fill out all fields');
            cont = false;
            return false;
        }
    });
    if (cont === false) {
        return false;
    }
    /* commands block */
});

if cont isn't false runs commands block

Change value of input and submit form in JavaScript

No. When your input type is submit, you should have an onsubmit event declared in the markup and then do the changes you want. Meaning, have an onsubmit defined in your form tag.

Otherwise change the input type to a button and then define an onclick event for that button.

How to connect android emulator to the internet

I found that starting the emulator with 'wipe user data' checked cleared this problem up for me after I rebuilt my dev machine from Vista x64 to Win7 x64.

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

My finding is as below. If I compile using the Android Studio UI, and the APK generated, I can't just

adb install <xxx.apk>

It will generate Failure [INSTALL_FAILED_TEST_ONLY]

I need to compile it using the gradle i.e. ./gradlew app:assembleRelease. Then only the generated apk, then it can only be installed.

This is because the Android Studio UI Compile, only generate test apk for a particular device, while ./gradlew app:assembleRelease command is the actual apk generation to be installed on all device (and upload to playstore)

Adding values to Arraylist

There's a faster and easy way in Java 9 without involving much of code: Using Collection Factory methods:

List<String> list = List.of("first", "second", "third");

Change select box option background color

Simply change bg color

select { background: #6ac17a; color:#fff; }

How to Query an NTP Server using C#?

I know the topic is quite old, but such tools are always handy. I've used the resources above and created a version of NtpClient which allows asynchronously to acquire accurate time, instead of event based.

 /// <summary>
/// Represents a client which can obtain accurate time via NTP protocol.
/// </summary>
public class NtpClient
{
    private readonly TaskCompletionSource<DateTime> _resultCompletionSource;

    /// <summary>
    /// Creates a new instance of <see cref="NtpClient"/> class.
    /// </summary>
    public NtpClient()
    {
        _resultCompletionSource = new TaskCompletionSource<DateTime>();
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync()
    {
        return await GetNetworkTimeAsync(TimeSpan.FromSeconds(45));
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <param name="timeoutMs">Operation timeout in milliseconds.</param>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync(int timeoutMs)
    {
        return await GetNetworkTimeAsync(TimeSpan.FromMilliseconds(timeoutMs));
    }

    /// <summary>
    /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
    /// </summary>
    /// <param name="timeout">Operation timeout.</param>
    /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
    public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
    {
        using (var socket = new DatagramSocket())
        using (var ct = new CancellationTokenSource(timeout))
        {
            ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());

            socket.MessageReceived += OnSocketMessageReceived;
            //The UDP port number assigned to NTP is 123
            await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
            using (var writer = new DataWriter(socket.OutputStream))
            {
                // NTP message size is 16 bytes of the digest (RFC 2030)
                var ntpBuffer = new byte[48];

                // Setting the Leap Indicator, 
                // Version Number and Mode values
                // LI = 0 (no warning)
                // VN = 3 (IPv4 only)
                // Mode = 3 (Client Mode)
                ntpBuffer[0] = 0x1B;

                writer.WriteBytes(ntpBuffer);
                await writer.StoreAsync();
                var result = await _resultCompletionSource.Task;
                return result;
            }
        }
    }

    private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
    {
        try
        {
            using (var reader = args.GetDataReader())
            {
                byte[] response = new byte[48];
                reader.ReadBytes(response);
                _resultCompletionSource.TrySetResult(ParseNetworkTime(response));
            }
        }
        catch (Exception ex)
        {
            _resultCompletionSource.TrySetException(ex);
        }
    }

    private static DateTime ParseNetworkTime(byte[] rawData)
    {
        //Offset to get to the "Transmit Timestamp" field (time at which the reply 
        //departed the server for the client, in 64-bit timestamp format."
        const byte serverReplyTime = 40;

        //Get the seconds part
        ulong intPart = BitConverter.ToUInt32(rawData, serverReplyTime);

        //Get the seconds fraction
        ulong fractPart = BitConverter.ToUInt32(rawData, serverReplyTime + 4);

        //Convert From big-endian to little-endian
        intPart = SwapEndianness(intPart);
        fractPart = SwapEndianness(fractPart);

        var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

        //**UTC** time
        DateTime networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
        return networkDateTime;
    }

    // stackoverflow.com/a/3294698/162671
    private static uint SwapEndianness(ulong x)
    {
        return (uint)(((x & 0x000000ff) << 24) +
                       ((x & 0x0000ff00) << 8) +
                       ((x & 0x00ff0000) >> 8) +
                       ((x & 0xff000000) >> 24));
    }
}

Usage:

var ntp = new NtpClient();
var accurateTime = await ntp.GetNetworkTimeAsync(TimeSpan.FromSeconds(10));

Check for special characters (/*-+_@&$#%) in a string?

Simple:

function HasSpecialChars(string yourString)
{
    return yourString.Any( ch => ! Char.IsLetterOrDigit( ch ) )
}

How to align flexbox columns left and right?

There are different ways but simplest would be to use the space-between see the example at the end

#container {    
    border: solid 1px #000;
    display: flex;    
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
    height: 50px;
}

.item {
    width: 20%;
    border: solid 1px #000;
    text-align: center;
}

see the example

Differences between MySQL and SQL Server

Anyone have any good experience with a "port" of a database from SQL Server to MySQL?

This should be fairly painful! I switched versions of MySQL from 4.x to 5.x and various statements wouldn't work anymore as they used to. The query analyzer was "improved" so statements which previously were tuned for performance would not work anymore as expected.

The lesson learned from working with a 500GB MySQL database: It's a subtle topic and anything else but trivial!

Calculate the display width of a string in Java

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For example, if you have a Graphics variable called g, you'd use:

int width = g.getFontMetrics().stringWidth(text);

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

Extract the first (or last) n characters of a string

The stringr package provides the str_sub function, which is a bit easier to use than substr, especially if you want to extract right portions of your string :

R> str_sub("leftright",1,4)
[1] "left"
R> str_sub("leftright",-5,-1)
[1] "right"

Difference between socket and websocket?

Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.

I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html

How to close a GUI when I push a JButton?

See JFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE)1. You might also use EXIT_ON_CLOSE, but it is better to explicitly clean up any running threads, then when the last GUI element becomes invisible, the EDT & JRE will end.

The 'button' to invoke this operation is already on a frame.

  1. See this answer to How to best position Swing GUIs? for a demo. of the DISPOSE_ON_CLOSE functionality.

    The JRE will end after all 3 frames are closed by clicking the X button.

Static Vs. Dynamic Binding in Java

In the case of the static binding type of object determined at the compile-time whereas in the dynamic binding type of the object is determined at the runtime.



class Dainamic{

    void run2(){
        System.out.println("dainamic_binding");
    }

}


public class StaticDainamicBinding extends Dainamic {

    void run(){
        System.out.println("static_binding");
    }

    @Override
    void run2() {
        super.run2();
    }

    public static void main(String[] args) {
        StaticDainamicBinding st_vs_dai = new StaticDainamicBinding();
        st_vs_dai.run();
        st_vs_dai.run2();
    }

}

Change MySQL root password in phpMyAdmin

0) go to phpmyadmin don't select any db
1) Click "Privileges". You'll see all the users on MySQL's privilege tables.
2) Check the user "root" whose Host value is localhost, and click the "Edit Privileges" icon.
3) In the "Change password" field, click "Password" and enter a new password.
4) Retype the password to confirm. Then click "Go" to apply the settings.

Convert a space delimited string to list

states = "Alaska Alabama Arkansas American Samoa Arizona California Colorado"
states_list = states.split (' ')

How do I enable NuGet Package Restore in Visual Studio?

Helped me through Tools >>> Nuget Package Manager >>> General then tick option Allow Nuget to download missing package and Automatically check for missing packages during build in visual studio.

enter image description here

get one item from an array of name,value JSON

You can't do what you're asking natively with an array, but javascript objects are hashes, so you can say...

var hash = {};
hash['k1'] = 'abc';
...

Then you can retrieve using bracket or dot notation:

alert(hash['k1']); // alerts 'abc'
alert(hash.k1); // also alerts 'abc'

For arrays, check the underscore.js library in general and the detect method in particular. Using detect you could do something like...

_.detect(arr, function(x) { return x.name == 'k1' });

Or more generally

MyCollection = function() {
  this.arr = [];
}

MyCollection.prototype.getByName = function(name) {
  return _.detect(this.arr, function(x) { return x.name == name });
}

MyCollection.prototype.push = function(item) {
  this.arr.push(item);
}

etc...

Create a jTDS connection string

Really, really, really check if the TCP/IP protocol is enabled in your local SQLEXPRESS instance.

Follow these steps to make sure:

  • Open "Sql Server Configuration Manager" in "Start Menu\Programs\Microsoft SQL Server 2012\Configuration Tools\"
  • Expand "SQL Server Network Configuration"
  • Go in "Protocols for SQLEXPRESS"
  • Enable TCP/IP

If you have any problem, check this blog post for details, as it contains screenshots and much more info.

Also check if the "SQL Server Browser" windows service is activated and running:

  • Go to Control Panel -> Administrative Tools -> Services
  • Open "SQL Server Browser" service and enable it (make it manual or automatic, depends on your needs)
  • Start it.

That's it.

After I installed a fresh local SQLExpress, all I had to do was to enable TCP/IP and start the SQL Server Browser service.

Below a code I use to test the SQLEXPRESS local connection. Of course, you should change the IP, DatabaseName and user/password as needed.:

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JtdsSqlExpressInstanceConnect {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        ResultSet rs = null;
        String url = "jdbc:jtds:sqlserver://127.0.0.1;instance=SQLEXPRESS;DatabaseName=master";
        String driver = "net.sourceforge.jtds.jdbc.Driver";
        String userName = "user";
        String password = "password";
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, userName, password);
            System.out.println("Connected to the database!!! Getting table list...");
            DatabaseMetaData dbm = conn.getMetaData();
            rs = dbm.getTables(null, null, "%", new String[] { "TABLE" });
            while (rs.next()) { System.out.println(rs.getString("TABLE_NAME")); }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            conn.close();
            rs.close();
        }
    }
}

And if you use Maven, add this to your pom.xml:

<dependency>
    <groupId>net.sourceforge.jtds</groupId>
    <artifactId>jtds</artifactId>
    <version>1.2.4</version>
</dependency>

How to catch SQLServer timeout exceptions

Whats the value for the SqlException.ErrorCode property? Can you work with that?

When having timeouts, it may be worth checking the code for -2146232060.

I would set this up as a static const in your data code.