Programs & Examples On #Movies

useState set method not reflecting change immediately

You can solve it by using the useRef hook but then it's will not re-render when it' updated. I have created a hooks called useStateRef, that give you the good from both worlds. It's like a state that when it's updated the Component re-render, and it's like a "ref" that always have the latest value.

See this example:

var [state,setState,ref]=useStateRef(0)

It works exactly like useState but in addition, it gives you the current state under ref.current

Learn more:

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

Rounded Corners Image in Flutter

Try This it works well.

Container(
  height: 220.0,
  width: double.infinity,
  decoration: BoxDecoration(
    borderRadius: new BorderRadius.only(
      topLeft: Radius.circular(10),
       topRight: Radius.circular(10),
    ),
    image: DecorationImage(
      fit: BoxFit.fill,
      image: NetworkImage(
        photoUrl,
      ),
     ),
   ),
);

Dart: mapping a list (list.map)

Yes, You can do it this way too

 List<String> listTab = new List();
 map.forEach((key, val) {
  listTab.add(val);
 });

 //your widget//
 bottom: new TabBar(
  controller: _controller,
  isScrollable: true,
  tabs: listTab
  ,
),

ReferenceError: fetch is not defined

The following works for me in Node.js 12.x:

npm i node-fetch;

to initialize the Dropbox instance:

var Dropbox = require("dropbox").Dropbox;
var dbx = new Dropbox({
   accessToken: <your access token>,
   fetch: require("node-fetch")    
});

to e.g. upload a content (an asynchronous method used in this case):

await dbx.filesUpload({
  contents: <your content>,
  path: <file path>
});

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

You should add the pipe to the interpolation and not to the ngFor

ul
  li(*ngFor='let movie of (movies)') ///////////removed here///////////////////
    | {{ movie.title | async }}

Reference docs

Default values for Vue component props & how to check if a user did not set the prop?

Also something important to add here, in order to set default values for arrays and objects we must use the default function for props:

propE: {
      type: Object,
      // Object or array defaults must be returned from
      // a factory function
      default: function () {
        return { message: 'hello' }
      }
    },

React Native fetch() Network Request Failed

I have similar problem. In my case requests to localhost was working and suddenly stopped. It turn out that the problem was that I was turn off my wifi on my android phone.

ReactJS - Add custom event listener to component

You could use componentDidMount and componentWillUnmount methods:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MovieItem extends Component
{
    _handleNVEvent = event => {
        ...
    };

    componentDidMount() {
        ReactDOM.findDOMNode(this).addEventListener('nv-event', this._handleNVEvent);
    }

    componentWillUnmount() {
        ReactDOM.findDOMNode(this).removeEventListener('nv-event', this._handleNVEvent);
    }

    [...]

}

export default MovieItem;

AttributeError: 'dict' object has no attribute 'predictors'

The dict.items iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items() will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The class dict does not have any predictors attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

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

I had the same problem. It was caused because I delayed notification for adapter about item insert.

But ViewHolder tried to redraw some data in it's view and it started the RecyclerView measuring and recounting children count - at that moment it crashed (items list and it's size was already updated, but the adapter was not notified yet).

How to filter a RecyclerView with a SearchView

I don't know why everyone is using 2 copies of the same list to solve this. This uses too much RAM...

Why not just hide the elements that are not found, and simply store their index in a Set to be able to restore them later? That's much less RAM especially if your objects are quite large.

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.SampleViewHolders>{
    private List<MyObject> myObjectsList; //holds the items of type MyObject
    private Set<Integer> foundObjects; //holds the indices of the found items

    public MyRecyclerViewAdapter(Context context, List<MyObject> myObjectsList)
    {
        this.myObjectsList = myObjectsList;
        this.foundObjects = new HashSet<>();
        //first, add all indices to the indices set
        for(int i = 0; i < this.myObjectsList.size(); i++)
        {
            this.foundObjects.add(i);
        }
    }

    @NonNull
    @Override
    public SampleViewHolders onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View layoutView = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.my_layout_for_staggered_grid, null);
        MyRecyclerViewAdapter.SampleViewHolders rcv = new MyRecyclerViewAdapter.SampleViewHolders(layoutView);
        return rcv;
    }

    @Override
    public void onBindViewHolder(@NonNull SampleViewHolders holder, int position)
    {
        //look for object in O(1) in the indices set
        if(!foundObjects.contains(position))
        {
            //object not found => hide it.
            holder.hideLayout();
            return;
        }
        else
        {
            //object found => show it.
            holder.showLayout();
        }

        //holder.imgImageView.setImageResource(...)
        //holder.nameTextView.setText(...)
    }

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

    public void findObject(String text)
    {
        //look for "text" in the objects list
        for(int i = 0; i < myObjectsList.size(); i++)
        {
            //if it's empty text, we want all objects, so just add it to the set.
            if(text.length() == 0)
            {
                foundObjects.add(i);
            }
            else
            {
                //otherwise check if it meets your search criteria and add it or remove it accordingly
                if (myObjectsList.get(i).getName().toLowerCase().contains(text.toLowerCase()))
                {
                    foundObjects.add(i);
                }
                else
                {
                    foundObjects.remove(i);
                }
            }
        }
        notifyDataSetChanged();
    }

    public class SampleViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener
    {
        public ImageView imgImageView;
        public TextView nameTextView;

        private final CardView layout;
        private final CardView.LayoutParams hiddenLayoutParams;
        private final CardView.LayoutParams shownLayoutParams;

        
        public SampleViewHolders(View itemView)
        {
            super(itemView);
            itemView.setOnClickListener(this);
            imgImageView = (ImageView) itemView.findViewById(R.id.some_image_view);
            nameTextView = (TextView) itemView.findViewById(R.id.display_name_textview);

            layout = itemView.findViewById(R.id.card_view); //card_view is the id of my androidx.cardview.widget.CardView in my xml layout
            //prepare hidden layout params with height = 0, and visible layout params for later - see hideLayout() and showLayout()
            hiddenLayoutParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            hiddenLayoutParams.height = 0;
            shownLayoutParams = new CardView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }

        @Override
        public void onClick(View view)
        {
            //implement...
        }

        private void hideLayout() {
            //hide the layout
            layout.setLayoutParams(hiddenLayoutParams);
        }

        private void showLayout() {
            //show the layout
            layout.setLayoutParams(shownLayoutParams);
        }
    }
}

And I simply have an EditText as my search box:

cardsSearchTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                myViewAdapter.findObject(editable.toString().toLowerCase());
            }
        });

Result:

Search example gif

Swift: Sort array of objects alphabetically

let sortArray =  array.sorted(by: { $0.name.lowercased() < $1.name.lowercased() })

Query based on multiple where clauses in Firebase

I've written a personal library that allows you to order by multiple values, with all the ordering done on the server.

Meet Querybase!

Querybase takes in a Firebase Database Reference and an array of fields you wish to index on. When you create new records it will automatically handle the generation of keys that allow for multiple querying. The caveat is that it only supports straight equivalence (no less than or greater than).

const databaseRef = firebase.database().ref().child('people');
const querybaseRef = querybase.ref(databaseRef, ['name', 'age', 'location']);

// Automatically handles composite keys
querybaseRef.push({ 
  name: 'David',
  age: 27,
  location: 'SF'
});

// Find records by multiple fields
// returns a Firebase Database ref
const queriedDbRef = querybaseRef
 .where({
   name: 'David',
   age: 27
 });

// Listen for realtime updates
queriedDbRef.on('value', snap => console.log(snap));

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The Accept Ranges header (the bit in writeHead()) is required for the HTML5 video controls to work.

I think instead of just blindly send the full file, you should first check the Accept Ranges header in the REQUEST, then read in and send just that bit. fs.createReadStream support start, and end option for that.

So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream to send the requested part to the client.

var fs = require("fs"),
    http = require("http"),
    url = require("url"),
    path = require("path");

http.createServer(function (req, res) {
  if (req.url != "/movie.mp4") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
  } else {
    var file = path.resolve(__dirname,"movie.mp4");
    fs.stat(file, function(err, stats) {
      if (err) {
        if (err.code === 'ENOENT') {
          // 404 Error if file not found
          return res.sendStatus(404);
        }
      res.end(err);
      }
      var range = req.headers.range;
      if (!range) {
       // 416 Wrong range
       return res.sendStatus(416);
      }
      var positions = range.replace(/bytes=/, "").split("-");
      var start = parseInt(positions[0], 10);
      var total = stats.size;
      var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
      var chunksize = (end - start) + 1;

      res.writeHead(206, {
        "Content-Range": "bytes " + start + "-" + end + "/" + total,
        "Accept-Ranges": "bytes",
        "Content-Length": chunksize,
        "Content-Type": "video/mp4"
      });

      var stream = fs.createReadStream(file, { start: start, end: end })
        .on("open", function() {
          stream.pipe(res);
        }).on("error", function(err) {
          res.end(err);
        });
    });
  }
}).listen(8888);

What does %>% mean in R

The infix operator %>% is not part of base R, but is in fact defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.

What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris gets passed to head():

library(magrittr)
iris %>% head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Thus, iris %>% head() is equivalent to head(iris).

Often, %>% is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris is passed to head(), then the result of that is passed to summary().

iris %>% head() %>% summary()

Thus iris %>% head() %>% summary() is equivalent to summary(head(iris)). Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.

ASP.NET Identity DbContext confusion

If you drill down through the abstractions of the IdentityDbContext you'll find that it looks just like your derived DbContext. The easiest route is Olav's answer, but if you want more control over what's getting created and a little less dependency on the Identity packages have a look at my question and answer here. There's a code example if you follow the link, but in summary you just add the required DbSets to your own DbContext subclass.

The object 'DF__*' is dependent on column '*' - Changing int to double

This is the tsql way

 ALTER TABLE yourtable DROP CONSTRAINT constraint_name     -- DF_Movies_Rating__48CFD27E

For completeness, this just shows @Joe Taras's comment as an answer

How to read xml file contents in jQuery and display in html elements?

You can use $.each()

Suppose your xml is

<Cloudtags><id>1</id></Cloudtags><Cloudtags><id>2</id></Cloudtags><Cloudtags><id>3</id></Cloudtags>

In your Ajax success

success: function (xml) {
    $(xml).find('Cloudtags').each(function(){// your outer tag of xml
         var id = $(this).find("id").text(); // 
    });
}

For your case

success: function (xml) {
        $(xml).find('person').each(function(){// your outer tag of xml
             var name = $(this).find("name").text(); // 
             var age = $(this).find("age").text();
        });
    }

CROSS JOIN vs INNER JOIN in SQL

While writing queries using inner joins the records will fetches from both tables if the condition satisfied on both tables, i.e. exact match of the common column in both tables.

While writing query using cross join the result is like cartesian product of the no of records in both tables. example if table1 contains 2 records and table2 contains 3 records then result of the query is 2*3 = 6 records.

So dont go for cross join until you need that.

how to parse JSONArray in android

If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?

Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:

List<String> allNames = new ArrayList<String>();

JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
    JSONObject actor = cast.getJSONObject(i);
    String name = actor.getString("name");
    allNames.add(name);
}

(typed straight into the browser, so not tested).

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

Here is the swift version (by using @Nitesh Borad objective C code) :-

   if let img: UIImage = UIImage(data: previewImg[indexPath.row]) {
                cell.cardPreview.image = img
            } else {
                // The image isn't cached, download the img data
                // We should perform this in a background thread
                let imgURL = NSURL(string: "webLink URL")
                let request: NSURLRequest = NSURLRequest(URL: imgURL!)
                let session = NSURLSession.sharedSession()
                let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
                    let error = error
                    let data = data
                    if error == nil {
                        // Convert the downloaded data in to a UIImage object
                        let image = UIImage(data: data!)
                        // Store the image in to our cache
                        self.previewImg[indexPath.row] = data!
                        // Update the cell
                        dispatch_async(dispatch_get_main_queue(), {
                            if let cell: YourTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as? YourTableViewCell {
                                cell.cardPreview.image = image
                            }
                        })
                    } else {
                        cell.cardPreview.image = UIImage(named: "defaultImage")
                    }
                })
                task.resume()
            }

window.location.href doesn't redirect

Make sure you're not sending a '#' at the end of your URL. In my case, that was preventing window.location.href from working.

Turning off some legends in a ggplot

You can simply add show.legend=FALSE to geom to suppress the corresponding legend

How to show and update echo on same line

If I have understood well, you can get it replacing your echo with the following line:

echo -ne "Movie $movies - $dir ADDED! \033[0K\r"

Here is a small example that you can run to understand its behaviour:

#!/bin/bash
for pc in $(seq 1 100); do
    echo -ne "$pc%\033[0K\r"
    sleep 1
done
echo

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

When do I need a fb:app_id or fb:admins?

I think the documentation is reasonably helpful!

If you read it again, it says that adding open graph elements on your website will make your website act as a facebook page and you'll get the ability to publish updates to them etc.

So I think it's up to you - you can either just have a page with no OG elements, which is less work but also less 'rewarding' for you.

If you do use og, then set type to: blog

Finally: fb:admins or fb:app_id - A comma-separated list of either the Facebook IDs of page administrators or a Facebook Platform application ID. At a minimum, include only your own Facebook ID.

So just put your own fbid in there. As a tip, you can easily get this by looking at the url of your profile photo on facebook.

linq where list contains any in list

You can use a Contains query for this:

var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));

Insert array into MySQL database with PHP

Recently,I'm learning Wordpress,it provide a class WP_QUERY to operate the database. You can insert array or object to the database.I feel it is amazing,so I go to see how to achieve it.Maybe,some ideas you can get from it.The main function is: apply_filters.

apply_filters( $tag, $value, $key);

you can ignore the first parameter ,treat the second parameter as array,what the function do is sanitizing the array into string.

after inserting into the database,you can see this :

key     s:12:"focal_length";s:3:"190";s:3:"iso";s:3:"400";s:13:"shutter_speed";s:6:"0.0004";s:5:"title";s:0:"";}}

Eclipse error: "Editor does not contain a main type"

private int user_movie_matrix[][];Th. should be `private int user_movie_matrix[][];.

private int user_movie_matrix[][]; should be private static int user_movie_matrix[][];

cfiltering(numberOfUsers, numberOfMovies); should be new cfiltering(numberOfUsers, numberOfMovies);

Whether or not the code works as intended after these changes is beyond the scope of this answer; there were several syntax/scoping errors.

Mongod complains that there is no /data/db folder

Create the folder.

sudo mkdir -p /data/db/

Give yourself permission to the folder.

sudo chown `id -u` /data/db

Then you can run mongod without sudo. Works on OSX Yosemite

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This appears to be a UTF-8 encoding issue that may have been caused by a double-UTF8-encoding of the database file contents.

This situation could happen due to factors such as the character set that was or was not selected (for instance when a database backup file was created) and the file format and encoding database file was saved with.

I have seen these strange UTF-8 characters in the following scenario (the description may not be entirely accurate as I no longer have access to the database in question):

  • As I recall, there the database and tables had a "uft8_general_ci" collation.
  • Backup is made of the database.
  • Backup file is opened on Windows in UNIX file format and with ANSI encoding.
  • Database is restored on a new MySQL server by copy-pasting the contents from the database backup file into phpMyAdmin.

Looking into the file contents:

  • Opening the SQL backup file in a text editor shows that the SQL backup file has strange characters such as "sÃ¥". On a side note, you may get different results if opening the same file in another editor. I use TextPad here but opening the same file in SublimeText said "sÃ¥" because SublimeText correctly UTF8-encoded the file -- still, this is a bit confusing when you start trying to fix the issue in PHP because you don't see the right data in SublimeText at first. Anyways, that can be resolved by taking note of which encoding your text editor is using when presenting the file contents.
  • The strange characters are double-encoded UTF-8 characters, so in my case the first "Ã" part equals "Ã" and "Â¥" = "¥" (this is my first "encoding"). THe "Ã¥" characters equals the UTF-8 character for "å" (this is my second encoding).

So, the issue is that "false" (UTF8-encoded twice) utf-8 needs to be converted back into "correct" utf-8 (only UTF8-encoded once).

Trying to fix this in PHP turns out to be a bit challenging:

utf8_decode() is not able to process the characters.

// Fails silently (as in - nothing is output)
$str = "så";

$str = utf8_decode($str);
printf("\n%s", $str);

$str = utf8_decode($str);
printf("\n%s", $str);

iconv() fails with "Notice: iconv(): Detected an illegal character in input string".

echo iconv("UTF-8", "ISO-8859-1", "så");

Another fine and possible solution fails silently too in this scenario

$str = "så";
echo html_entity_decode(htmlentities($str, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-15');

mb_convert_encoding() silently: #

$str = "så";
echo mb_convert_encoding($str, 'ISO-8859-15', 'UTF-8');
// (No output)

Trying to fix the encoding in MySQL by converting the MySQL database characterset and collation to UTF-8 was unsuccessfully:

ALTER DATABASE myDatabase CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE myTable CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;

I see a couple of ways to resolve this issue.

The first is to make a backup with correct encoding (the encoding needs to match the actual database and table encoding). You can verify the encoding by simply opening the resulting SQL file in a text editor.

The other is to replace double-UTF8-encoded characters with single-UTF8-encoded characters. This can be done manually in a text editor. To assist in this process, you can manually pick incorrect characters from Try UTF-8 Encoding Debugging Chart (it may be a matter of replacing 5-10 errors).

Finally, a script can assist in the process:

    $str = "så";
    // The two arrays can also be generated by double-encoding values in the first array and single-encoding values in the second array.
    $str = str_replace(["Ã","Â¥"], ["Ã","¥"], $str); 
    $str = utf8_decode($str);
    echo $str;
    // Output: "så" (correct)

mysql count group by having

One way would be to use a nested query:

SELECT count(*)
FROM (
   SELECT COUNT(Genre) AS count
   FROM movies
   GROUP BY ID
   HAVING (count = 4)
) AS x

The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.

sql query to find the duplicate records

This query uses the Group By and and Having clauses to allow you to select (locate and list out) for each duplicate record. The As clause is a convenience to refer to Quantity in the select and Order By clauses, but is not really part of getting you the duplicate rows.

Select
    Title,
    Count( Title ) As [Quantity]
   From
    Training
   Group By
    Title
   Having 
    Count( Title ) > 1
   Order By
    Quantity desc

Manipulate a url string by adding GET parameters

Use strpos to detect a ?. Since ? can only appear in the URL at the beginning of a query string, you know if its there get params already exist and you need to add params using &

function addGetParamToUrl(&$url, $varName, $value)
{
    // is there already an ?
    if (strpos($url, "?"))
    {
        $url .= "&" . $varName . "=" . $value; 
    }
    else
    {
        $url .= "?" . $varName . "=" . $value;
    }
}

How to sort a List of objects by their date (java collections, List<Object>)

Do not access or modify the collection in the Comparator. The comparator should be used only to determine which object is comes before another. The two objects that are to be compared are supplied as arguments.

Date itself is comparable, so, using generics:

class MovieComparator implements Comparator<Movie> {
    public int compare(Movie m1, Movie m2) {
       //possibly check for nulls to avoid NullPointerException
       return m1.getDate().compareTo(m2.getDate());
    }
}

And do not instantiate the comparator on each sort. Use:

private static final MovieComparator comparator = new MovieComparator();

Transfer data between databases with PostgreSQL

I just had to do this exact thing so I figured I'd post the recipe here. This assumes that both databases are on the same server.

First, copy the table from the old db to the new db (because apparently you can't move data between databases). At the commandline:

pg_dump -U postgres -t <old_table> <old_database> | psql -U postgres -d <new_database>

# Just adding extra space here so scrollbar doesn't hide the command

Next, grant permissions of the copied table to the user of the new database. Log into psql:

psql -U postgres -d <new_database>

ALTER TABLE <old_table> OWNER TO <new_user>;

\q

Finally, copy data from the old table to the new table. Log in as the new user and then:

INSERT INTO <new_table> (field1, field2, field3) 
SELECT field1, field2, field3 from <old_table>;

Done!

C++ Vector of pointers

As far as I understand, you create a Movie class:

class Movie
{
private:
  std::string _title;
  std::string _director;
  int         _year;
  int         _rating;
  std::vector<std::string> actors;
};

and having such class, you create a vector instance:

std::vector<Movie*> movies;

so, you can add any movie to your movies collection. Since you are creating a vector of pointers to movies, do not forget to free the resources allocated by your movie instances OR you could use some smart pointer to deallocate the movies automatically:

std::vector<shared_ptr<Movie>> movies;

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

The HTTP Content-Type for .ogg should be application/ogg (video/ogg for .ogv) and for .mp4 it should be video/mp4. You can check using the Web Sniffer.

Can I do a max(count(*)) in SQL?

SELECT * from 
(
SELECT yr as YEAR, COUNT(title) as TCOUNT
FROM actor
JOIN casting ON actor.id = casting.actorid
JOIN movie ON casting.movieid = movie.id
WHERE name = 'John Travolta'
GROUP BY yr
order by TCOUNT desc
) res
where rownum < 2

iPhone SDK:How do you play video inside a view? Rather than fullscreen

Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.framework to your target.

Here's some sample code:

#import <MediaPlayer/MediaPlayer.h>

@interface ViewController () {
    MPMoviePlayerController *moviePlayerController;
}

@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Instantiate a movie player controller and add it to your view
    NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
    NSURL *movieURL = [NSURL fileURLWithPath:moviePath];    
    moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    [moviePlayerController.view setFrame:self.movieView.bounds];  // player's frame must match parent's
    [self.movieView addSubview:moviePlayerController.view];

    // Configure the movie player controller
    moviePlayerController.controlStyle = MPMovieControlStyleNone;        
    [moviePlayerController prepareToPlay];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Start the movie
    [moviePlayerController play];
}

@end

Multiple "order by" in LINQ

Using non-lambda, query-syntax LINQ, you can do this:

var movies = from row in _db.Movies 
             orderby row.Category, row.Name
             select row;

[EDIT to address comment] To control the sort order, use the keywords ascending (which is the default and therefore not particularly useful) or descending, like so:

var movies = from row in _db.Movies 
             orderby row.Category descending, row.Name
             select row;

symfony2 : failed to write cache directory

i executed:

ps aux | grep apache

and got something like that:

root     28147  0.0  5.4 326336 27024 ?        Ss   20:06   0:00 /usr/sbin/apache2 -k start
www-data 28150  0.0  1.3 326368  6852 ?        S    20:06   0:00 /usr/sbin/apache2 -k start
www-data 28151  0.0  4.4 329016 22124 ?        S    20:06   0:00 /usr/sbin/apache2 -k start
www-data 28152  0.1  6.0 331252 30092 ?        S    20:06   0:00 /usr/sbin/apache2 -k start
www-data 28153  0.0  1.3 326368  6852 ?        S    20:06   0:00 /usr/sbin/apache2 -k start
www-data 28154  0.0  1.3 326368  6852 ?        S    20:06   0:00 /usr/sbin/apache2 -k start
www-data 28157  0.0  1.3 326368  6852 ?        S    20:06   0:00 /usr/sbin/apache2 -k start
user     28297  0.0  0.1  15736   924 pts/4    S+   20:12   0:00 grep --color=auto apache

so my user with no access turned out to be www-data thus i executed commands:

sudo chown -R www-data app/cache
sudo chown -R www-data app/logs

and it solved access errors.

Never-ever use unsecure 777 for solving specific access probles:

sudo chmod -R 777 app/cache
sudo chmod -R 777 app/logs

CSS Classes & SubClasses

Just need to add a space:

.area2 .item
{
    ...
}

Is the ternary operator faster than an "if" condition in Java

Yes, it matters, but not because of code execution performance.

Faster (performant) coding is more relevant for looping and object instantiation than simple syntax constructs. The compiler should handle optimization (it's all gonna be about the same binary!) so your goal should be efficiency for You-From-The-Future (humans are always the bottleneck in software).

The answer citing 9 lines versus one can be misleading: fewer lines of code does not always equal better. Ternary operators can be a more concise way in limited situations (your example is a good one).

BUT they can often be abused to make code unreadable (which is a cardinal sin) = do not nest ternary operators!

Also consider future maintainability, if-else is much easier to extend or modify:

int a;
if ( i != 0 && k == 7 ){
    a = 10;
    logger.debug( "debug message here" );
}else
    a = 3;
    logger.debug( "other debug message here" );
}


int a = (i != 0 && k== 7 ) ? 10 : 3;  // density without logging nor ability to use breakpoints

p.s. very complete StackOverflow answer at To ternary or not to ternary?

how to add <script>alert('test');</script> inside a text box?

is you want fix XSS on input element? you can encode string before output to input field

PHP:

$str = htmlentities($str);

C#:

str = WebUtility.HtmlEncode(str);

after that output value direct to input field:

<input type="text" value="<?php echo $str" />

How to get HTML 5 input type="date" working in Firefox and/or IE 10

This is just a suggestion that follows Dax's answer. (I would put it in a comment at that answer, but I don't have enough reputation yet to comment on others questions).

Id's should be unique for every field, so, if you have multiple date fields in your form (or forms), you could use the class element instead of the ID:

 $(function() { $( ".datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' }); });

and your input as:

 <input type="text" class="datepicker" name="your-name" />

Now, every time you need the date picker, just add that class. PS I know, you still have to use the js :(, but at least you're set for all your site. My 2 cents...

CSS text-align: center; is not centering things

This worked for me :

  e.Row.Cells["cell no "].HorizontalAlign = HorizontalAlign.Center;

But 'css text-align = center ' didn't worked for me

hope it will help you

How to subtract n days from current date in java?

for future use find day of the week ,deduct day and display the deducted day using date.

public static void main(String args[]) throws ParseException {

String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
        "Thursday", "Friday", "Saturday" };
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date dt1 = format1.parse("20/10/2013");

Calendar c = Calendar.getInstance();
c.setTime(dt1);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
long diff = Calendar.getInstance().getTime().getTime() ;
System.out.println(dayOfWeek);

switch (dayOfWeek) {

case 6:
    System.out.println(days[dayOfWeek - 1]);
    break;
case 5:

    System.out.println(days[dayOfWeek - 1]);
    break;      
case 4:
    System.out.println(days[dayOfWeek - 1]);
    break;
case 3:

    System.out.println(days[dayOfWeek - 1]);
    break;
case 2:
    System.out.println(days[dayOfWeek - 1]);
    break;
case 1:

    System.out.println(days[dayOfWeek - 1]);

     diff = diff -(dt1.getTime()- 3 );
     long valuebefore = dt1.getTime();
     long valueafetr = dt1.getTime()-2;
     System.out.println("DATE IS befor subtraction :"+valuebefore);
     System.out.println("DATE IS after subtraction :"+valueafetr);

     long x= dt1.getTime()-(2 * 24 * 3600 * 1000);
     System.out.println("Deducted date to find firday is - 2 days form Sunday :"+new Date((dt1.getTime()-(2*24*3600*1000))));
     System.out.println("DIffrence from now on is :"+diff);
        if(diff > 0) {

            diff = diff / (1000 * 60 * 60 * 24);
            System.out.println("Diff"+diff);
            System.out.println("Date is Expired!"+(dt1.getTime() -(long)2));
        }

    break;
}
}

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

If you are using CocoaPods, the most likely problem is because your Pods project Build Settings for Build Active Architecture Only is set to Yes for Debug.

The solution is simple. Change it to No.

Similarly, change to No for your application project.

Why does the C preprocessor interpret the word "linux" as the constant "1"?

From info gcc (emphasis mine):

-ansi

In C mode, this is equivalent to -std=c90. In C++ mode, it is equivalent to -std=c++98. This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or of standard C++ (when compiling C++ code), such as the asm and typeof keywords, and predefined macros such as 'unix' and 'vax' that identify the type of system you are using. It also enables the undesirable and rarely used ISO trigraph feature. For the C compiler, it disables recognition of C++ style // comments as well as the inline keyword.

(It uses vax in the example instead of linux because when it was written maybe it was more popular ;-).

The basic idea is that GCC only tries to fully comply with the ISO standards when it is invoked with the -ansi option.

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

C# Interfaces. Implicit implementation versus Explicit implementation

Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:

public void CopyTo(Array array, int index)
{
    throw new NotImplementedException();
}

and explicitly as:

void ICollection.CopyTo(Array array, int index)
{
    throw new NotImplementedException();
}

The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.

MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.

I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.

I am sure there are more reasons to use/not use explicit that others will post.

See the next post in this thread for excellent reasoning behind each.

How to embed YouTube videos in PHP?

If you want to upload videos programatically, check the YouTube Data API for PHP

OPTION (RECOMPILE) is Always Faster; Why?

Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.

  1. STATISTICS - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop a "Plan" of attack for how it will do the query, for example the type of method it will use to match keys between tables using a hash or looking through the entire set. You can call Update Statistics on the entire database or just certain tables or indexes. This slows down the query from one run to another because when statistics are out of date, its likely the query plan is not optimal for the newly inserted or changed data for the same query (explained more later below). It may not be proper to Update Statistics immediately on a Production database as there will be some overhead, slow down and lag depending on the amount of data to sample. You can also choose to use a Full Scan or Sampling to update Statistics. If you look at the Query Plan, you can then also view the statistics on the Indexes in use such using the command DBCC SHOW_STATISTICS (tablename, indexname). This will show you the distribution and ranges of the keys that the query plan is using to base its approach on.

  2. PARAMETER SNIFFING - The query plan that is cached is not optimal for the particular parameters you are passing in, even though the query itself has not changed. For example, if you pass in a parameter which only retrieves 10 out of 1,000,000 rows, then the query plan created may use a Hash Join, however if the parameter you pass in will use 750,000 of the 1,000,000 rows, the plan created may be an index scan or table scan. In such a situation you can tell the SQL statement to use the option OPTION (RECOMPILE) or an SP to use WITH RECOMPILE. To tell the Engine this is a "Single Use Plan" and not to use a Cached Plan which likely does not apply. There is no rule on how to make this decision, it depends on knowing the way the query will be used by users.

  3. INDEXES - Its possible that the query haven't changed, but a change elsewhere such as the removal of a very useful index has slowed down the query.

  4. ROWS CHANGED - The rows you are querying drastically changes from call to call. Usually statistics are automatically updated in these cases. However if you are building dynamic SQL or calling SQL within a tight loop, there is a possibility you are using an outdated Query Plan based on the wrong drastic number of rows or statistics. Again in this case OPTION (RECOMPILE) is useful.

  5. THE LOGIC Its the Logic, your query is no longer efficient, it was fine for a small number of rows, but no longer scales. This usually involves more indepth analysis of the Query Plan. For example, you can no longer do things in bulk, but have to Chunk things and do smaller Commits, or your Cross Product was fine for a smaller set but now takes up CPU and Memory as it scales larger, this may also be true for using DISTINCT, you are calling a function for every row, your key matches don't use an index because of CASTING type conversion or NULLS or functions... Too many possibilities here.

In general when you write a query, you should have some mental picture of roughly how certain data is distributed within your table. A column for example, can have an evenly distributed number of different values, or it can be skewed, 80% of the time have a specific set of values, whether the distribution will varying frequently over time or be fairly static. This will give you a better idea of how to build an efficient query. But also when debugging query performance have a basis for building a hypothesis as to why it is slow or inefficient.

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

If you need profile-specific control the in your application-{profile}.properties file

org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false

Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/

Is there a <meta> tag to turn off caching in all browsers?

It doesn't work in IE5, but that's not a big issue.

However, cacheing headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.

How to use Monitor (DDMS) tool to debug application

As far as I know, currently (Android Studio 2.3) there is no way to do this.

As per Android Studio documentation:

"Note: Only one debugger can be connected to your device at a time."

When you attempt to connect Android Device Monitor it disconnects Android Studio's debug session and vice versa, when you attempt to connect Android Studio's debugger, it disconnects Android Device Monitor.

Fortunately the new version of Android Studio (3.0) will feature a Device File Explorer that will allow you to pull files from within Android Studio without the need to open the Android Device Monitor which should resolve the problem.

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

How to add hours to current date in SQL Server?

declare @hours int = 5;

select dateadd(hour,@hours,getdate())

Order Bars in ggplot2 bar graph

I think the already provided solutions are overly verbose. A more concise way to do a frequency sorted barplot with ggplot is

ggplot(theTable, aes(x=reorder(Position, -table(Position)[Position]))) + geom_bar()

It's similar to what Alex Brown suggested, but a bit shorter and works without an anynymous function definition.

Update

I think my old solution was good at the time, but nowadays I'd rather use forcats::fct_infreq which is sorting factor levels by frequency:

require(forcats)

ggplot(theTable, aes(fct_infreq(Position))) + geom_bar()

Detect application heap size in Android

The official API is:

This was introduced in 2.0 where larger memory devices appeared. You can assume that devices running prior versions of the OS are using the original memory class (16).

Invalid default value for 'dateAdded'

CURRENT_TIMESTAMP is version specific and is now allowed for DATETIME columns as of version 5.6.

See MySQL docs.

Is it possible to set UIView border properties from interface builder?

Rich86Man's answer is correct, but you can use categories to proxy properties such as layer.borderColor. (From the ConventionalC CocoaPod)

CALayer+XibConfiguration.h:

#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>

@interface CALayer(XibConfiguration)

// This assigns a CGColor to borderColor.
@property(nonatomic, assign) UIColor* borderUIColor;

@end

CALayer+XibConfiguration.m:

#import "CALayer+XibConfiguration.h"

@implementation CALayer(XibConfiguration)

-(void)setBorderUIColor:(UIColor*)color
{
    self.borderColor = color.CGColor;
}

-(UIColor*)borderUIColor
{
    return [UIColor colorWithCGColor:self.borderColor];
}

@end

Interface Builder

layer.borderUIColor

The result will be apparent during runtime, not in Xcode.

Edit: You also need to set layer.borderWidth to at least 1 to see the border with the chosen color.

In Swift 2.0:

extension CALayer {
    var borderUIColor: UIColor {
        set {
            self.borderColor = newValue.CGColor
        }

        get {
            return UIColor(CGColor: self.borderColor!)
        }
    }
}

In Swift 3.0:

extension CALayer {
    var borderUIColor: UIColor {
        set {
            self.borderColor = newValue.cgColor
        }

        get {
            return UIColor(cgColor: self.borderColor!)
        }
    }
}

How to combine date from one field with time from another field - MS SQL Server

This is an alternative solution without any char conversions:

DATEADD(ms, DATEDIFF(ms, '00:00:00', [Time]), CONVERT(DATETIME, [Date]))

You will only get milliseconds accuracy this way, but that would normally be OK. I have tested this in SQL Server 2008.

mongodb: insert if not exists

You may use Upsert with $setOnInsert operator.

db.Table.update({noExist: true}, {"$setOnInsert": {xxxYourDocumentxxx}}, {upsert: true})

What is difference between monolithic and micro kernel?

1.Monolithic Kernel (Pure Monolithic) :all

  • All Kernel Services From single component

    (-) addition/removal is not possible, less/Zero flexible

    (+) inter Component Communication is better

e.g. :- Traditional Unix

2.Micro Kernel :few

  • few services(Memory management ,CPU management,IPC etc) from core kernel, other services(File management,I/O management. etc.) from different layers/component

  • Split Approach [Some services is in privileged(kernel) mode and some are in Normal(user) mode]

    (+)flexible for changes/up-gradations

    (-)communication overhead

e.g.:- QNX etc.

3.Modular kernel(Modular Monolithic) :most

  • Combination of Micro and Monolithic kernel

  • Collection of Modules -- modules can be --> Static + Dynamic

  • Drivers come in the form of Modules

e.g. :- Linux Modern OS

Redirect within component Angular 2

This worked for me Angular cli 6.x:

import {Router} from '@angular/router';

constructor(private artistService: ArtistService, private router: Router) { }

  selectRow(id: number): void{
       this.router.navigate([`./artist-detail/${id}`]);

  }

Add day(s) to a Date object

date.setTime( date.getTime() + days * 86400000 );

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

Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).

printf("%llu", 285212672);

How do I move a redis database from one server to another?

redis-dump finally worked for me. Its documentation provides an example how to dump a Redis database and insert the data into another one.

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

It means that one of the dependent dlls is compiled with a different run-time library.

Project -> Properties -> C/C++ -> Code Generation -> Runtime Library

Go over all the libraries and see that they are compiled in the same way.

More about this error in this link:

warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs

Mockito, JUnit and Spring

Here's my short summary.

If you want to write a unit test, don't use a Spring applicationContext because you don't want any real dependencies injected in the class you are unit testing. Instead use mocks, either with the @RunWith(MockitoJUnitRunner.class) annotation on top of the class, or with MockitoAnnotations.initMocks(this) in the @Before method.

If you want to write an integration test, use:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("yourTestApplicationContext.xml")

To set up your application context with an in-memory database for example. Normally you don't use mocks in integration tests, but you could do it by using the MockitoAnnotations.initMocks(this) approach described above.

Is it necessary to use # for creating temp tables in SQL server?

The difference between this two tables ItemBack1 and #ItemBack1 is that the first on is persistent (permanent) where as the other is temporary.

Now if take a look at your question again

Is it necessary to Use # for creating temp table in sql server?

The answer is Yes, because without this preceding # the table will not be a temporary table, it will be independent of all sessions and scopes.

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

Determine the number of NA values in a column

Try the colSums function

df <- data.frame(x = c(1,2,NA), y = rep(NA, 3))

colSums(is.na(df))

#x y 
#1 3 

How to convert an ASCII character into an int in C

A char value in C is implicitly convertible to an int. e.g, char c; ... printf("%d", c) prints the decimal ASCII value of c, and int i = c; puts the ASCII integer value of c in i. You can also explicitly convert it with (int)c. If you mean something else, such as how to convert an ASCII digit to an int, that would be c - '0', which implicitly converts c to an int and then subtracts the ASCII value of '0', namely 48 (in C, character constants such as '0' are of type int, not char, for historical reasons).

How to build a 'release' APK in Android Studio?

Click \Build\Select Build Variant... in Android Studio. And choose release.

HTML tag <a> want to add both href and onclick working

To achieve this use following html:

<a href="www.mysite.com" onclick="make(event)">Item</a>

<script>
    function make(e) {
        // ...  your function code
        // e.preventDefault();   // use this to NOT go to href site
    }
</script>

Here is working example.

INSERT with SELECT

Of course you can.

One thing should be noted however: The INSERT INTO SELECT statement copies data from one table and inserts it into another table AND requires that data types in source and target tables match. If data types from given table columns does not match (i.e. trying to insert VARCHAR into INT, or TINYINT intoINT) the MySQL server will throw an SQL Error (1366).

So be careful.

Here is the syntax of the command:

INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3 FROM table1
WHERE condition;

Side note: There is a way to circumvent different column types insertion problem by using casting in your SELECT, for example:

SELECT CAST('qwerty' AS CHAR CHARACTER SET utf8) COLLATE utf8_bin;

This conversion (CAST() is synonym of CONVERT() ) is very useful if your tables have different character sets on the same table column (which can potentially lead to data loss if not handled properly).

How to replace NA values in a table for selected columns

Edit 2020-06-15

Since data.table 1.12.4 (Oct 2019), data.table gains two functions to facilitate this: nafill and setnafill.

nafill operates on columns:

cols = c('a', 'b')
y[ , (cols) := lapply(.SD, nafill, fill=0), .SDcols = cols]

setnafill operates on tables (the replacements happen by-reference/in-place)

setnafill(y, cols=cols, fill=0)
# print y to show the effect
y[]

This will also be more efficient than the other options; see ?nafill for more, the last-observation-carried-forward (LOCF) and next-observation-carried-backward (NOCB) versions of NA imputation for time series.


This will work for your data.table version:

for (col in c("a", "b")) y[is.na(get(col)), (col) := 0]

Alternatively, as David Arenburg points out below, you can use set (side benefit - you can use it either on data.frame or data.table):

for (col in 1:2) set(x, which(is.na(x[[col]])), col, 0)

I need to round a float to two decimal places in Java

1.2975118E7 is scientific notation.

1.2975118E7 = 1.2975118 * 10^7 = 12975118

Also, Math.round(f) returns an integer. You can't use it to get your desired format x.xx.

You could use String.format.

String s = String.format("%.2f", 1.2975118);
// 1.30

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

How do I escape ampersands in XML so they are rendered as entities in HTML?

Use CDATA tags:

 <![CDATA[
   This is some text with ampersands & other funny characters. >>
 ]]>

Where does MAMP keep its php.ini?

After running the MAMP server, you have php info link in toolbar Once click, You will get all information about php enter image description here

JavaFX open new window

The code below worked for me I used part of the code above inside the button class.

public Button signupB;

public void handleButtonClick (){

    try {
        FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
        /*
         * if "fx:controller" is not set in fxml
         * fxmlLoader.setController(NewWindowController);
         */
        Scene scene = new Scene(fxmlLoader.load(), 630, 400);
        Stage stage = new Stage();
        stage.setTitle("New Window");
        stage.setScene(scene);
        stage.show();
    } catch (IOException e) {
        Logger logger = Logger.getLogger(getClass().getName());
        logger.log(Level.SEVERE, "Failed to create new Window.", e);
    }

}

}

Best way to handle list.index(might-not-exist) in python?

There is nothing "dirty" about using try-except clause. This is the pythonic way. ValueError will be raised by the .index method only, because it's the only code you have there!

To answer the comment:
In Python, easier to ask forgiveness than to get permission philosophy is well established, and no index will not raise this type of error for any other issues. Not that I can think of any.

API vs. Webservice

Check this http://en.wikipedia.org/wiki/Web_service

As the link mentioned then Web API is a development in Web services that most likely relates to Web 2.0, whereas SOAP based services are replaced by REST based communications. Note that REST services do not require XML, SOAP, or WSDL service-API definitions so this is major different to traditional web service.

Can't ping a local VM from the host

The issue could be that the VM is connected to the network via NAT. You need to set the network adapter of the VM to a bridged connection so that the VM will get it's own IP within the actual network and not on the LAN on the host.

How to compare DateTime in C#?

MuSTaNG's answer says it all, but I am still adding it to make it a little more elaborate, with links and all.


The conventional operators

are available for DateTime since .NET Framework 1.1. Also, addition and subtraction of DateTime objects are also possible using conventional operators + and -.

One example from MSDN:

Equality:
System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);

// areEqual gets false.
bool areEqual = april19 == otherDate;

otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;

Other operators can be used likewise.

Here is the list all operators available for DateTime.

Provisioning Profiles menu item missing from Xcode 5

After searching a few times in google, i found one software for provisioning profiles.

Install this iPhone configuration utility software and manage your all provisioning profiles in MAC.

Support for the experimental syntax 'classProperties' isn't currently enabled

you must install

npm install @babel/core @babel/plugin-proposal-class-properties @babel/preset-env @babel/preset-react babel-loader

and

change entry and output


const path = require('path')        
module.exports = {
  entry: path.resolve(__dirname,'src', 'app.js'),
  output: {
    path: path.resolve(__dirname, "public","dist",'javascript'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.(jsx|js)$/,
        exclude: /node_modules/,
        use: [{
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', {
                "targets": "defaults"
              }],
              '@babel/preset-react'
            ],
            plugins: [
              "@babel/plugin-proposal-class-properties"
            ]
          }
        }]
      }
    ]
  }
}

Need to get a string after a "word" in a string in c#

string originalSting = "This is my string";
string texttobesearched = "my";
string dataAfterTextTobeSearch= finalCommand.Split(new string[] { texttobesearched     }, StringSplitOptions.None).Last();
if(dataAfterTextobeSearch!=originalSting)
{
    //your action here if data is found
}
else
{
    //action if the data being searched was not found
}

Why doesn't Java allow overriding of static methods?

The following code shows that it is possible:

class OverridenStaticMeth {   

static void printValue() {   
System.out.println("Overriden Meth");   
}   

}   

public class OverrideStaticMeth extends OverridenStaticMeth {   

static void printValue() {   
System.out.println("Overriding Meth");   
}   

public static void main(String[] args) {   
OverridenStaticMeth osm = new OverrideStaticMeth();   
osm.printValue();   

System.out.println("now, from main");
printValue();

}   

} 

What is the difference between a 'closure' and a 'lambda'?

Simply speaking, closure is a trick about scope, lambda is an anonymous function. We can realize closure with lambda more elegantly and lambda is often used as a parameter passed to a higher function

Flutter position stack widget in center

Thanks to all of the above answers I'd like to share something that may come in handy in some certain cases. So lets see what happens when you use Positioned:( right: 0.0, left:0.0, bottom:0.0) :

      Padding(
        padding: const EdgeInsets.all(4.0),
        child: Stack(
          children: <Widget>[
            Positioned(
                bottom: 0.0,
                right: 0.0,
                left: 0.0,
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8.0),
                  child: Container(
                      color: Colors.blue,
                      child: Center(
                        child: Text('Hello',
                          style: TextStyle(color: Color(0xffF6C37F),
                          fontSize: 46, fontWeight: FontWeight.bold),),
                      )
                  ),
                )
            ),
          ],
        ),
      ),

This would be the output of the above code:

enter image description here

As you can see it would fill the whole width with the container even though you don't want it and you just want the container to wrap its children. so for this you can try trick below:

      Padding(
        padding: const EdgeInsets.all(4.0),
        child: Stack(
          children: <Widget>[
            Positioned(
                bottom: 0.0,
                right: 0.0,
                left: 0.0,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 8.0),
                      child: Container(
                          color: Colors.blue,
                          child: Text('Hello',
                            style: TextStyle(color: Color(0xffF6C37F), 
                            fontSize: 46, fontWeight: FontWeight.bold),)
                      ),
                    ),
                    Container(),
                  ],
                )
            ),
          ],
        ),
      ),

enter image description here

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

This solved it for me:
https://gist.github.com/beccasaurus/929007/a8f820b153a1cfdee3d06a9c0a1d7ebfced8bb77

TL;DR:
Problem:
localhost returns expected content, remote IP alters 400 content to "Bad Request"
Solution:
Adding <httpErrors existingResponse="PassThrough"></httpErrors> to web.config/configuration/system.webServer solved this for me; now all servers (local & remote) return the exact same content (generated by me) regardless of the IP address and/or HTTP code I return.

git pull remote branch cannot find remote ref

You need to set your local branch to track the remote branch, which it won't do automatically if they have different capitalizations.

Try:

git branch --set-upstream downloadmanager origin/DownloadManager
git pull

UPDATE:

'--set-upstream' option is no longer supported.

git branch --set-upstream-to downloadmanager origin/DownloadManager
git pull

How do I "commit" changes in a git submodule?

Note that if you have committed a bunch of changes in various submodules, you can (or will be soon able to) push everything in one go (ie one push from the parent repo), with:

git push --recurse-submodules=on-demand

git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1) mentions:

"git push --recurse-submodules" learned to optionally look into the histories of submodules bound to the superproject and push them out.

Probably done after this patch and the --on-demand option:

--recurse-submodules=<check|on-demand|no>::

Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.

  • If check is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
    Otherwise the push will be aborted and exit with non-zero status.
  • If on-demand is used, all submodules that changed in the revisions to be pushed will be pushed.
    If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.

This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.

Seeding the random number generator in Javascript

Please see Pierre L'Ecuyer's work going back to the late 1980s and early 1990s. There are others as well. Creating a (pseudo) random number generator on your own, if you are not an expert, is pretty dangerous, because there is a high likelihood of either the results not being statistically random or in having a small period. Pierre (and others) have put together some good (pseudo) random number generators that are easy to implement. I use one of his LFSR generators.

https://www.iro.umontreal.ca/~lecuyer/myftp/papers/handstat.pdf

Phil Troy

Naming Conventions: What to name a boolean variable?

How about:

 hasSiblings
 or isFollowedBySiblings (or isFolloedByItems, or isFollowedByOtherItems etc.)
 or moreItems

Although I think that even though you shouldn't make a habit of braking 'the rules' sometimes the best way to accomplish something may be to make an exception of the rule (Code Complete guidelines), and in your case, name the variable isNotLast

How to use Collections.sort() in Java?

Use this method Collections.sort(List,Comparator) . Implement a Comparator and pass it to Collections.sort().

class RecipeCompare implements Comparator<Recipe> {

    @Override
    public int compare(Recipe o1, Recipe o2) {
        // write comparison logic here like below , it's just a sample
        return o1.getID().compareTo(o2.getID());
    }
}

Then use the Comparator as

Collections.sort(recipes,new RecipeCompare());

jQuery UI themes and HTML tables

I've got a one liner to make HTML Tables look BootStrapped:

<table class="table table-striped table-bordered table-hover">

The theme suits other controls and it supports alternate row highlighting.

Algorithm to find Largest prime factor of a number

It seems to me that step #2 of the algorithm given isn't going to be all that efficient an approach. You have no reasonable expectation that it is prime.

Also, the previous answer suggesting the Sieve of Eratosthenes is utterly wrong. I just wrote two programs to factor 123456789. One was based on the Sieve, one was based on the following:

1)  Test = 2 
2)  Current = Number to test 
3)  If Current Mod Test = 0 then  
3a)     Current = Current Div Test 
3b)     Largest = Test
3c)     Goto 3. 
4)  Inc(Test) 
5)  If Current < Test goto 4
6)  Return Largest

This version was 90x faster than the Sieve.

The thing is, on modern processors the type of operation matters far less than the number of operations, not to mention that the algorithm above can run in cache, the Sieve can't. The Sieve uses a lot of operations striking out all the composite numbers.

Note, also, that my dividing out factors as they are identified reduces the space that must be tested.

Can I use break to exit multiple nested 'for' loops?

How about this?

for(unsigned int i=0; i < 50; i++)
{
    for(unsigned int j=0; j < 50; j++)
    {
        for(unsigned int k=0; k < 50; k++)
        {
            //Some statement
            if (condition)
            {
                j=50;
                k=50;
            }
        }
    }
}

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

Create views on two first "selects" and "union" them.

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

Could not find an implementation of the query pattern

You must have forgotten to add a using statement to the file like this:

using System.Linq;

enumerate() for dictionary in python

The first column of output is the index of each item in enumm and the second one is its keys. If you want to iterate your dictionary then use .items():

for k, v in enumm.items():
    print(k, v)

And the output should look like:

0 1
1 2
2 3
4 4 
5 5
6 6
7 7

Hive Alter table change Column Name

In the comments @libjack mentioned a point which is really important. I would like to illustrate more into it. First, we can check what are the columns of our table by describe <table_name>; command. enter image description here

there is a double-column called _c1 and such columns are created by the hive itself when we moving data from one table to another. To address these columns we need to write it inside backticks

`_c1`

Finally, the ALTER command will be,

ALTER TABLE <table_namr> CHANGE `<system_genarated_column_name>` <new_column_name> <data_type>;

JavaScript module pattern with example

Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/

Is quitting an application frowned upon?

Another Option can be Android Accessibility Services Which Greenify Application is using to Force close applications to speedup memory. With having your application accessibility service access you can click on buttons so basically Greenify Application clicks on the force close Button found in settings of an application:

Here you can study accessibility services: https://developer.android.com/reference/android/accessibilityservice/AccessibilityService.html

Here is the Setting Button which accessibility service clicks programitically: enter image description here

So You can Achieve Killing any Application Including Yours By the following Steps:

1) Register Application for Accessibility Services 2) Depending on your requirements if you want to kill all application get list of All Packages 3) Navigate to their Settings Screen And Click Force Close Button Thats It. I can Share a sample code I also created an application like greenify as an home assignment. Thank you

Update: "The user doesn't, the system handles this automatically." So Basically with this solution we are indirectly using system force close but on the User Demand. So That Both Stay Happy :-)

Why is vertical-align: middle not working on my span or div?

Here is the latest simplest solution - no need to change anything, just add three lines of CSS rules to your container of the div where you wish to center at. I love Flex Box #LoveFlexBox

_x000D_
_x000D_
.main {_x000D_
  /* I changed height to 200px to make it easy to see the alignment. */_x000D_
  height: 200px;_x000D_
  vertical-align: middle;_x000D_
  border: 1px solid #000000;_x000D_
  padding: 2px;_x000D_
  _x000D_
  /* Just add the following three rules to the container of which you want to center at. */_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  /* This is true vertical center, no math needed. */_x000D_
}_x000D_
.inner {_x000D_
  border: 1px solid #000000;_x000D_
}_x000D_
.second {_x000D_
  border: 1px solid #000000;_x000D_
}
_x000D_
<div class="main">_x000D_
  <div class="inner">This box should be centered in the larger box_x000D_
    <div class="second">Another box in here</div>_x000D_
  </div>_x000D_
  <div class="inner">This box should be centered in the larger box_x000D_
    <div class="second">Another box in here</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Bonus

the justify-content value can be set to the following few options:

  • flex-start, which will align the child div to where the flex flow starts in its parent container. In this case, it will stay on top.

  • center, which will align the child div to the center of its parent container. This is really neat, because you don't need to add an additional div to wrap around all children to put the wrapper in a parent container to center the children. Because of that, this is the true vertical center (in the column flex-direction. similarly, if you change the flow-direction to row, it will become horizontally centered.

  • flex-end, which will align the child div to where the flex flow ends in its parent container. In this case, it will move to bottom.

  • space-between, which will spread all children from the beginning of the flow to the end of the flow. If the demo, I added another child div, to show they are spread out.

  • space-around, similar to space-between, but with half of the space in the beginning and end of the flow.

How to position text over an image in css

as of 2017 this is more responsive and worked for me. This is for putting text inside vs over, like a badge. instead of the number 8, I had a variable to pull data from a database.

this code started with Kailas's answer up above

https://jsfiddle.net/jim54729/memmu2wb/3/

My HTML

<div class="containerBox">
  <img class="img-responsive"    src="https://s20.postimg.org/huun8e6fh/Gold_Ring.png">
  <div class='text-box'>
   <p class='dataNumber'> 8 </p>
  </div>
</div>

and my css:

.containerBox {
  position: relative;
  display: inline-block;
}

.text-box {
  position: absolute;
  height: 30%;
  text-align: center;
  width: 100%;
  margin: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  font-size: 30px;
}

.img-responsive {
  display: block;
  max-width: 100%;
  height: 120px;
  margin: auto;
  padding: auto;
}

.dataNumber {
  margin-top: auto;
}

Installing Numpy on 64bit Windows 7 with Python 2.7.3

It is not improbable, that programmers looking for python on windows, also use the Python Tools for Visual Studio. In this case it is easy to install additional packages, by taking advantage of the included "Python Environment" Window. "Overview" is selected within the window as default. You can select "Pip" there.

Then you can install numpy without additional work by entering numpy into the seach window. The coresponding "install numpy" instruction is already suggested.

Nevertheless I had 2 easy to solve Problems in the beginning:

  • "error: Unable to find vcvarsall.bat": This problem has been solved here. Although I did not find it at that time and instead installed the C++ Compiler for Python.
  • Then the installation continued but failed because of an additional inner exception. Installing .NET 3.5 solved this.

Finally the installation was done. It took some time (5 minutes), so don't cancel the process to early.

Converting from IEnumerable to List

If you're using an implementation of System.Collections.IEnumerable you can do like following to convert it to a List. The following uses Enumerable.Cast method to convert IEnumberable to a Generic List.

//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");

List<string> provinces = _provinces.Cast<string>().ToList();

If you're using Generic version IEnumerable<T>, The conversion is straight forward. Since both are generics, you can do like below,

IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();

But if the IEnumerable is null, when you try to convert it to a List, you'll get ArgumentNullException saying Value cannot be null.

IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();

enter image description here

Therefore as mentioned in the other answer, remember to do a null check before converting it to a List.

Set background color in PHP?

I would recommend to use css, but php to use to set some class or id for the element, in order to make it generated dynamically.

Zooming MKMapView to fit annotation pins?

You've got it right.

Find your maximum and minimum latitudes and longitudes, apply some simple arithmetic, and use MKCoordinateRegionMake.

For iOS 7 and above, use showAnnotations:animated:, from MKMapView.h:

// Position the map such that the provided array of annotations are all visible to the fullest extent possible. 
- (void)showAnnotations:(NSArray *)annotations animated:(BOOL)animated NS_AVAILABLE(10_9, 7_0);

byte[] to file in Java

This is a program where we are reading and printing array of bytes offset and length using String Builder and Writing the array of bytes offset length to the new file.

`Enter code here

import java.io.File;   
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;        

//*This is a program where we are reading and printing array of bytes offset and length using StringBuilder and Writing the array of bytes offset length to the new file*//     

public class ReadandWriteAByte {
    public void readandWriteBytesToFile(){
        File file = new File("count.char"); //(abcdefghijk)
        File bfile = new File("bytefile.txt");//(New File)
        byte[] b;
        FileInputStream fis = null;              
        FileOutputStream fos = null;          

        try{               
            fis = new FileInputStream (file);           
            fos = new FileOutputStream (bfile);             
            b = new byte [1024];              
            int i;              
            StringBuilder sb = new StringBuilder();

            while ((i = fis.read(b))!=-1){                  
                sb.append(new String(b,5,5));               
                fos.write(b, 2, 5);               
            }               

            System.out.println(sb.toString());               
        }catch (IOException e) {                    
            e.printStackTrace();                
        }finally {               
            try {              
                if(fis != null);           
                    fis.close();    //This helps to close the stream          
            }catch (IOException e){           
                e.printStackTrace();              
            }            
        }               
    }               

    public static void main (String args[]){              
        ReadandWriteAByte rb = new ReadandWriteAByte();              
        rb.readandWriteBytesToFile();              
    }                 
}                

O/P in console : fghij

O/P in new file :cdefg

How to format dateTime in django template?

You can use this:

addedDate = datetime.now().replace(microsecond=0)

Why won't my PHP app send a 404 error?

A little bit shorter version. Suppress odd echo.

if (strstr($_SERVER['REQUEST_URI'],'index.php')){
  header('HTTP/1.0 404 Not Found');
  exit("<h1>404 Not Found</h1>\nThe page that you have requested could not be found.");
}

Phone validation regex

This regex matches any number with the common format 1-(999)-999-9999 and anything in between. Also, the regex will allow braces or no braces and separations with period, space or dash. "^([01][- .])?(\(\d{3}\)|\d{3})[- .]?\d{3}[- .]\d{4}$"

Jquery UI tooltip does not support html content

add html = true to the tooltip options

$({selector}).tooltip({html: true});

Update
it's not relevant for jQuery ui tooltip property - it's true in bootstrap ui tooltip - my bad!

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Had the same problem, it was indeed caused by weblogic stupidly using its own opensaml implementation. To solve it, you have to tell it to load classes from WEB-INF/lib for this package in weblogic.xml:

    <prefer-application-packages>
        <package-name>org.opensaml.*</package-name>
    </prefer-application-packages>

maybe <prefer-web-inf-classes>true</prefer-web-inf-classes> would work too.

Print debugging info from stored procedure in MySQL

One workaround is just to use select without any other clauses.

http://lists.mysql.com/mysql/197901

Change the row color in DataGridView based on the quantity of a cell value

Just remove the : in your Quantity. Make sure that your attribute is the same with the parameter you include in the code, like this:

Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
        If Me.DataGridView1.Rows(i).Cells("Quantity").Value < 5 Then
            Me.DataGridView1.Rows(i).Cells("Quantity").Style.ForeColor = Color.Red
        End If
    Next
End Sub

Java SSLException: hostname in certificate didn't match

In httpclient-4.3.3.jar, there is another HttpClient to use:

public static void main (String[] args) throws Exception {
    // org.apache.http.client.HttpClient client = new DefaultHttpClient();
    org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
    System.out.println("HttpClient = " + client.getClass().toString());
    org.apache.http.client.methods.HttpPost post = new HttpPost("https://www.rideforrainbows.org/");
    org.apache.http.HttpResponse response = client.execute(post);
    java.io.InputStream is = response.getEntity().getContent();
    java.io.BufferedReader rd = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line;
    while ((line = rd.readLine()) != null) { 
        System.out.println(line);
    }
}

This HttpClientBuilder.create().build() will return org.apache.http.impl.client.InternalHttpClient. It can handle the this hostname in certificate didn't match issue.

Mongoose (mongodb) batch insert?

Indeed, you can use the "create" method of Mongoose, it can contain an array of documents, see this example:

Candy.create({ candy: 'jelly bean' }, { candy: 'snickers' }, function (err, jellybean, snickers) {
});

The callback function contains the inserted documents. You do not always know how many items has to be inserted (fixed argument length like above) so you can loop through them:

var insertedDocs = [];
for (var i=1; i<arguments.length; ++i) {
    insertedDocs.push(arguments[i]);
}

Update: A better solution

A better solution would to use Candy.collection.insert() instead of Candy.create() - used in the example above - because it's faster (create() is calling Model.save() on each item so it's slower).

See the Mongo documentation for more information: http://docs.mongodb.org/manual/reference/method/db.collection.insert/

(thanks to arcseldon for pointing this out)

Force update of an Android app when a new version is available

I highly recommend checking out Firebase's Remote Config functionality for this.

I implemented it using a parameter - app_version_enabled - with a condition "Disabled Android Versions" that looks like this:

applies if App ID == com.example.myapp and App version regular expression ^(5.6.1|5.4.2) 

Default for the parameter is "true", but Disabled Android Versions has a value of false. In my regex for Disabled Android Versions, you can add more disabled versions simply with another |{version name} inside those parentheses.

Then I just check if the configuration says the version is enabled or not -- I have an activity that I launch that forces the user to upgrade. I check in the only two places the app can be launched from externally (my default launcher activity and an intent-handling activity). Since Remote Config works on a cache basis, it won't immediately capture "disabled" versions of the app if the requisite time hasn't passed for the cache to be invalidated, but that is at most 12 hours if you're going by their recommended cache expiration value.

Server configuration by allow_url_fopen=0 in

Use this code in your php script (first lines)

ini_set('allow_url_fopen',1);

Virtualhost For Wildcard Subdomain and Static Subdomain

Wildcards can only be used in the ServerAlias rather than the ServerName. Something which had me stumped.

For your use case, the following should suffice

<VirtualHost *:80>
    ServerAlias *.example.com
    VirtualDocumentRoot /var/www/%1/
</VirtualHost>

How to set-up a favicon?

This method is recommended

<link rel="icon" 
  type="image/png" 
  href="/somewhere/myicon.png" />

Getting JSONObject from JSONArray

{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]

The get companyid, username, date;

jsonObj.syncresponse.deletedtrs[0].companyid
jsonObj.syncresponse.deletedtrs[0].username
jsonObj.syncresponse.deletedtrs[0].date

Easiest way to compare arrays in C#

SequenceEqual will only return true if two conditions or met.

  1. They contain the same elements.
  2. The elements are in the same order.

If you only want to check if they contain the same elements regardless of their order and your problem is of the type

Does values2 contain all the values contained in values1?

you can use LINQ extension method Enumerable.Except and then check if the result has any value. Here's an example

int[] values1 = { 1, 2, 3, 4 };
int[] values2 = { 1, 2, 5 };
var result = values1.Except(values2);
if(result.Count()==0)
{
   //They are the same
}
else
{
    //They are different
}

And also by using this you get the different items as well automatically. Two birds with one stone.

Keep in mind, if you execute your code like this

var result = values2.Except(values1);

you will get different results.

In my case I have a local copy of an array and want to check if anything has been removed from the original array so I use this method.

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

If you are using laragon open the php.ini

In the interface of laragon menu-> php-> php.ini

when you open the file look for ; extension_dir = "./"

create another one without **; ** with the path of your php version to the folder ** ext ** for example

extension_dir = "C: \ laragon \ bin \ php \ php-7.3.11-Win32-VC15-x64 \ ext"

change it save it

WordPress asking for my FTP credentials to install plugins

As mentioned by Niels, this happens because the server process user can't write to the Wordpress folder.

But here's the thing a lot of articles don't explain. It's the owner of the php process, not the nginx process. If you try to change the nginx owner, it won't solve this.

To solve it, try running ps aux to see which user owns the php-fpm process. Then check that user is the same user as the owner of the wordpress folder, or can at least write to it. If the user can't write to it, you'll need to change permissions and/or ownership of the folder; or put the two users (server owner and wordpress folder owner) in a common group which can write to the folder; or change php.ini "user" property to a user that can write to the folder.

How to type ":" ("colon") in regexp?

Colon does not have special meaning in a character class and does not need to be escaped. According to the PHP regex docs, the only characters that need to be escaped in a character class are the following:

All non-alphanumeric characters other than \, -, ^ (at the start) and the terminating ] are non-special in character classes, but it does no harm if they are escaped.

For more info about Java regular expressions, see the docs.

Android ImageView Fixing Image Size

In your case you need to

  1. Fix the ImageView's size. You need to use dp unit so that it will look the same in all devices.
  2. Set android:scaleType to fitXY

Below is an example:

<ImageView
    android:id="@+id/photo"
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:src="@drawable/iclauncher" 
    android:scaleType="fitXY"/>

For more information regarding ImageView scaleType please refer to the developer website.

Remove all the children DOM elements in div

node.innerHTML = "";

Non-standard, but fast and well supported.

Remove stubborn underline from link

Without seeing the page, hard to speculate.

But it sounds to me like you may have a border-bottom: 1px solid blue; being applied. Perhaps add border: none;. text-decoration: none !important is right, it's possible that you have another style that is still overriding that CSS though.

This is where using the Firefox Web Developer Toolbar is awesome, you can edit the CSS right there and see if things work, at least for Firefox. It's under CSS > Edit CSS.

How do I write good/correct package __init__.py files

Your __init__.py should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

Read input numbers separated by spaces

int main() {
int sum = 0;
cout << "enter number" << endl;
int i = 0;
while (true) {
    cin >> i;
    sum += i;
    //cout << i << endl;
    if (cin.peek() == '\n') {
        break;
    }
    
}

cout << "result: " << sum << endl;
return 0;
}

I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints

How to get the CUDA version?

Apart from the ones mentioned above, your CUDA installations path (if not changed during setup) typically contains the version number

doing a which nvcc should give the path and that will give you the version

PS: This is a quick and dirty way, the above answers are more elegant and will result in the right version with considerable effort

Delete all data in SQL Server database

As an alternative answer, if you Visual Studio SSDT or possibly Red Gate Sql Compare, you could simply run a schema comparison, script it out, drop the old database (possibly make a backup first in case there would be a reason that you will need that data), and then create a new database with the script created by the comparison tool. While on a very small database this may be more work, on a very large database it will be much quicker to simply drop the database then to deal with the different triggers and constraints that may be on the database.

Error: "Could Not Find Installable ISAM"

Try putting single quotes around the data source:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb';

The problem tends to be white space which does have meaning to the parser.

If you had other attributes (e.g., Extended Properties), their values may also have to be enclosed in single quotes:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb'; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';

You could equally well use double quotes; however, you'll probably have to escape them, and I find that more of a Pain In The Algorithm than using singles.

How to turn a vector into a matrix in R?

Just use matrix:

matrix(vec,nrow = 7,ncol = 7)

One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

How to use Console.WriteLine in ASP.NET (C#) during debug?

Trace.Write("Error Message") and Trace.Warn("Error Message") are the methods to use in web, need to decorate the page header trace=true and in config file to hide the error message text to go to end-user and so as to stay in iis itself for programmer debug.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

Rotating a point about another point (2D)

This is the answer by Nils Pipenbrinck, but implemented in c# fiddle.

https://dotnetfiddle.net/btmjlG

using System;

public class Program
{
    public static void Main()
    {   
        var angle = 180 * Math.PI/180;
        Console.WriteLine(rotate_point(0,0,angle,new Point{X=10, Y=10}).Print());
    }

    static Point rotate_point(double cx, double cy, double angle, Point p)
    {
        double s = Math.Sin(angle);
        double c = Math.Cos(angle);
        // translate point back to origin:
        p.X -= cx;
        p.Y -= cy;
        // rotate point
        double Xnew = p.X * c - p.Y * s;
        double Ynew = p.X * s + p.Y * c;
        // translate point back:
        p.X = Xnew + cx;
        p.Y = Ynew + cy;
        return p;
    }

    class Point
    {
        public double X;
        public double Y;

        public string Print(){
            return $"{X},{Y}";
        }
    }
}

Ps: Apparently I can’t comment, so I’m obligated to post it as an answer ...

Simple UDP example to send and receive data from same socket

I'll try to keep this short, I've done this a few months ago for a game I was trying to build, it does a UDP "Client-Server" connection that acts like TCP, you can send (message) (message + object) using this. I've done some testing with it and it works just fine, feel free to modify it if needed.

How to use BOOLEAN type in SELECT statement

The BOOLEAN data type is a PL/SQL data type. Oracle does not provide an equivalent SQL data type (...) you can create a wrapper function which maps a SQL type to the BOOLEAN type.

Check this: http://forums.datadirect.com/ddforums/thread.jspa?threadID=1771&tstart=0&messageID=5284

Getting ssh to execute a command in the background on target machine

YOUR-COMMAND &> YOUR-LOG.log &    

This should run the command and assign a process id you can simply tail -f YOUR-LOG.log to see results written to it as they happen. you can log out anytime and the process will carry on

How to detect pressing Enter on keyboard using jQuery?

I used $(document).on("keydown").

On some browsers keyCode is not supported. The same with which so if keyCode is not supported you need to use which and vice versa.

_x000D_
_x000D_
$(document).on("keydown", function(e) {_x000D_
  const ENTER_KEY_CODE = 13;_x000D_
  const ENTER_KEY = "Enter";_x000D_
  var code = e.keyCode || e.which_x000D_
  var key = e.key_x000D_
  if (code == ENTER_KEY_CODE || key == ENTER_KEY) {_x000D_
    console.log("Enter key pressed")_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Get full URL and query string in Servlet for both HTTP and HTTPS requests

I know this is a Java question, but if you're using Kotlin you can do this quite nicely:

val uri = request.run {
    if (queryString.isNullOrBlank()) requestURI else "$requestURI?$queryString"
}

How to reset sequence in postgres and fill id column with new data?

Just resetting the sequence and updating all rows may cause duplicate id errors. In many cases you have to update all rows twice. First with higher ids to avoid the duplicates, then with the ids you actually want.

Please avoid to add a fixed amount to all ids (as recommended in other comments). What happens if you have more rows than this fixed amount? Assuming the next value of the sequence is higher than all the ids of the existing rows (you just want to fill the gaps), i would do it like:

UPDATE table SET id = DEFAULT;
ALTER SEQUENCE seq RESTART;
UPDATE table SET id = DEFAULT;

Splitting a string into chunks of a certain size

Based around other posters answers, along with some samples of useage:

public static string FormatSortCode(string sortCode)
{
    return ChunkString(sortCode, 2, "-");
}
public static string FormatIBAN(string iban)
{
    return ChunkString(iban, 4, "&nbsp;&nbsp;");
}

private static string ChunkString(string str, int chunkSize, string separator)
{
    var b = new StringBuilder();
    var stringLength = str.Length;
    for (var i = 0; i < stringLength; i += chunkSize)
    {
        if (i + chunkSize > stringLength) chunkSize = stringLength - i;
        b.Append(str.Substring(i, chunkSize));
        if (i+chunkSize != stringLength)
            b.Append(separator);
    }
    return b.ToString();
}

How can I start an interactive console for Perl?

You can use the perl debugger on a trivial program, like so:

perl -de1

Alternatively there's Alexis Sukrieh's Perl Console application, but I haven't used it.

How to remove MySQL completely with config and library files?

Just a little addition to the answer of @dAm2k :

In addition to sudo apt-get remove --purge mysql\*

I've done a sudo apt-get remove --purge mariadb\*.

I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.

Hope it helps.

Getting year in moment.js

The year() function just retrieves the year component of the underlying Date object, so it returns a number.

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY, then the result will be a string containing the year.

If all you need is the year, then use the year() function. It will be faster, as there is less work to do.

Do note that while years are the same in this regard, months are not! Calling format('M') will return months in the range 1-12. Calling month() will return months in the range 0-11. This is due to the same behavior of the underlying Date object.

Moving Panel in Visual Studio Code to right side

Go to view, then appearence. Then select move panel bottom.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

LaTeX beamer: way to change the bullet indentation?

Setting \itemindent for a new itemize environment solves the problem:

\newenvironment{beameritemize}
{ \begin{itemize}
  \setlength{\itemsep}{1.5ex}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}   
  \addtolength{\itemindent}{-2em}  }
{ \end{itemize} } 

explicit casting from super class to subclass

The code generates a compilation error because your instance type is an Animal:

Animal animal=new Animal();

Downcasting is not allowed in Java for several reasons. See here for details.

Delaying a jquery script until everything else has loaded

The following script ensures that my_finalFunction runs after your page has been fully loaded with images, stylesheets and external content:

<script>

    document.addEventListener("load", my_finalFunction, false);

    function my_finalFunction(e) {
        /* things to do after all has been loaded */
    }

</script>

A good explanation is provided by kirupa on running your code at the right time, see https://www.kirupa.com/html5/running_your_code_at_the_right_time.htm.

Set Content-Type to application/json in jsp file

@Petr Mensik & kensen john

Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:

    <%
        String callback = request.getParameter("callback");
        response.setCharacterEncoding("UTF-8");
        if (callback != null) {
            // Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
            response.setContentType("text/javascript");
        } else {
            // Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
            response.setContentType("application/json");
        }

        [...]

        String output = "";

        if (callback != null) {
            output += callback + "(";
        }

        output += jsonObj.toString();

        if (callback != null) {
            output += ");";
        }
    %>
    <%=output %>

When callback is supplied, returns:

    callback({...JSON stuff...});

with content-type "text/javascript"

When callback is NOT supplied, returns:

    {...JSON stuff...}

with content-type "application/json"

Changing .gitconfig location on Windows

Change HOME directory for this is wrong. Better is create symbolic link for gitconfig to HOME directory.

  1. Move your .gitconfig from user home directory, to the directory where you want.
  2. Run command line as Administrator
  3. Go to your user home directory
  4. Enter mklink .gitconfig \PathForNewLocationOfConfig.gitconfig

Scanner method to get a char

Console cons = System.console();

The above code line creates cons as a null reference. The code and output are given below:

Console cons = System.console();
if (cons != null) {
    System.out.println("Enter single character: ");
    char c = (char) cons.reader().read();
    System.out.println(c);
}else{
    System.out.println(cons);
}

Output :

null

The code was tested on macbook pro with java version "1.6.0_37"

variable or field declared void

Did you put void while calling your function?

For example:

void something(int x){
    logic..
}

int main() {

    **void** something();

    return 0;

}

If so, you should delete the last void.

Making a UITableView scroll when text field is selected

Easy and fast solution.

I just scroll to the right cell whenever scrolling happens

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView 

Assuming I know table now is in this mode "_keepMyCellOnTop" & I know selected cell "_selectedCellIndex" or scroll to selected cell

- (void)scrollViewDidScroll:(UIScrollView *)scrollView 
{

    if (_keepMyCellOnTop)
    {
        [self.tableView scrollToRowAtIndexPath:_selectedCellIndex atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

This will prevent scrolling.

Placing the code in -(void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView will result a scroll up and down

iPhone get SSID without private library

Here's the short & sweet Swift version.

Remember to link and import the Framework:

import UIKit
import SystemConfiguration.CaptiveNetwork

Define the method:

func fetchSSIDInfo() -> CFDictionary? {
    if let
        ifs = CNCopySupportedInterfaces().takeUnretainedValue() as? [String],
        ifName = ifs.first,
        info = CNCopyCurrentNetworkInfo((ifName as CFStringRef))
    {
        return info.takeUnretainedValue()
    }
    return nil
}

Call the method when you need it:

if let
    ssidInfo = fetchSSIDInfo() as? [String:AnyObject],
    ssID = ssidInfo["SSID"] as? String
{
    println("SSID: \(ssID)")
} else {
    println("SSID not found")
}

As mentioned elsewhere, this only works on your iDevice. When not on WiFi, the method will return nil – hence the optional.

How to show all shared libraries used by executables in Linux?

readelf -d recursion

redelf -d produces similar output to objdump -p which was mentioned at: https://stackoverflow.com/a/15520982/895245

But beware that dynamic libraries can depend on other dynamic libraries, to you have to recurse.

Example:

readelf -d /bin/ls | grep 'NEEDED'

Sample ouptut:

 0x0000000000000001 (NEEDED)             Shared library: [libselinux.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libacl.so.1]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]

Then:

$ locate libselinux.so.1
/lib/i386-linux-gnu/libselinux.so.1
/lib/x86_64-linux-gnu/libselinux.so.1
/mnt/debootstrap/lib/x86_64-linux-gnu/libselinux.so.1

Choose one, and repeat:

readelf -d /lib/x86_64-linux-gnu/libselinux.so.1 | grep 'NEEDED'

Sample output:

0x0000000000000001 (NEEDED)             Shared library: [libpcre.so.3]
0x0000000000000001 (NEEDED)             Shared library: [libdl.so.2]
0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
0x0000000000000001 (NEEDED)             Shared library: [ld-linux-x86-64.so.2]

And so on.

/proc/<pid>/maps for running processes

This is useful to find all the libraries currently being used by running executables. E.g.:

sudo awk '/\.so/{print $6}' /proc/1/maps | sort -u

shows all currently loaded dynamic dependencies of init (PID 1):

/lib/x86_64-linux-gnu/ld-2.23.so
/lib/x86_64-linux-gnu/libapparmor.so.1.4.0
/lib/x86_64-linux-gnu/libaudit.so.1.0.0
/lib/x86_64-linux-gnu/libblkid.so.1.1.0
/lib/x86_64-linux-gnu/libc-2.23.so
/lib/x86_64-linux-gnu/libcap.so.2.24
/lib/x86_64-linux-gnu/libdl-2.23.so
/lib/x86_64-linux-gnu/libkmod.so.2.3.0
/lib/x86_64-linux-gnu/libmount.so.1.1.0
/lib/x86_64-linux-gnu/libpam.so.0.83.1
/lib/x86_64-linux-gnu/libpcre.so.3.13.2
/lib/x86_64-linux-gnu/libpthread-2.23.so
/lib/x86_64-linux-gnu/librt-2.23.so
/lib/x86_64-linux-gnu/libseccomp.so.2.2.3
/lib/x86_64-linux-gnu/libselinux.so.1
/lib/x86_64-linux-gnu/libuuid.so.1.3.0

This method also shows libraries opened with dlopen, tested with this minimal setup hacked up with a sleep(1000) on Ubuntu 18.04.

See also: https://superuser.com/questions/310199/see-currently-loaded-shared-objects-in-linux/1243089

how to get files from <input type='file' .../> (Indirect) with javascript

Above answers are pretty sufficient. Additional to the onChange, if you upload a file using drag and drop events, you can get the file in drop event by accessing eventArgs.dataTransfer.files.

How to check if object property exists with a variable holding the property name?

Thank you for everyone's assistance and pushing to get rid of the eval statement. Variables needed to be in brackets, not dot notation. This works and is clean, proper code.

Each of these are variables: appChoice, underI, underObstr.

if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
    //enter code here
}

NoSQL Use Case Scenarios or WHEN to use NoSQL

It really is an "it depends" kinda question. Some general points:

  • NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
  • NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
  • Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
  • It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
  • IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
  • It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
  • NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.

JBoss vs Tomcat again

Take a look at TOMEE

It has all the features that you need to build a complete Java EE app.

How to set the height and the width of a textfield in Java?

You should not play with the height. Let the text field determine the height based on the font used.

If you want to control the width of the text field then you can use

textField.setColumns(...);

to let the text field determine the preferred width.

Or if you want the width to be the entire width of the parent panel then you need to use an appropriate layout. Maybe the NORTH of a BorderLayout.

See the Swing tutorial on Layout Managers for more information.

Check if a list contains an item in Ansible

Ansible has a version_compare filter since 1.6. You can do something like below in when conditional:

when: ansible_distribution_version | version_compare('12.04', '>=')

This will give you support for major & minor versions comparisons and you can compare versions using operators like:

<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne

You can find more information about this here: Ansible - Version comparison filters

Otherwise if you have really simple case you can use what @ProfHase85 suggested

How to install wkhtmltopdf on a linux based (shared hosting) web server

Chances are that without full access to this server (due to being a hosted account) you are going to have problems. I would go so far as to say that I think it is a fruitless endeavor--they have to lock servers down in hosted environments for good reason.

Call your hosting company and make the request to them to install it, but don't expect a good response--they typically won't install very custom items for single users unless there is a really good reason (bug fixes for example).

Lastly, depending on how familiar you are with server administration and what you are paying for server hosting now consider something like http://www.slicehost.com. $20 a month will get you a low grade web server (256 ram) and you can install anything you want. However, if you are running multiple sites or have heavy load the cost will go up as you need larger servers.

GL!

How do I extract a substring from a string until the second space is encountered?

Use a regex: .

Match m = Regex.Match(text, @"(.+? .+?) ");
if (m.Success) {
    do_something_with(m.Groups[1].Value);
}

How do I run git log to see changes only for a specific branch?

For those using Magit, hit l and =m to toggle --no-merges and =pto toggle --first-parent.

Then either just hit l again to show commits from the current branch (with none of commits merged onto it) down to end of history, or, if you want the log to end where it was branched off from master, hit o and type master.. as your range:

enter image description here

Adding onClick event dynamically using jQuery

You can use the click event and call your function or move your logic into the handler:

$("#bfCaptchaEntry").click(function(){ myFunction(); });

You can use the click event and set your function as the handler:

$("#bfCaptchaEntry").click(myFunction);

.click()

Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

http://api.jquery.com/click/


You can use the on event bound to "click" and call your function or move your logic into the handler:

$("#bfCaptchaEntry").on("click", function(){ myFunction(); });

You can use the on event bound to "click" and set your function as the handler:

$("#bfCaptchaEntry").on("click", myFunction);

.on()

Attach an event handler function for one or more events to the selected elements.

http://api.jquery.com/on/

How to find the Vagrant IP?

Terminating a connection open with vagrant ssh will show the address, so a dummy or empty command can be executed:

$ vagrant ssh -c ''
Connection to 192.168.121.155 closed.

Use ffmpeg to add text subtitles

I will provide a simple and general answer that works with any number of audios and srt subtitles and respects the metadata that may include the mkv container. So it will even add the images the matroska may include as attachments (though not another types AFAIK) and convert them to tracks; you will not be able to watch but they will be there (you can demux them). Ah, and if the mkv has chapters the mp4 too.

ffmpeg -i <mkv-input> -c copy -map 0 -c:s mov_text <mp4-output>

As you can see, it's all about the -map 0, that tells FFmpeg to add all the tracks, which includes metadata, chapters, attachments, etc. If there is an unrecognized "track" (mkv allows to attach any type of file), it will end with an error.

You can create a simple batch mkv2mp4.bat, if you usually do this, to create an mp4 with the same name as the mkv. It would be better with error control, a different output name, etc., but you get the point.

@ffmpeg -i %1 -c copy -map 0 -c:s mov_text "%~n1.mp4"

Now you can simply run

mkv2mp4 "Video with subtitles etc.mkv"

And it will create "Video with subtitles etc.mp4" with the maximum of information included.

What does string::npos mean in this code?

npos is just a token value that tells you that find() did not find anything (probably -1 or something like that). find() checks for the first occurence of the parameter, and returns the index at which the parameter begins. For Example,

  string name = "asad.txt";
  int i = name.find(".txt");
  //i holds the value 4 now, that's the index at which ".txt" starts
  if (i==string::npos) //if ".txt" was NOT found - in this case it was, so  this condition is false
    name.append(".txt");

What is the Difference Between Mercurial and Git?

Nothing. They both do the same, both perform about equally. The only reason you should choose one over the other is if you help out with a project that already uses one..

The other possible reason for choosing one is an application or service which only supports one of the system.. For example, I pretty much chose to learn git because of github..

Create Windows service from executable

Probably all your answers are better, but - just to be complete on the choice of options - I wanted to remind about old, similar method used for years:

SrvAny (installed by InstSrv)

as described here: https://docs.microsoft.com/en-us/troubleshoot/windows-client/deployment/create-user-defined-service

Wheel file installation

you can follow the below command to install using the wheel file at your local

pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl

Remove by _id in MongoDB console

db.collection("collection_name").deleteOne({_id:ObjectId("4d513345cc9374271b02ec6c")})

Yii2 data provider default sorting

if you have CRUD (index) and you need set default sorting your controller for GridView, or ListView, or more... Example

public function actionIndex()
{
    $searchModel = new NewsSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    // set default sorting
    $dataProvider->sort->defaultOrder = ['id' => SORT_DESC];

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

you need add

$dataProvider->sort->defaultOrder = ['id' => SORT_DESC];

How to get post slug from post in WordPress?

Wordpress: Get post/page slug

<?php 
// Custom function to return the post slug
function the_slug($echo=true){
  $slug = basename(get_permalink());
  do_action('before_slug', $slug);
  $slug = apply_filters('slug_filter', $slug);
  if( $echo ) echo $slug;
  do_action('after_slug', $slug);
  return $slug;
}
?>
<?php if (function_exists('the_slug')) { the_slug(); } ?>

How do I correctly clone a JavaScript object?

Performance

Today 2020.04.30 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v75.0 on MacOs High Sierra v10.13.6.

I focus on speed of copy DATA (object with simple type fields, not methods etc.). The solutions A-I can make only shallow copy, solutions J-U can make deep copy.

Results for shallow copy

  • solution {...obj} (A) is fastest on chrome and firefox and medium fast on safari
  • solution based on Object.assign (B) is fast on all browsers
  • jQuery (E) and lodash (F,G,H) solutions are medium/quite fast
  • solution JSON.parse/stringify (K) is quite slow
  • solutions D and U are slow on all browsers

enter image description here

Results for deep copy

  • solution Q is fastest on all browsers
  • jQuery (L) and lodash (J) are medium fast
  • solution JSON.parse/stringify (K) is quite slow
  • solution U is slowest on all browsers
  • lodash (J) and solution U crash on Chrome for 1000 level deep object

enter image description here

Details

For choosen solutions: A B C(my) D E F G H I J K L M N O P Q R S T U, I perform 4 tests

  • shallow-small: object with 10 non-nested fields - you can run it HERE
  • shallow-big: object with 1000 non-nested fields - you can run it HERE
  • deep-small: object with 10 levels-nested fields - you can run it HERE
  • deep-big: object with 1000 levels-nested fields - you can run it HERE

Objects used in tests are show in below snippet

_x000D_
_x000D_
let obj_ShallowSmall = {_x000D_
  field0: false,_x000D_
  field1: true,_x000D_
  field2: 1,_x000D_
  field3: 0,_x000D_
  field4: null,_x000D_
  field5: [],_x000D_
  field6: {},_x000D_
  field7: "text7",_x000D_
  field8: "text8",_x000D_
}_x000D_
_x000D_
let obj_DeepSmall = {_x000D_
  level0: {_x000D_
   level1: {_x000D_
    level2: {_x000D_
     level3: {_x000D_
      level4: {_x000D_
       level5: {_x000D_
        level6: {_x000D_
         level7: {_x000D_
          level8: {_x000D_
           level9: [[[[[[[[[['abc']]]]]]]]]],_x000D_
  }}}}}}}}},_x000D_
};_x000D_
_x000D_
let obj_ShallowBig = Array(1000).fill(0).reduce((a,c,i) => (a['field'+i]=getField(i),a) ,{});_x000D_
_x000D_
_x000D_
let obj_DeepBig = genDeepObject(1000);_x000D_
_x000D_
_x000D_
_x000D_
// ------------------_x000D_
// Show objects_x000D_
// ------------------_x000D_
_x000D_
console.log('obj_ShallowSmall:',JSON.stringify(obj_ShallowSmall));_x000D_
console.log('obj_DeepSmall:',JSON.stringify(obj_DeepSmall));_x000D_
console.log('obj_ShallowBig:',JSON.stringify(obj_ShallowBig));_x000D_
console.log('obj_DeepBig:',JSON.stringify(obj_DeepBig));_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
// ------------------_x000D_
// HELPERS_x000D_
// ------------------_x000D_
_x000D_
function getField(k) {_x000D_
  let i=k%10;_x000D_
  if(i==0) return false;_x000D_
  if(i==1) return true;_x000D_
  if(i==2) return k;_x000D_
  if(i==3) return 0;_x000D_
  if(i==4) return null;_x000D_
  if(i==5) return [];_x000D_
  if(i==6) return {};  _x000D_
  if(i>=7) return "text"+k;_x000D_
}_x000D_
_x000D_
function genDeepObject(N) {_x000D_
  // generate: {level0:{level1:{...levelN: {end:[[[...N-times...['abc']...]]] }}}...}}}_x000D_
  let obj={};_x000D_
  let o=obj;_x000D_
  let arr = [];_x000D_
  let a=arr;_x000D_
_x000D_
  for(let i=0; i<N; i++) {_x000D_
    o['level'+i]={};_x000D_
    o=o['level'+i];_x000D_
    let aa=[];_x000D_
    a.push(aa);_x000D_
    a=aa;_x000D_
  }_x000D_
_x000D_
  a[0]='abc';_x000D_
  o['end']=arr;_x000D_
  return obj;_x000D_
}
_x000D_
_x000D_
_x000D_

Below snippet presents tested solutions and shows differences between them

_x000D_
_x000D_
function A(obj) {_x000D_
  return {...obj}_x000D_
}_x000D_
_x000D_
function B(obj) {_x000D_
  return Object.assign({}, obj); _x000D_
}_x000D_
_x000D_
function C(obj) {_x000D_
  return Object.keys(obj).reduce( (a,c) => (a[c]=obj[c], a), {})_x000D_
}_x000D_
_x000D_
function D(obj) {_x000D_
  let copyOfObject = {};_x000D_
  Object.defineProperties(copyOfObject, Object.getOwnPropertyDescriptors(obj));_x000D_
  return copyOfObject;_x000D_
}_x000D_
_x000D_
function E(obj) {_x000D_
  return jQuery.extend({}, obj) // shallow_x000D_
}_x000D_
_x000D_
function F(obj) {_x000D_
  return _.clone(obj);_x000D_
}_x000D_
_x000D_
function G(obj) {_x000D_
  return _.clone(obj,true);_x000D_
}_x000D_
_x000D_
function H(obj) {_x000D_
  return _.extend({},obj);_x000D_
}_x000D_
_x000D_
function I(obj) {_x000D_
    if (null == obj || "object" != typeof obj) return obj;_x000D_
    var copy = obj.constructor();_x000D_
    for (var attr in obj) {_x000D_
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];_x000D_
    }_x000D_
    return copy;_x000D_
}_x000D_
_x000D_
function J(obj) {_x000D_
  return _.cloneDeep(obj,true);_x000D_
}_x000D_
_x000D_
function K(obj) {_x000D_
 return JSON.parse(JSON.stringify(obj));_x000D_
}_x000D_
_x000D_
function L(obj) {_x000D_
  return jQuery.extend(true, {}, obj) // deep_x000D_
}_x000D_
_x000D_
function M(obj) {_x000D_
  if(obj == null || typeof(obj) != 'object')_x000D_
    return obj;    _x000D_
  var temp = new obj.constructor(); _x000D_
  for(var key in obj)_x000D_
    temp[key] = M(obj[key]);    _x000D_
  return temp;_x000D_
}_x000D_
_x000D_
function N(obj) {_x000D_
  let EClone = function(obj) {_x000D_
    var newObj = (obj instanceof Array) ? [] : {};_x000D_
    for (var i in obj) {_x000D_
      if (i == 'EClone') continue;_x000D_
      if (obj[i] && typeof obj[i] == "object") {_x000D_
        newObj[i] = EClone(obj[i]);_x000D_
      } else newObj[i] = obj[i]_x000D_
    } return newObj;_x000D_
  };_x000D_
_x000D_
 return EClone(obj);_x000D_
};_x000D_
_x000D_
function O(obj) {_x000D_
    if (obj == null || typeof obj != "object") return obj;_x000D_
    if (obj.constructor != Object && obj.constructor != Array) return obj;_x000D_
    if (obj.constructor == Date || obj.constructor == RegExp || obj.constructor == Function ||_x000D_
        obj.constructor == String || obj.constructor == Number || obj.constructor == Boolean)_x000D_
        return new obj.constructor(obj);_x000D_
_x000D_
    let to = new obj.constructor();_x000D_
_x000D_
    for (var name in obj)_x000D_
    {_x000D_
        to[name] = typeof to[name] == "undefined" ? O(obj[name], null) : to[name];_x000D_
    }_x000D_
_x000D_
    return to;_x000D_
}_x000D_
_x000D_
function P(obj) {_x000D_
  function clone(target, source){_x000D_
_x000D_
      for(let key in source){_x000D_
_x000D_
          // Use getOwnPropertyDescriptor instead of source[key] to prevent from trigering setter/getter._x000D_
          let descriptor = Object.getOwnPropertyDescriptor(source, key);_x000D_
          if(descriptor.value instanceof String){_x000D_
              target[key] = new String(descriptor.value);_x000D_
          }_x000D_
          else if(descriptor.value instanceof Array){_x000D_
              target[key] = clone([], descriptor.value);_x000D_
          }_x000D_
          else if(descriptor.value instanceof Object){_x000D_
              let prototype = Reflect.getPrototypeOf(descriptor.value);_x000D_
              let cloneObject = clone({}, descriptor.value);_x000D_
              Reflect.setPrototypeOf(cloneObject, prototype);_x000D_
              target[key] = cloneObject;_x000D_
          }_x000D_
          else {_x000D_
              Object.defineProperty(target, key, descriptor);_x000D_
          }_x000D_
      }_x000D_
      let prototype = Reflect.getPrototypeOf(source);_x000D_
      Reflect.setPrototypeOf(target, prototype);_x000D_
      return target;_x000D_
  }_x000D_
  return clone({},obj);_x000D_
}_x000D_
_x000D_
function Q(obj) {_x000D_
    var copy;_x000D_
_x000D_
    // Handle the 3 simple types, and null or undefined_x000D_
    if (null == obj || "object" != typeof obj) return obj;_x000D_
_x000D_
    // Handle Date_x000D_
    if (obj instanceof Date) {_x000D_
        copy = new Date();_x000D_
        copy.setTime(obj.getTime());_x000D_
        return copy;_x000D_
    }_x000D_
_x000D_
    // Handle Array_x000D_
    if (obj instanceof Array) {_x000D_
        copy = [];_x000D_
        for (var i = 0, len = obj.length; i < len; i++) {_x000D_
            copy[i] = Q(obj[i]);_x000D_
        }_x000D_
        return copy;_x000D_
    }_x000D_
_x000D_
    // Handle Object_x000D_
    if (obj instanceof Object) {_x000D_
        copy = {};_x000D_
        for (var attr in obj) {_x000D_
            if (obj.hasOwnProperty(attr)) copy[attr] = Q(obj[attr]);_x000D_
        }_x000D_
        return copy;_x000D_
    }_x000D_
_x000D_
    throw new Error("Unable to copy obj! Its type isn't supported.");_x000D_
}_x000D_
_x000D_
function R(obj) {_x000D_
    const gdcc = "__getDeepCircularCopy__";_x000D_
    if (obj !== Object(obj)) {_x000D_
        return obj; // primitive value_x000D_
    }_x000D_
_x000D_
    var set = gdcc in obj,_x000D_
        cache = obj[gdcc],_x000D_
        result;_x000D_
    if (set && typeof cache == "function") {_x000D_
        return cache();_x000D_
    }_x000D_
    // else_x000D_
    obj[gdcc] = function() { return result; }; // overwrite_x000D_
    if (obj instanceof Array) {_x000D_
        result = [];_x000D_
        for (var i=0; i<obj.length; i++) {_x000D_
            result[i] = R(obj[i]);_x000D_
        }_x000D_
    } else {_x000D_
        result = {};_x000D_
        for (var prop in obj)_x000D_
            if (prop != gdcc)_x000D_
                result[prop] = R(obj[prop]);_x000D_
            else if (set)_x000D_
                result[prop] = R(cache);_x000D_
    }_x000D_
    if (set) {_x000D_
        obj[gdcc] = cache; // reset_x000D_
    } else {_x000D_
        delete obj[gdcc]; // unset again_x000D_
    }_x000D_
    return result;_x000D_
}_x000D_
_x000D_
function S(obj) {_x000D_
    const cache = new WeakMap(); // Map of old - new references_x000D_
_x000D_
    function copy(object) {_x000D_
        if (typeof object !== 'object' ||_x000D_
            object === null ||_x000D_
            object instanceof HTMLElement_x000D_
        )_x000D_
            return object; // primitive value or HTMLElement_x000D_
_x000D_
        if (object instanceof Date) _x000D_
            return new Date().setTime(object.getTime());_x000D_
_x000D_
        if (object instanceof RegExp) _x000D_
            return new RegExp(object.source, object.flags);_x000D_
_x000D_
        if (cache.has(object)) _x000D_
            return cache.get(object);_x000D_
_x000D_
        const result = object instanceof Array ? [] : {};_x000D_
_x000D_
        cache.set(object, result); // store reference to object before the recursive starts_x000D_
_x000D_
        if (object instanceof Array) {_x000D_
            for(const o of object) {_x000D_
                 result.push(copy(o));_x000D_
            }_x000D_
            return result;_x000D_
        }_x000D_
_x000D_
        const keys = Object.keys(object); _x000D_
_x000D_
        for (const key of keys)_x000D_
            result[key] = copy(object[key]);_x000D_
_x000D_
        return result;_x000D_
    }_x000D_
_x000D_
    return copy(obj);_x000D_
}_x000D_
_x000D_
function T(obj){_x000D_
    var clonedObjectsArray = [];_x000D_
    var originalObjectsArray = []; //used to remove the unique ids when finished_x000D_
    var next_objid = 0;_x000D_
_x000D_
    function objectId(obj) {_x000D_
        if (obj == null) return null;_x000D_
        if (obj.__obj_id == undefined){_x000D_
            obj.__obj_id = next_objid++;_x000D_
            originalObjectsArray[obj.__obj_id] = obj;_x000D_
        }_x000D_
        return obj.__obj_id;_x000D_
    }_x000D_
_x000D_
    function cloneRecursive(obj) {_x000D_
        if (null == obj || typeof obj == "string" || typeof obj == "number" || typeof obj == "boolean") return obj;_x000D_
_x000D_
        // Handle Date_x000D_
        if (obj instanceof Date) {_x000D_
            var copy = new Date();_x000D_
            copy.setTime(obj.getTime());_x000D_
            return copy;_x000D_
        }_x000D_
_x000D_
        // Handle Array_x000D_
        if (obj instanceof Array) {_x000D_
            var copy = [];_x000D_
            for (var i = 0; i < obj.length; ++i) {_x000D_
                copy[i] = cloneRecursive(obj[i]);_x000D_
            }_x000D_
            return copy;_x000D_
        }_x000D_
_x000D_
        // Handle Object_x000D_
        if (obj instanceof Object) {_x000D_
            if (clonedObjectsArray[objectId(obj)] != undefined)_x000D_
                return clonedObjectsArray[objectId(obj)];_x000D_
_x000D_
            var copy;_x000D_
            if (obj instanceof Function)//Handle Function_x000D_
                copy = function(){return obj.apply(this, arguments);};_x000D_
            else_x000D_
                copy = {};_x000D_
_x000D_
            clonedObjectsArray[objectId(obj)] = copy;_x000D_
_x000D_
            for (var attr in obj)_x000D_
                if (attr != "__obj_id" && obj.hasOwnProperty(attr))_x000D_
                    copy[attr] = cloneRecursive(obj[attr]);                 _x000D_
_x000D_
            return copy;_x000D_
        }       _x000D_
_x000D_
_x000D_
        throw new Error("Unable to copy obj! Its type isn't supported.");_x000D_
    }_x000D_
    var cloneObj = cloneRecursive(obj);_x000D_
_x000D_
_x000D_
_x000D_
    //remove the unique ids_x000D_
    for (var i = 0; i < originalObjectsArray.length; i++)_x000D_
    {_x000D_
        delete originalObjectsArray[i].__obj_id;_x000D_
    };_x000D_
_x000D_
    return cloneObj;_x000D_
}_x000D_
_x000D_
function U(obj) {_x000D_
  /*_x000D_
    Deep copy objects by value rather than by reference,_x000D_
    exception: `Proxy`_x000D_
  */_x000D_
_x000D_
  const seen = new WeakMap()_x000D_
_x000D_
  return clone(obj)_x000D_
_x000D_
  function defineProp(object, key, descriptor = {}, copyFrom = {}) {_x000D_
    const { configurable: _configurable, writable: _writable }_x000D_
      = Object.getOwnPropertyDescriptor(object, key)_x000D_
      || { configurable: true, writable: true }_x000D_
_x000D_
    const test = _configurable // Can redefine property_x000D_
      && (_writable === undefined || _writable) // Can assign to property_x000D_
_x000D_
    if (!test || arguments.length <= 2) return test_x000D_
_x000D_
    const basisDesc = Object.getOwnPropertyDescriptor(copyFrom, key)_x000D_
      || { configurable: true, writable: true } // Custom…_x000D_
      || {}; // …or left to native default settings_x000D_
_x000D_
    ["get", "set", "value", "writable", "enumerable", "configurable"]_x000D_
      .forEach(attr =>_x000D_
        descriptor[attr] === undefined &&_x000D_
        (descriptor[attr] = basisDesc[attr])_x000D_
      )_x000D_
_x000D_
    const { get, set, value, writable, enumerable, configurable }_x000D_
      = descriptor_x000D_
_x000D_
    return Object.defineProperty(object, key, {_x000D_
      enumerable, configurable, ...get || set_x000D_
        ? { get, set } // Accessor descriptor_x000D_
        : { value, writable } // Data descriptor_x000D_
    })_x000D_
  }_x000D_
_x000D_
  function clone(object) {_x000D_
    if (object !== Object(object)) return object /*_x000D_
    —— Check if the object belongs to a primitive data type */_x000D_
_x000D_
    if (object instanceof Node) return object.cloneNode(true) /*_x000D_
    —— Clone DOM trees */_x000D_
_x000D_
    let _object // The clone of object_x000D_
_x000D_
    switch (object.constructor) {_x000D_
      case Array:_x000D_
      case Object:_x000D_
        _object = cloneObject(object)_x000D_
        break_x000D_
_x000D_
      case Date:_x000D_
        _object = new Date(+object)_x000D_
        break_x000D_
_x000D_
      case Function:_x000D_
        const fnStr = String(object)_x000D_
_x000D_
        _object = new Function("return " +_x000D_
          (/^(?!function |[^{]+?=>)[^(]+?\(/.test(fnStr)_x000D_
            ? "function " : ""_x000D_
          ) + fnStr_x000D_
        )()_x000D_
_x000D_
        copyPropDescs(_object, object)_x000D_
        break_x000D_
_x000D_
      case RegExp:_x000D_
        _object = new RegExp(object)_x000D_
        break_x000D_
_x000D_
      default:_x000D_
        switch (Object.prototype.toString.call(object.constructor)) {_x000D_
          //                              // Stem from:_x000D_
          case "[object Function]":       // `class`_x000D_
          case "[object Undefined]":      // `Object.create(null)`_x000D_
            _object = cloneObject(object)_x000D_
            break_x000D_
_x000D_
          default:                        // `Proxy`_x000D_
            _object = object_x000D_
        }_x000D_
    }_x000D_
_x000D_
    return _object_x000D_
  }_x000D_
_x000D_
_x000D_
  function cloneObject(object) {_x000D_
    if (seen.has(object)) return seen.get(object) /*_x000D_
    —— Handle recursive references (circular structures) */_x000D_
_x000D_
    const _object = Array.isArray(object)_x000D_
      ? []_x000D_
      : Object.create(Object.getPrototypeOf(object)) /*_x000D_
        —— Assign [[Prototype]] for inheritance */_x000D_
_x000D_
    seen.set(object, _object) /*_x000D_
    —— Make `_object` the associative mirror of `object` */_x000D_
_x000D_
    Reflect.ownKeys(object).forEach(key =>_x000D_
      defineProp(_object, key, { value: clone(object[key]) }, object)_x000D_
    )_x000D_
_x000D_
    return _object_x000D_
  }_x000D_
_x000D_
_x000D_
  function copyPropDescs(target, source) {_x000D_
    Object.defineProperties(target,_x000D_
      Object.getOwnPropertyDescriptors(source)_x000D_
    )_x000D_
  }_x000D_
}_x000D_
 _x000D_
// ------------------------_x000D_
// Test properties_x000D_
// ------------------------_x000D_
_x000D_
_x000D_
console.log(`  shallow deep  func  circ  undefined date  RegExp bigInt`)_x000D_
_x000D_
log(A);_x000D_
log(B);_x000D_
log(C);_x000D_
log(D);_x000D_
log(E);_x000D_
log(F);_x000D_
log(G);_x000D_
log(H);_x000D_
log(I);_x000D_
log(J);_x000D_
log(K);_x000D_
log(L);_x000D_
log(M);_x000D_
log(N);_x000D_
log(O);_x000D_
log(P);_x000D_
log(Q);_x000D_
log(R);_x000D_
log(S);_x000D_
log(T);_x000D_
log(U);_x000D_
_x000D_
console.log(`  shallow deep  func  circ  undefined date  RegExp bigInt_x000D_
----_x000D_
LEGEND:_x000D_
shallow - solution create shallow copy_x000D_
deep - solution create deep copy_x000D_
func - solution copy functions_x000D_
circ - solution can copy object with circular references_x000D_
undefined - solution copy fields with undefined value_x000D_
date - solution can copy date_x000D_
RegExp - solution can copy fields with regular expressions_x000D_
bigInt - solution can copy BigInt_x000D_
`)_x000D_
_x000D_
_x000D_
// ------------------------_x000D_
// Helper functions_x000D_
// ------------------------_x000D_
_x000D_
_x000D_
function deepCompare(obj1,obj2) {_x000D_
  return JSON.stringify(obj1)===JSON.stringify(obj2);_x000D_
}_x000D_
_x000D_
function getCase() { // pure data case_x000D_
  return { _x000D_
    undef: undefined,_x000D_
    bool: true, num: 1, str: "txt1",    _x000D_
    e1: null, e2: [], e3: {}, e4: 0, e5: false,_x000D_
    arr: [ false, 2, "txt3", null, [], {},_x000D_
      [ true,4,"txt5",null, [], {},  [true,6,"txt7",null,[],{} ], _x000D_
        {bool: true,num: 8, str: "txt9", e1:null, e2:[] ,e3:{} ,e4: 0, e5: false}_x000D_
      ],_x000D_
        {bool: true,num: 10, str: "txt11", e1:null, e2:[] ,e3:{} ,e4: 0, e5: false}_x000D_
    ], _x000D_
    obj: { _x000D_
        bool: true, num: 12, str: "txt13",_x000D_
        e1: null, e2: [], e3: {}, e4: 0, e5: false,_x000D_
        arr: [true,14,"txt15",null,[],{} ],_x000D_
        obj: { _x000D_
          bool: true, num: 16, str: "txt17",_x000D_
          e1: null, e2: [], e3: {}, e4: 0, e5: false,_x000D_
          arr: [true,18,"txt19",null,[],{} ],_x000D_
          obj: {bool: true,num: 20, str: "txt21", e1:null, e2:[] ,e3:{} ,e4: 0, e5: false}_x000D_
      } _x000D_
    } _x000D_
  };_x000D_
}_x000D_
_x000D_
function check(org, copy, field, newValue) {_x000D_
  copy[field] = newValue;_x000D_
  return deepCompare(org,copy); _x000D_
}_x000D_
_x000D_
function testFunc(f) {_x000D_
 let o = { a:1, fun: (i,j)=> i+j };_x000D_
  let c = f(o);_x000D_
  _x000D_
  let val = false_x000D_
  try{_x000D_
    val = c.fun(3,4)==7;_x000D_
  } catch(e) { }_x000D_
  return val;_x000D_
} _x000D_
_x000D_
function testCirc(f) {_x000D_
 function Circ() {_x000D_
    this.me = this;_x000D_
  }_x000D_
_x000D_
  var o = {_x000D_
      x: 'a',_x000D_
      circ: new Circ(),_x000D_
      obj_circ: null,_x000D_
  };_x000D_
  _x000D_
  o.obj_circ = o;_x000D_
_x000D_
  let val = false;_x000D_
_x000D_
  try{_x000D_
    let c = f(o);  _x000D_
    val = (o.obj_circ == o) && (o.circ == o.circ.me);_x000D_
  } catch(e) { }_x000D_
  return val;_x000D_
} _x000D_
_x000D_
function testRegExp(f) {_x000D_
  let o = {_x000D_
    re: /a[0-9]+/,_x000D_
  };_x000D_
  _x000D_
  let val = false;_x000D_
_x000D_
  try{_x000D_
    let c = f(o);  _x000D_
    val = (String(c.re) == String(/a[0-9]+/));_x000D_
  } catch(e) { }_x000D_
  return val;_x000D_
}_x000D_
_x000D_
function testDate(f) {_x000D_
  let o = {_x000D_
    date: new Date(),_x000D_
  };_x000D_
  _x000D_
  let val = false;_x000D_
_x000D_
  try{_x000D_
    let c = f(o);  _x000D_
    val = (+new Date(c.date) == +new Date(o.date));_x000D_
  } catch(e) { }_x000D_
  return val;_x000D_
}_x000D_
_x000D_
function testBigInt(f) {_x000D_
  let val = false;_x000D_
  _x000D_
  try{_x000D_
    let o = {_x000D_
      big: 123n,_x000D_
    };_x000D_
  _x000D_
    let c = f(o);  _x000D_
  _x000D_
    val = o.big == c.big;_x000D_
  } catch(e) { }_x000D_
  _x000D_
  return val;_x000D_
}_x000D_
_x000D_
function log(f) {_x000D_
  let o = getCase();  // orginal object_x000D_
  let oB = getCase(); // "backup" used for shallow valid test_x000D_
  _x000D_
  let c1 = f(o); // copy 1 for reference_x000D_
  let c2 = f(o); // copy 2 for test shallow values_x000D_
  let c3 = f(o); // copy 3 for test deep values_x000D_
_x000D_
  let is_proper_copy = deepCompare(c1,o);  // shoud be true_x000D_
  _x000D_
  // shallow changes_x000D_
  let testShallow = _x000D_
    [ ['bool',false],['num',666],['str','xyz'],['arr',[]],['obj',{}] ]_x000D_
    .reduce((acc,curr)=> acc && check(c1,c2,curr[0], curr[1]), true );_x000D_
  _x000D_
  // should be true (original object shoud not have changed shallow fields)_x000D_
  let is_valid = deepCompare(o,oB); _x000D_
_x000D_
  // deep test (intruduce some change)_x000D_
  if (c3.arr[6]) c3.arr[6][7].num = 777;_x000D_
  _x000D_
  let diff_shallow = !testShallow; // shoud be true (shallow field was copied)_x000D_
  let diff_deep = !deepCompare(c1,c3);    // shoud be true (deep field was copied)_x000D_
  let can_copy_functions = testFunc(f);_x000D_
  let can_copy_circular = testCirc(f);_x000D_
  let can_copy_regexp = testRegExp(f);_x000D_
  let can_copy_date = testDate(f);_x000D_
  let can_copy_bigInt = testBigInt(f);_x000D_
  _x000D_
  let has_undefined = 'undef' in c1; // field with undefined value is copied?  _x000D_
  let is_ok = is_valid && is_proper_copy;_x000D_
  let b=(bool) => (bool+'').padEnd(5,' '); // bool value to formated string_x000D_
  _x000D_
  testFunc(f);_x000D_
  _x000D_
  if(is_ok) {_x000D_
    console.log(`${f.name} ${b(diff_shallow)}   ${b(diff_deep)} ${b(can_copy_functions)} ${b(can_copy_circular)} ${b(has_undefined)}     ${b(can_copy_date)} ${b(can_copy_regexp)}  ${b(can_copy_bigInt)}`)_x000D_
  } else {_x000D_
    console.log(`${f.name}: INVALID ${is_valid} ${is_proper_copy}`,{c1})_x000D_
  }_x000D_
  _x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>_x000D_
_x000D_
This snippet only presents tested solutions and show differences between them (but it no make performence tests)
_x000D_
_x000D_
_x000D_

Below there are example results for Chrome for shallow-big object

enter image description here

JavaScript URL Decode function

Here is a complete function (taken from PHPJS):

function urldecode(str) {
   return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}

How to sleep the thread in node.js without affecting other threads?

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.

This method is sort of similar to a while (!condition) sleep loop, but yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.

export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:

async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}

How to create correct JSONArray in Java using JSONObject

Here is some code using java 6 to get you started:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();

How can I convert a string with dot and comma into a float in Python

Just replace, with replace().

f = float("123,456.908".replace(',','')) print(type(f)

type() will show you that it has converted into a float

Favicon not showing up in Google Chrome

I read a bunch of different entries till I finally found a solution that worked for my scenario (ASP.NET MVC4 project).

Instead of using the filename favicon.ico for my icon, I renamed it to something else, ie myIcon.ico. Then I just used exactly what Domi posted:

<link rel="shortcut icon" href="myIcon.ico" type="image/x-icon" />

And this worked!

It's not a caching issue because I tested this with Fiddler - a request for favicon never occurred, even if I cleared my cache "From the beginning of time". I believe it's just some odd bug with chrome?

Entity Framework select distinct name

Entity-Framework Select Distinct Name:

Suppose if you are want every first data of particular column of each group ;

 var data = objDb.TableName.GroupBy(dt => dt.ColumnName).Select(dt => new { dt.Key }).ToList();

            foreach (var item in data)
            {
                var data2= objDb.TableName.Where(dt=>dt.ColumnName==item.Key).Select(dt=>new {dt.SelectYourColumn}).Distinct().FirstOrDefault();

               //Eg.
                {
                       ListBox1.Items.Add(data2.ColumnName);                    
                }

            }

How can you make a custom keyboard in Android?

First of all you will need a keyboard.xml file which will be placed in the res/xml folder (if the folder does not exist, created it).

<?xml version="1.0" encoding="utf-8"?> 
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="15%p"
    android:keyHeight="15%p" >

    <Row>
        <Key android:codes="1"    android:keyLabel="1" android:horizontalGap="4%p"/>
        <Key android:codes="2"    android:keyLabel="2" android:horizontalGap="4%p"/>
        <Key android:codes="3"    android:keyLabel="3" android:horizontalGap="4%p" />
        <Key android:codes="4"    android:keyLabel="4" android:horizontalGap="4%p" />
        <Key android:codes="5"    android:keyLabel="5" android:horizontalGap="4%p" />
    </Row>
    <Row>
        <Key android:codes="6"    android:keyLabel="6" android:horizontalGap="4%p"/>
        <Key android:codes="7"    android:keyLabel="7" android:horizontalGap="4%p"/>
        <Key android:codes="8"    android:keyLabel="8" android:horizontalGap="4%p" />
        <Key android:codes="9"    android:keyLabel="9" android:horizontalGap="4%p" />
        <Key android:codes="0"    android:keyLabel="0" android:horizontalGap="4%p" />
    </Row>

    <Row>
        <Key android:codes="-1"    android:keyIcon="@drawable/backspace" android:keyWidth="34%p" android:horizontalGap="4%p"/>
        <Key android:codes="100"    android:keyLabel="Enter" android:keyWidth="53%p" android:horizontalGap="4%p"/>
    </Row>
 </Keyboard>

**Note that you will have to create the backspace drawable and place it in the res/drawable-ldpi folder with a very small size (like 18x18 pixels)

Then in the xml file that you want it to be used (where your TextView is in) you should add the following code:

<RelativeLayout
 ...
>

        .....


        <android.inputmethodservice.KeyboardView
             android:id="@+id/keyboardview"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_alignParentBottom="true"
             android:layout_centerHorizontal="true"
             android:focusable="true"
             android:focusableInTouchMode="true"
             android:visibility="gone" 
         />
         
        ......


</RelativeLayout>

**Note that the xml file that you will place the android.inputmethodservice.KeyboardView in, has to be RelativeLayout in order to be able to set the alignParentBottom="true" (Usually the keyboards are presented in the bottom of the screen)

Then you need to add the following code in the onCreate function of the Activity that handles the TextView you want to attach the keyboard to

    // Create the Keyboard
    mKeyboard= new Keyboard(this,R.xml.keyboard);

    // Lookup the KeyboardView
    mKeyboardView= (KeyboardView)findViewById(R.id.keyboardview);
    // Attach the keyboard to the view
    mKeyboardView.setKeyboard( mKeyboard );
    
    // Do not show the preview balloons
    //mKeyboardView.setPreviewEnabled(false);
    
    // Install the key handler
    mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);

**Note that mKeyboard and mKeyboardView are private class variables that you have to create.

Then you need the following function for opening the keyboard ( you must associate it with the TextView through the onClick xml property)

    public void openKeyboard(View v)
    {
       mKeyboardView.setVisibility(View.VISIBLE);
       mKeyboardView.setEnabled(true);
       if( v!=null)((InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

And finally you need the OnKeyboardActionListener that will handle your events

private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {
    @Override public void onKey(int primaryCode, int[] keyCodes) 
    {
         //Here check the primaryCode to see which key is pressed 
         //based on the android:codes property
         if(primaryCode==1)
         {
            Log.i("Key","You just pressed 1 button");
         }
    }

    @Override public void onPress(int arg0) {
    }

    @Override public void onRelease(int primaryCode) {
    }

    @Override public void onText(CharSequence text) {
    }

    @Override public void swipeDown() {
    }

    @Override public void swipeLeft() {
    }

    @Override public void swipeRight() {
    }

    @Override public void swipeUp() {
    }
};

Hope that helps!!!

Most of the code found here

____________________________________________________________-

EDIT:

Since KeyboardView is depreciated since API level 29, you can find its code in this website and create a class in your code before implementing the keyboard as described above.

How can I fill a column with random numbers in SQL? I get the same value in every row

require_once('db/connect.php');

//rand(1000000 , 9999999);

$products_query = "SELECT id FROM products";
$products_result = mysqli_query($conn, $products_query);
$products_row = mysqli_fetch_array($products_result);
$ids_array = [];

do
{
    array_push($ids_array, $products_row['id']);
}
while($products_row = mysqli_fetch_array($products_result));

/*
echo '<pre>';
print_r($ids_array);
echo '</pre>';
*/
$row_counter = count($ids_array);

for ($i=0; $i < $row_counter; $i++)
{ 
    $current_row = $ids_array[$i];
    $rand = rand(1000000 , 9999999);
    mysqli_query($conn , "UPDATE products SET code='$rand' WHERE id='$current_row'");
}

Windows batch: sleep

To wait 10 seconds:

choice /T 10 /C X /D X /N

How can I create 2 separate log files with one log4j config file?

Modify your log4j.properties file accordingly:

log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog

Change the log levels for each logger depending to your needs.

Java: set timeout on a certain block of code?

EDIT: Peter Lawrey is completely right: it's not as simple as interrupting a thread (my original suggestion), and Executors & Callables are very useful ...

Rather than interrupting threads, you could set a variable on the Callable once the timeout is reached. The callable should check this variable at appropriate points in task execution, to know when to stop.

Callables return Futures, with which you can specify a timeout when you try to 'get' the future's result. Something like this:

try {
   future.get(timeoutSeconds, TimeUnit.SECONDS)
} catch(InterruptedException e) {
   myCallable.setStopMeAtAppropriatePlace(true);
}

See Future.get, Executors, and Callable ...

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html#get-long-java.util.concurrent.TimeUnit-

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool%28int%29

Laravel 5.4 create model, controller and migration in single artisan command

Updated

Laravel 6 Through the model

To Generate a migration, seeder, factory, and resource controller for the model

php artisan make:model Todo -a

Or

php artisan make:model Todo -all

Other Options

-c, --controller Create a new controller for the model

-f, --factory Create a new factory for the model

--force Create the class even if the model already exists

-m, --migration Create a new migration file for the model

-s, --seed Create a new seeder file for the model

-p, --pivot Indicates if the generated model should be a custom inte rmediate table model

-r, --resource Indicates if the generated controller should be a resour ce controller

For More Help

php artisan make:model Todo -help

Hope Newbies will get help.

Difference between SelectedItem, SelectedValue and SelectedValuePath

Their names can be a bit confusing :). Here's a summary:

  • The SelectedItem property returns the entire object that your list is bound to. So say you've bound a list to a collection of Category objects (with each Category object having Name and ID properties). eg. ObservableCollection<Category>. The SelectedItem property will return you the currently selected Category object. For binding purposes however, this is not always what you want, as this only enables you to bind an entire Category object to the property that the list is bound to, not the value of a single property on that Category object (such as its ID property).

  • Therefore we have the SelectedValuePath property and the SelectedValue property as an alternative means of binding (you use them in conjunction with one another). Let's say you have a Product object, that your view is bound to (with properties for things like ProductName, Weight, etc). Let's also say you have a CategoryID property on that Product object, and you want the user to be able to select a category for the product from a list of categories. You need the ID property of the Category object to be assigned to the CategoryID property on the Product object. This is where the SelectedValuePath and the SelectedValue properties come in. You specify that the ID property on the Category object should be assigned to the property on the Product object that the list is bound to using SelectedValuePath='ID', and then bind the SelectedValue property to the property on the DataContext (ie. the Product).

The example below demonstrates this. We have a ComboBox bound to a list of Categories (via ItemsSource). We're binding the CategoryID property on the Product as the selected value (using the SelectedValue property). We're relating this to the Category's ID property via the SelectedValuePath property. And we're saying only display the Name property in the ComboBox, with the DisplayMemberPath property).

<ComboBox ItemsSource="{Binding Categories}" 
          SelectedValue="{Binding CategoryID, Mode=TwoWay}" 
          SelectedValuePath="ID" 
          DisplayMemberPath="Name" />
public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class Product
{
    public int CategoryID { get; set; }
}

It's a little confusing initially, but hopefully this makes it a bit clearer... :)

Chris

SMTPAuthenticationError when sending mail using gmail and python

Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct

EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

I got this issue while installing transformers library from HuggingFace. It was due to the fact package enum34 was installed in my environment which was overriding built-in enum in Python. This package was probably installed by something as for forward compatibility which is no longer needed with Python 3.6+. So the solution is simply,

pip uninstall -y enum34

Disable native datepicker in Google Chrome

I know this is an old question now, but I just landed here looking for information about this so somebody else might too.

You can use Modernizr to detect whether the browser supports HTML5 input types, like 'date'. If it does, those controls will use the native behaviour to display things like datepickers. If it doesn't, you can specify what script should be used to display your own datepicker. Works well for me!

I added jquery-ui and Modernizr to my page, then added this code:

<script type="text/javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(initDateControls);
    initDateControls();

    function initDateControls() {
        //Adds a datepicker to inputs with a type of 'date' when the browser doesn't support that HTML5 tag (type=date)'
        Modernizr.load({
            test: Modernizr.inputtypes.datetime,
            nope: "scripts/jquery-ui.min.js",
            callback: function () {
                $("input[type=date]").datepicker({ dateFormat: "dd-mm-yy" });
            }
        });
    }

</script>

This means that the native datepicker is displayed in Chrome, and the jquery-ui one is displayed in IE.

ALTER TABLE on dependent column

I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.

ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl) 
    REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back

However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)

How to get the previous url using PHP

$_SERVER['HTTP_REFERER'] is the answer

Remove HTML tags from a String

It sounds like you want to go from HTML to plain text.
If that is the case look at www.htmlparser.org. Here is an example that strips all the tags out from the html file found at a URL.
It makes use of org.htmlparser.beans.StringBean.

static public String getUrlContentsAsText(String url) {
    String content = "";
    StringBean stringBean = new StringBean();
    stringBean.setURL(url);
    content = stringBean.getStrings();
    return content;
}

How can I reset eclipse to default settings?

You can reset settings for eclipse by deleting .metadata folder from your current workspace.

This will however remove all projects from your project explorer NOT workspace. So dont worry your projects have not gone anywhere.

You can import projects from your workspace like this : just make sure that you uncheck "Copy project into workspace".

import Have a look here : import project in eclipse

Split a string into an array of strings based on a delimiter

Using the SysUtils.TStringHelper.Split function, introduced in Delphi XE3:

var
  MyString: String;
  Splitted: TArray<String>;
begin
  MyString := 'word:doc,txt,docx';
  Splitted := MyString.Split([':']);
end.

This will split a string with a given delimiter into an array of strings.

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

Rails raw SQL example

I know this is old... But I was having the same problem today and found a solution:

Model.find_by_sql

If you want to instantiate the results:

Client.find_by_sql("
  SELECT * FROM clients
  INNER JOIN orders ON clients.id = orders.client_id
  ORDER BY clients.created_at desc
")
# => [<Client id: 1, first_name: "Lucas" >, <Client id: 2, first_name: "Jan">...]

Model.connection.select_all('sql').to_hash

If you just want a hash of values:

Client.connection.select_all("SELECT first_name, created_at FROM clients
   WHERE id = '1'").to_hash
# => [
  {"first_name"=>"Rafael", "created_at"=>"2012-11-10 23:23:45.281189"},
  {"first_name"=>"Eileen", "created_at"=>"2013-12-09 11:22:35.221282"}
]

Result object:

select_all returns a result object. You can do magic things with it.

result = Post.connection.select_all('SELECT id, title, body FROM posts')
# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

Sources:

  1. ActiveRecord - Findinig by SQL.
  2. Ruby on Rails - Active Record Result .

Changing the current working directory in Java?

There is a way to do this using the system property "user.dir". The key part to understand is that getAbsoluteFile() must be called (as shown below) or else relative paths will be resolved against the default "user.dir" value.

import java.io.*;

public class FileUtils
{
    public static boolean setCurrentDirectory(String directory_name)
    {
        boolean result = false;  // Boolean indicating whether directory was set
        File    directory;       // Desired current working directory

        directory = new File(directory_name).getAbsoluteFile();
        if (directory.exists() || directory.mkdirs())
        {
            result = (System.setProperty("user.dir", directory.getAbsolutePath()) != null);
        }

        return result;
    }

    public static PrintWriter openOutputFile(String file_name)
    {
        PrintWriter output = null;  // File to open for writing

        try
        {
            output = new PrintWriter(new File(file_name).getAbsoluteFile());
        }
        catch (Exception exception) {}

        return output;
    }

    public static void main(String[] args) throws Exception
    {
        FileUtils.openOutputFile("DefaultDirectoryFile.txt");
        FileUtils.setCurrentDirectory("NewCurrentDirectory");
        FileUtils.openOutputFile("CurrentDirectoryFile.txt");
    }
}

CSS3 transition doesn't work with display property

max-height

.PrimaryNav-container {
...
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease;
...
}

.PrimaryNav.PrimaryNav--isOpen .PrimaryNav-container {
max-height: 300px;
}

https://www.codehive.io/boards/bUoLvRg

How do I programmatically determine operating system in Java?

You can use:

System.getProperty("os.name")

P.S. You may find this code useful:

class ShowProperties {
    public static void main(String[] args) {
        System.getProperties().list(System.out);
    }
}

All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)

Sort array by value alphabetically php

Note that sort() operates on the array in place, so you only need to call

sort($a);
doSomething($a);

This will not work;

$a = sort($a);
doSomething($a);

What is an idempotent operation?

Quite a detailed and technical answers. Just adding a simple definition.

Idempotent = Re-runnable

For example, Create operation in itself is not guaranteed to run without error if executed more than once. But if there is an operation CreateOrUpdate then it states re-runnability (Idempotency).

How to Set Active Tab in jQuery Ui

Inside your function for the click action use

$( "#tabs" ).tabs({ active: # });

Where # is replaced by the tab index you want to select.

Edit: change from selected to active, selected is deprecated

Turn a number into star rating display using jQuery and CSS

DEMO

You can do it with 2 images only. 1 blank stars, 1 filled stars.

Overlay filled image on the top of the other one. and convert rating number into percentage and use it as width of fillter image.

enter image description here

.containerdiv {
  border: 0;
  float: left;
  position: relative;
  width: 300px;
} 
.cornerimage {
  border: 0;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
 } 
 img{
   max-width: 300px;
 }

Hibernate: How to fix "identifier of an instance altered from X to Y"?

Are you changing the primary key value of a User object somewhere? You shouldn't do that. Check that your mapping for the primary key is correct.

What does your mapping XML file or mapping annotations look like?

JavaScript/jQuery - How to check if a string contain specific words

This will

/\bword\b/.test("Thisword is not valid");

return false, when this one

/\bword\b/.test("This word is valid");

will return true.

How do I align a number like this in C?

Looking at the edited question, you need to find the number of digits in the largest number to be presented, and then generate the printf() format using sprintf(), or using %*d with the number of digits being passed as an int for the * and then the value. Once you've got the biggest number (and you have to determine that in advance), you can determine the number of digits with an 'integer logarithm' algorithm (how many times can you divide by 10 before you get to zero), or by using snprintf() with the buffer length of zero, the format %d and null for the string; the return value tells you how many characters would have been formatted.

If you don't know and cannot determine the maximum number ahead of its appearance, you are snookered - there is nothing you can do.

Create directory if it does not exist

[System.IO.Directory]::CreateDirectory('full path to directory')

This internally checks for directory existence, and creates one, if there is no directory. Just one line and native .NET method working perfectly.

TypeError: argument of type 'NoneType' is not iterable

If a function does not return anything, e.g.:

def test():
    pass

it has an implicit return value of None.

Thus, as your pick* methods do not return anything, e.g.:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")

the lines that call them, e.g.:

word = pickEasy()

set word to None, so wordInput in getInput is None. This means that:

if guess in wordInput:

is the equivalent of:

if guess in None:

and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

The fix is to add the return type:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

C# list.Orderby descending

Yes. Use OrderByDescending instead of OrderBy.

Nginx: Job for nginx.service failed because the control process exited

  • use these command to

    1. sudo service apache2 stop

    2. sudo apt-get purge apache2

    3. sudo apt-get update

    4. sudo apt-get install nginx

    5. sudo service nginx restart

Why is setState in reactjs Async instead of Sync?

Good article here https://github.com/vasanthk/react-bits/blob/master/patterns/27.passing-function-to-setState.md

// assuming this.state.count === 0
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
// this.state.count === 1, not 3

Solution
this.setState((prevState, props) => ({
  count: prevState.count + props.increment
}));

or pass callback this.setState ({.....},callback)

https://medium.com/javascript-scene/setstate-gate-abc10a9b2d82 https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b

Setting the selected attribute on a select list using jQuery

Code:

var select = function(dropdown, selectedValue) {
    var options = $(dropdown).find("option");
    var matches = $.grep(options,
        function(n) { return $(n).text() == selectedValue; });
    $(matches).attr("selected", "selected");
};

Example:

select("#dropdown", "B");

C++: Converting Hexadecimal to Decimal

I use this:

template <typename T>
bool fromHex(const std::string& hexValue, T& result)
{
    std::stringstream ss;
    ss << std::hex << hexValue;
    ss >> result;

    return !ss.fail();
}

Create SQL script that create database and tables

Yes, you can add as many SQL statements into a single script as you wish. Just one thing to note: the order matters. You can't INSERT into a table until you CREATE it; you can't set a foreign key until the primary key is inserted.

Component based game engine design

I am currently researching this exact topic in the many (MANY) threads at GameDev.net and found the following two solutions to be good candidates on what I will develop for my game:

How to read text files with ANSI encoding and non-English letters?

If I remember correctly the XmlDocument.Load(string) method always assumes UTF-8, regardless of the XML encoding. You would have to create a StreamReader with the correct encoding and use that as the parameter.

xmlDoc.Load(new StreamReader(
                     File.Open("file.xml"), 
                     Encoding.GetEncoding("iso-8859-15"))); 

I just stumbled across KB308061 from Microsoft. There's an interesting passage: Specify the encoding declaration in the XML declaration section of the XML document. For example, the following declaration indicates that the document is in UTF-16 Unicode encoding format:

<?xml version="1.0" encoding="UTF-16"?>

Note that this declaration only specifies the encoding format of an XML document and does not modify or control the actual encoding format of the data.

Link Source:

XmlDocument.Load() method fails to decode € (euro)