text:
Q: Firefox: Long lines in text area not visible If you have long lines in a text area of Firefox, you can't see whether there is one long line or whether there are several short lines.
I've attached two screen shots as an example.
Firefox:

Emacs:

Is there a way to configure firefox to show me long lines which get wrapped?
I don't care how this gets done. But I think the arrow symbols used by emacs fit.

A: I can see 2 methods that will partially meet your needs:

*

*The masking or wrapping of such lines in Firefox are because Firefox by default obeys the css built into the page. One way to view the page without the css, and thus see the raw number display, is to install the web developer toolbar:
Web Developer
and then toggle the css display by using the key combination:
Alt+Shift+A

*Another choice is to perhaps permanently display all long lines without line wrapping. This was a behavior introduced with Firefox 22 as explained here. To reverse this you will need to follow these steps (taken from the linked article):

*

*Type about:config into the address bar and hit enter.

*Confirm that you will be careful if this is the first time you open this page

*Use the search at the top to filter for plain_text.wrap_long_lines.

*Double-click the value to set it to false which deactivates the feature.

*To restore the original value at any time, repeat the steps abov

Not exactly what you are after but probably as close as you will get...

A: If you want to see whether there is one long line or whether there are several short lines - there is a simple way to tell. Just resize your Firefox window (to a larger width, if possible). If the text re-flows to fit the new width then it is a single long (logical) line. If it keeps the same lines, then these are multiple short lines.
You can also get some hint when resizing to a smaller width. If you have multiple short lines they may wrap into two lines but you will be able to detect the line breaks.
This method works with many text-centric web pages, for example this one. Other web pages display text with a fixed line width regardless of the window size (this very page is an example). With these pages, resizing won't provide any information, unless you tweak the text properties (e.g. as suggested by @andrew.46).


text:
Q: Handle command-line switch in Ruby without if...else block In a blog post about unconditional programming Michael Feathers shows how limiting if statements can be used as a tool for reducing code complexity.
He uses a specific example to illustrate his point. Now, I've been thinking about other specific examples that could help me learn more about unconditional/ifless/forless programming.
For example, using OptionParser I made a cat clone that will upcase the stream if the --upcase switch is set:
#!/usr/bin/env ruby

require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: cat [options] [file ...]"

  opts.on("-u", "--upcase", "Upcase stream") do
    options[:upcase] = true
  end
end.parse!

if options[:upcase]
  puts ARGF.read.upcase
else
  puts ARGF.read
end

How would I handle that switch without an if..else block?
Also interested in links to other illustrative specific examples.

A: Try this,
#!/usr/bin/env ruby
require 'optparse'

options = { :transform => :itself }
OptionParser.new do |opts|
  opts.banner = "Usage: cat [options] [file ...]"
  opts.on("-u", "--upcase", "Upcase stream") do
    options[:transform] = :upcase
  end
  # add more options for downcase, reverse, etc ...
end.parse!

puts ARGF.read.send(options[:transform])

This worked quite well, I am actually surprised how well that worked.
What has been changed?

*

*The option is internally renamed to :transform

*The internal default value is :itself

*The command line switch sets the internal option to :upcase

*Call the method with send
Not all if statements can be improved upon like this though. I would guess the idea of unconditional programming is to prefer a combination of meaningful default values, as I did above, and intention revealing functions whenever it seems reasonable but not at all costs.
Here are some examples of intention revealing functions,

*

*max

*min

*Hash#fetch

*Enumerable#detect

*Enumerable#select

*Enumerable#chunk

*Enumerable#drop_while

*Enumerable#slice_when

*Enumerable#take_while

*etc...

Another related practice is forless programming.
If you want to practice unconditional and forless programming best look for examples that process arrays and strings and make use of the many "functional" methods in Ruby's enumerable module.
Here is an example of string justification without for and if,
str = 'This is an example to be aligned to both margins'
words = str.split
width, remainder = (50 - words.map(&:length).inject(:+)).divmod(words.length - 1)
words.take(words.length - 1).each { |each| width.times { each << 32 }}
words.take(words.length - 1).shuffle.take(remainder).each { |each| each << 32 }
p words.join
# => "This  is an example to  be aligned to both margins"

A: Eliminating conditions is a tool for reducing complexity, not an end goal. I explained that better in my other answer. In this case the condition must be there because whether or not options[:upcase] is set is part of the logic. But you can at least eliminate the duplication.
Because the else clause is the same as the if clause but just adds a step, you can remove the repetition and make your code linear by unconditionally doing the common bit, and then conditionally doing the extra stuff.
data = ARGF.read;
data.upcase! if options[:upcase];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connecting from sqlite database in rails I am facing problem with connecting with the SQLite database, instead of MySQL.
Can anyone please tell me the procedure to connect with the SQLite database from Rails.
Thanks in advance.
Anu.

A: Simply follow these instructions.


text:
Q: Which version of Xcode supported in iPhone XR the iPhone XR is running ios 12.4.1(16G102),which may not be supported by this version of Xcode
the running version of Xcode is 10.14

A: You can download zip from here and unzip it. And copy to dir /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport.
Final restart Xcode, your Xcode will support iOS 12.4.1 device


text:
Q: Does Basic "hello world" run as CGI.? My question is simple.
I install apache on centos and create a file as index.html and just add the content of "hello world".
Now, when I access my web it display the "hello world" quote. My question is does this process run as CGI or Apache-handler or any other API.?

A: No, a file ending .html is by default just treated as static HTML.


text:
Q: Why I cant connect to the database by connection string? I have a database on a local network.
I can connect to the database in SSMS:

But when I want to connect to the database by this connection string in c#:
"Data Source=192.168.0.3,14330;Network Library=DBMSSOCN;Initial Catalog=master;Integrated Security=True;User ID=sa;Password=123456789;"

I get the following error:

Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.

A: Your are telling sql server to use integrated security, ie windows security, however you trying to use a username and password
turn integrated security off, see the below example
"Data Source=192.168.0.3,14330;Network Library=DBMSSOCN;Initial Catalog=master;Integrated Security=False;User ID=sa;Password=123456789;"

Pertinent information
If User ID and Password are specified and Integrated Security is set to true, the User ID and Password will be ignored and Integrated Security will be used.
You can find more information on connection strings here, SqlConnection.ConnectionString Property
Update
maybe this question may help you more How to get the connection String from a database
Update 2
For more in depth troubleshooting, there is a great resource here How to Troubleshoot Connecting to the SQL Server Database Engine


text:
Q: Changing text value for each list item in flutter I have a list of buttons. onPressed function triggers datePicker function, after choosing date, button's text should change to the picked date. Each date is saved to a list of DateTime values, 'dates', which I use later. Dates list and the listView are dynamic, their length depends on the number chosen by user.  I've initiallized buttonText and set its value in initState to 'date'. The problem is, after picking date, each button displays the same date.
Future<DateTime> _pickDate() async {
    DateTime chosen = DateTime.now();
    DateTime date = await showDatePicker(
        context: context,
        initialDate: pickedDate,
        firstDate: DateTime(DateTime.now().year - 100),
        lastDate: DateTime.now());
    if (date != null) {
      setState(() {
        chosen = date;
        print(chosen);
        dates.add(chosen);
        print(dates);
      });
    }
    return chosen;
  }

Widget _dateList() {
    return Container(
      margin: EdgeInsets.all(10),
      width: MediaQuery.of(context).size.width * 0.8,
      height: MediaQuery.of(context).size.height * 0.1,
      decoration: BoxDecoration(
          //border: Border.all(
          //  color: Colors.red
          // )
          ),
      child: ListView.builder(
          scrollDirection: Axis.horizontal,
          shrinkWrap: true,
          itemCount:
              pregController.text == '' ? 0 : int.parse(pregController.text),
          itemBuilder: (BuildContext context, int index) {
            DateTime birth = DateTime.now();
            return Container(
              padding: EdgeInsets.all(5),
              width: MediaQuery.of(context).size.width * 0.3,
              child: RaisedButton(
                  color: Colors
                      .primaries[Random().nextInt(Colors.primaries.length)],
                  key: Key(index.toString()),
                  child: Text(
                    buttonText,
                    textAlign: TextAlign.center,
                    style: GoogleFonts.lato(
                        textStyle: TextStyle(
                      color: Colors.white,
                    )),
                  ),
                  onPressed: () async {
                    birth = await _pickDate();
                    setState(() {
                      buttonText =
                          '${dates[index].day}/${dates[index].month}/${dates[index].year}';
                    });
                  }),
            );
          }),
    );
  }

A: Try something like this:
class Test1 extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => Test1State();

}

class Test1State extends State<Test1> {
  List<DateTime> dates = [
    DateTime.now(),
    DateTime.now(),
    DateTime.now(),
    DateTime.now(),
    DateTime.now(),
  ];

  @override
  Widget build(BuildContext context) => Scaffold(
    body: _dateList(),
  );

  Future<DateTime> _pickDate(DateTime initialDate) async {
    DateTime chosen = DateTime.now();
    DateTime date = await showDatePicker(
        context: context,
        initialDate: initialDate,
        firstDate: DateTime(DateTime.now().year - 100),
        lastDate: DateTime.now());
    if (date != null) {
      setState(() {
        chosen = date;
        print(chosen);
        dates.add(chosen);
        print(dates);
      });
    }
    return chosen;
  }

  Widget _dateList() {
    return Container(
      margin: EdgeInsets.all(10),
      width: MediaQuery.of(context).size.width * 0.8,
      height: MediaQuery.of(context).size.height * 0.1,
      decoration: BoxDecoration(
        //border: Border.all(
        //  color: Colors.red
        // )
      ),
      child: ListView.builder(
          scrollDirection: Axis.horizontal,
          shrinkWrap: true,
          itemCount: dates.length,
          itemBuilder: (BuildContext context, int index) {
            DateTime birth = DateTime.now();
            return Container(
              padding: EdgeInsets.all(5),
              width: MediaQuery.of(context).size.width * 0.3,
              child: RaisedButton(
                  color: Colors
                      .primaries[Random().nextInt(Colors.primaries.length)],
                  key: Key(index.toString()),
                  child: Text(
                    '${dates[index].day}/${dates[index].month}/${dates[index].year}',
                    textAlign: TextAlign.center,
                  ),
                  onPressed: () async {
                    birth = await _pickDate(birth);
                    setState(() {
                      dates[index] = birth;
                    });
                  }),
            );
          }),
    );
  }

}


text:
Q: Listen to multiple RTSP Streams I plan on having multiple RTSP streaming servers on the same network:
rtsp://192.168.1.2
rtsp://192.168.1.3
rtsp://192.168.1.x
Is there any way I can listen to all of them in Windows 7 at the same time?  I don't need them to be synchronized into a file, but saving them to a file would be a plus.

A: First of all - since RTSP is a protocol with no defined standard codec - ensure that you have the correct codecs on your computer to decypher the stream when you have received it.
Onve you have managed to get your hands on the codecs, there are loads of freeware and open source RTSP capable media players - VLC Media player for instance
Regarding yoru wish to record the feeds in real time - again, a program like VLC has "save/convert" functionality which can capture a network feed from RTSP and save in a format to your PC.
Lastly, the aforementioned (sp?) software also supports opening multiple instances... as do many other media players which fulfill your criteria.
Ben


text:
Q: Can't change font color on Hover - Bootstrap Navbar So, I have a sub-navbar, which on hover only changes the color of the
 and not of the text. Here is my code for your reference. What am I missing? I'm sure this is something really minor, that I am overlooking.

.section-navbar {
    margin: -10px 0 0 -12px;
}

.section-navbar>ul {
    margin: 0px 0 -35px 0px;
    padding: 2px 0px;
    background-color: #ececec;
    height: 32px;
}

.section-navbar>ul>li {
    display: block;
    float: left;
    height: 30px;
    text-align: center;
    background-color: #ececec;
    border-right-color: #fff;
    border-right-width: thin;
    border-right-style: solid;
    border-radius: 2px;
    font-weight: normal;
    font-size: 12px;
    padding: 5px 20px;
}

.section-navbar>ul>li>a {
    display: inline-block;
    color: #999;
    text-decoration: none;
}

.section-navbar>ul>li.active {
    background-color: #0083ca;
    border-radius: 2px;
    border-top-color: #359dd5;
    border-top-style: solid;
    border-top-width: medium;
    text-decoration: none;
    padding: 7px 20px;
    margin-top: -5px;
    color: #fff;
    font-weight:bold;
    letter-spacing:0.5px;
    height: 35px;
}

.section-navbar>ul>li:hover {
    background-color: #0083ca;
    border-radius: 2px;
    border-top-color: #359dd5;
    border-top-style: solid;
    border-top-width: medium;
    text-decoration: none;
    margin: -5px 0;
    height:35px;
    color: #fff;
}

Search

Option 2

Lorem ipsum dolor sit

Option 4

A:

.section-navbar {
    margin: -10px 0 0 -12px;
}

.section-navbar>ul {
    margin: 0px 0 -35px 0px;
    padding: 2px 0px;
    background-color: #ececec;
    height: 32px;
}

.section-navbar>ul>li {
    display: block;
    float: left;
    height: 30px;
    text-align: center;
    background-color: #ececec;
    border-right-color: #fff;
    border-right-width: thin;
    border-right-style: solid;
    border-radius: 2px;
    font-weight: normal;
    font-size: 12px;
    padding: 5px 20px;
}

.section-navbar>ul>li>a {
    display: inline-block;
    color: #999;
    text-decoration: none;
}

.section-navbar>ul>li.active {
    background-color: #0083ca;
    border-radius: 2px;
    border-top-color: #359dd5;
    border-top-style: solid;
    border-top-width: medium;
    text-decoration: none;
    padding: 7px 20px;
    margin-top: -5px;
    color: #fff;
    font-weight:bold;
    letter-spacing:0.5px;
    height: 35px;
}

.section-navbar > ul > li:hover a {color:red}

.section-navbar>ul>li:hover {
    background-color: #0083ca;
    border-radius: 2px;
    border-top-color: #359dd5;
    border-top-style: solid;
    border-top-width: medium;
    text-decoration: none;
    margin: -5px 0;
    height:35px;
    color: red!important;
}

Search

Option 2

Lorem ipsum dolor sit

Option 4

A: you have to work in this class given below.
   .section-navbar > ul > li:hover a {
     color:red
    }

A: Added :hover style for a. Also changed padding to a , so that the whole area is clickable.

.section-navbar {
margin: -10px 0 0 -12px;
}

.section-navbar>ul {
margin: 0px 0 -35px 0px;
padding: 2px 0px;
background-color: #ececec;
height: 32px;
}

.section-navbar>ul>li {
display: block;
float: left;
height: 30px;
text-align: center;
background-color: #ececec;
border-right-color: #fff;
border-right-width: thin;
border-right-style: solid;
border-radius: 2px;
font-weight: normal;
font-size: 12px;
}

.section-navbar>ul>li>a {
display: inline-block;
color: #999;
text-decoration: none;
padding: 5px 20px;
height: 25px;
}
.section-navbar>ul>li>a:hover{
color: #fff;
}
.section-navbar>ul>li.active {
background-color: #0083ca;
border-radius: 2px;
border-top-color: #359dd5;
border-top-style: solid;
border-top-width: medium;
text-decoration: none;
padding: 7px 20px;
margin-top: -5px;
color: #fff;
font-weight:bold;
letter-spacing:0.5px;
height: 35px;
padding: 5px 20px;
}

.section-navbar>ul>li:hover {
background-color: #0083ca;
border-radius: 2px;
border-top-color: #359dd5;
border-top-style: solid;
border-top-width: medium;
text-decoration: none;
margin: -5px 0;
height:35px;
color: #fff;
}

Search

Option 2

Lorem ipsum dolor sit

Option 4


text:
Q: How exactly does this delegating recursion example from YDKJS work? I started reading You Don't Know JS: Async and Performance and tripped at delegating recursion example: I went through the code mentally and got the right result, but can't comprehend the description of the intermediate steps in the book.
Tried inserting console.log() into the functions' body, tried debugger to examine the call stack and still cannot conform my mental model of the code to the one, that's in the book.
function run(), which gets generator function as parameter, creates its instance and run it to the end, passing each previously yielded value to the next() call.
function run(gen) {
    var args = [].slice.call( arguments, 1), it;

    // initialize the generator in the current context
    it = gen.apply( this, args );

    // return a promise for the generator completing
    return Promise.resolve()
        .then( function handleNext(value){
            // run to the next yielded value
            var next = it.next( value );

            return (function handleResult(next){
                // generator has completed running?
                if (next.done) {
                    return next.value;
                }
                // otherwise keep going
                else {
                    return Promise.resolve( next.value )
                        .then(
                            // resume the async loop on
                            // success, sending the resolved
                            // value back into the generator
                            handleNext,

                            // if `value` is a rejected
                            // promise, propagate error back
                            // into the generator for its own
                            // error handling
                            function handleErr(err) {
                                return Promise.resolve(
                                    it.throw( err )
                                )
                                .then( handleResult );
                            }
                        );
                }
            })(next);
        } );
}

the example code:
function *foo(val) {
    if (val > 1) {
        // generator recursion
        val = yield *foo( val - 1 );
    }

    return yield request( "http://some.url/?v=" + val );
}

function *bar() {
    var r1 = yield *foo( 3 );
    console.log( r1 );
}

run( bar );

and for convenience's sake we can implement function request() like this:
function request(url) {
    return new Promise(function(resolve){
        setTimeout(function(){
            resolve( url.match(/v=(\d+)$/)[1] );
        },1000);
    });
}

The book provides these steps:

*

*run(bar) starts up the *bar() generator.

*foo(3) creates an iterator for *foo(..) and passes 3 as its val parameter.

*Because 3 > 1, foo(2) creates another iterator and passes in 2 as its val parameter.

*Because 2 > 1, foo(1) creates yet another iterator and passes in 1 as its val parameter.

*1 > 1 is false, so we next call request(..) with the 1 value, and get a promise back for that first Ajax call.

*That promise is yielded out, which comes back to the *foo(2)
generator instance.

*The yield * passes that promise back out to the *foo(3) generator
instance. Another yield * passes the promise out to the *bar()
generator instance. And yet again another yield * passes the promise
out to the run(..) utility, which will wait on that promise (for the
first Ajax request) to proceed.

*When the promise resolves, its fulfillment message is sent to resume
*bar(), which passes through the yield * into the *foo(3) instance, which then passes through the yield * to the *foo(2) generator
instance, which then passes through the yield * to the normal yield
that's waiting in the *foo(3) generator instance.

*That first call's Ajax response is now immediately returned from the
*foo(3) generator instance, which sends that value back as the result of the yield * expression in the *foo(2) instance, and
assigned to its local val variable.

*Inside *foo(2), a second Ajax request is made with request(..),
 whose promise is yielded back to the *foo(1) instance, and then
 yield * propagates all the way out to run(..) (step 7 again). When
 the promise resolves, the second Ajax response propagates all the
 way back into the *foo(2) generator instance, and is assigned to
 its local val variable.

*Finally, the third Ajax request is made with request(..), its
 promise goes out to run(..), and then its resolution value comes
 all the way back, which is then returned so that it comes back to
 the waiting yield * expression in *bar().

Everything is clear until the 8th step.

...which then passes through the yield * to the normal yield
      that's waiting in the *foo(3) generator instance.

Why waiting in foo(3), not in foo(2)? I thought after Promise fulfillment, its value (1) is passed to return yield request( "http://some.url/?v=" + val ); line, in place of yield, so we have return 1 at the end of foo(1). And then 1 is passed to val = yield *foo( val - 1 ); line, again, in place of yield, so we have val = 1 inside foo(2) call. After that, a second request() is made and yields a Promise to foo(3).
Then foo(3) yields the Promise to bar(), then bar() yields the Promise to run(). run() waits on the second Promise, just as with the first promise, and so on.
JSFiddle
What have I overlooked?

A:
What have I overlooked?

Nothing. In steps 8 and 9, the generator they should be referring to is the one created by foo(1), not by foo(3).


text:
Q: Merging .vec files Hi I am using this code:
import sys
import glob
import struct
import argparse
import traceback

def exception_response(e):
    exc_type, exc_value, exc_traceback = sys.exc_info()
    lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
    for line in lines:
        print(line)

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-v', dest='vec_directory')
    parser.add_argument('-o', dest='output_filename')
    args = parser.parse_args()
    return (args.vec_directory, args.output_filename)

def merge_vec_files(vec_directory, output_vec_file):
    """
    Iterates throught the .vec files in a directory and combines them.
    (1) Iterates through files getting a count of the total images in the .vec files
    (2) checks that the image sizes in all files are the same
    The format of a .vec file is:
    4 bytes denoting number of total images (int)
    4 bytes denoting size of images (int)
    2 bytes denoting min value (short)
    2 bytes denoting max value (short)
    ex:     6400 0000 4605 0000 0000 0000
        hex     6400 0000   4605 0000       0000        0000
                # images    size of h * w       min     max
        dec         100         1350            0       0
    :type vec_directory: string
    :param vec_directory: Name of the directory containing .vec files to be combined.
                Do not end with slash. Ex: '/Users/username/Documents/vec_files'
    :type output_vec_file: string
    :param output_vec_file: Name of aggregate .vec file for output.
        Ex: '/Users/username/Documents/aggregate_vec_file.vec'
    """

    # Check that the .vec directory does not end in '/' and if it does, remove it.
    if vec_directory.endswith('/'):
        vec_directory = vec_directory[:-1]
    # Get .vec files
    files = glob.glob('{0}/*.vec'.format(vec_directory))

    # Check to make sure there are .vec files in the directory
    if len(files) <= 0:
        print('Vec files to be mereged could not be found from directory: {0}'.format(vec_directory))
        sys.exit(1)
    # Check to make sure there are more than one .vec files
    if len(files) == 1:
        print('Only 1 vec file was found in directory: {0}. Cannot merge a single file.'.format(vec_directory))
        sys.exit(1)

    # Get the value for the first image size
    prev_image_size = 0
    try:
        with open(files[0], 'rb') as vecfile:
            content = b''.join((line) for line in vecfile.readlines())
            val = struct.unpack('<iihh', content[:12])
            prev_image_size = val[1]
    except IOError as e:
        print('An IO error occured while processing the file: {0}'.format(f))
        exception_response(e)

    # Get the total number of images
    total_num_images = 0
    for f in files:
        try:
            with open(f, 'rb') as vecfile:
                content = b''.join((line) for line in vecfile.readlines())
                val = struct.unpack('<iihh', content[:12])
                num_images = val[0]
                image_size = val[1]
                if image_size != prev_image_size:
                    err_msg = """The image sizes in the .vec files differ. These values must be the same. \n The image size of file {0}: {1}\n
                        The image size of previous files: {0}""".format(f, image_size, prev_image_size)
                    sys.exit(err_msg)

                total_num_images += num_images
        except IOError as e:
            print('An IO error occured while processing the file: {0}'.format(f))
            exception_response(e)

    # Iterate through the .vec files, writing their data (not the header) to the output file
    # '<iihh' means 'little endian, int, int, short, short'
    header = struct.pack('<iihh', total_num_images, image_size, 0, 0)
    try:
        with open(output_vec_file, 'wb') as outputfile:
            outputfile.write(header)

            for f in files:
                with open(f, 'rb') as vecfile:
                    content = b''.join((line) for line in vecfile.readlines())
                    outputfile.write(bytearray(content[12:]))
    except Exception as e:
        exception_response(e)

if __name__ == '__main__':
    vec_directory, output_filename = get_args()
    if not vec_directory:
        sys.exit('mergvec requires a directory of vec files. Call mergevec.py with -v /your_vec_directory')
    if not output_filename:
        sys.exit('mergevec requires an output filename. Call mergevec.py with -o your_output_filename')

merge_vec_files(vec_directory, output_filename)

and I am getting this error:
 File "mergevec.py", line 95, in merge_vec_files
    with open(output_vec_file, 'wb') as outputfile:

PermissionError: [Errno 13] Permission denied: 'output_vec_file'

My goal is to merge the vector files together to create one vector file as part of a haar cascade in opencv. I just updated this post, and there is a lot of code so I am currently using this as filler text, but yeah any help that you can give me is much appreciated. Thanks


text:
Q: updateMany based on other field in mongodb I have two documents
/* 1 */
{
    "lastUpdated" : ISODate("2019-01-01T01:01:20.201Z"),
    "content" : "someText01",
}

/* 2 */
{
    "lastUpdated" : ISODate("2020-11-11T16:11:20.202Z"),
    "content" : "someText02",
}

Now I would like to update documents - create new field as copy of lastUpdated field;
In robo3T I can do something like this
db.getCollection('someDocuments').update({},
    [
        {"$set": {"byMongoQuery": "$lastUpdated", }}
    ],
        {"multi": true}
)

And it works.
Now I would like to do same using java code (mongo-java-driver 3.9.0)
And I do something like
mongodb.getCollection("someDocuments").updateMany(Document.parse("{}"), Document.parse("{$set: {'byJavaApi': '$lastUpdated'}}"))

mongodb is instance of com.mongodb.client.MongoDatabase
Final results is like this:

Value is set as plaintext for some reason.
I'm using
Mongodb 4.2.6
mongo-java-driver 3.9.0
Questions:

*

*How to set this field using java code. I would prefer updateMany as there is a lot of those records

*Why results are different. I was expecting there is some common engine in mongdb that executes it. And this is exactly the same query.

A: Your update is using the MongoDB v4.2 feature of updating using a pipeline. You can code this using MongoDB Java Driver v3.11 or higher. Update a field using value from another field:
Bson query = new Document();
List<Bson> updatePipeline = Arrays.asList(Fiters.eq("$set", Filters.eq("byMongoQuery", "$lastUpdated")));
UpdateResult result = collection.updateMany(query, updatePipeline);


text:
Q: Are ViewModels within an NgRX store an anti-pattern? I have a complex Angular app which has a large number of UI components. I have a central NgRX store. I have a 'pure' data model in the store which gets updated via the backend and via user input. Whenever the central store is updated I build several view models which I'm storing in the central NgRX store. My UI components then subscribe to the view models. Sometimes many disparate UI components are subscribed to the same NgRX view models. This all feels fine to me, but I have read in numerous places that the components themselves should create the view models from the pure store data. In my case that would result in duplicate copies of view model data being stored in these components.
Is it considered bad practice to build and store view models in the NgRX store?
Thanks

A: I don't think it's "bad practice" as long as it works fine for you. One think you should consider, however, is that you might be omitting one of the strengths of NgRx: Memoization. Selectors are an insanely powerful feature in NgRx that truely boost your performance to new heights and you should use them to their absolut limit.
I assume, that your viewmodels contain redundant data that you update whenever new data comes from the users inputs or your backend service. So your state is (1) unnecessarily large and (2) drains additional performance when building your viewmodels.
So, instead of building redundant viewmodels, try to expose your viewmodels as NgRx selectors that compose all information a view needs. This allows your selectors to fully take advantage of their memoization capabilities which will result in a lot less change detection cycles. Another approach, that I personally prefer the most, is that your views (i.e. components) select all the slices from state they need. This might result in a list of queries from different feature modules in your views, but it allows to fully decouple your state. This is especially useful when you work in larger teams where you have some people working exclusively on the view and others working and designing exclusively the state.
The people working on the view just have to query what they need and you, who is working on the state, does not have to consider building any viewmodels that require knowledge of the view that is being built later on.
Last but not least, querying smaller portions of your state also results in less change detection cycles because your async pipes don't have to trigger for every tiny change in your viewmodel but instead only update a small part (maybe only a single element) in your DOM instead of your entire component.
So, to conclude my statement, you get 5 advantages from NOT using viewmodels:

*

*Smaller state since redundant data is eliminated

*Better performance because you don't have to build viewmodels in the first place

*Decoupling your state from your view which leads to more scalable, testable solutions that have improved separation of concerns

*Better performance through selector memoization

*Better performance through atomic UI updates

For reference:

*

*https://christianlydemann.com/top-5-ngrx-mistakes/

*https://auth0.com/blog/ngrx-facades-pros-and-cons/


text:
Q: The British equivalent of a 'Home run' in terms of describing a successful outcome I am looking for some examples of the British equivalent of the American term 'Home run', originally relating to baseball but used to describe an overall successful and highly favourable result.
For example usage in the sentence 'Make every morning a home run!'
All examples are appreciated!

A: The clearest and most obvious equivalent to "home run" is:

hit for six

which is to achieve the highest possible score with one stroke of the bat in cricket, the British summer sport played with bat and ball.
This is also used metaphorically, but (according to at least one dictionary and as mentioned in a comment by @k1eran) generally nowadays in relation to the adversity suffered by the bowling side, rather than to the success achieved by the batting side.
I would dispute this personally, as it would be natural for me to describe a success as "hitting someone for six". Perhaps this reflects my post-war literary upbringing, as a search through Google Books for "hit 'em for six" brings up examples of this type:

"We will hit them for six!" said Monty
"And then, blam, they catch us but we're cleared for action and we hit 'em for Six before the cruiser can get under way!"
"The sweat, the panic stations, the marvellous, hit-'em-for-six-damn-their-eyes spirit."

I assume that "Make every morning a home run" is some sort of advertising copy, perhaps to sell breakfast cereal? I don't see how you could use "hit for six" in this context.
A more likely sporting metaphor would be "Go for gold each morning", referencing gold medals in athletic and other sports. (This would, no doubt, be coupled with hacknied pictures of cereal crops bathed in sunshine.)

A: There's a British expression based on cricket rather than baseball, and it fits the definition of "overall successful result" better than "home run" does.
"Good innings" refers to the overall outcome of the game, whereas "home run" is only one specific highlight in what could eventually turn out to be a losing game.
"Home run" describes a battle victory; "Good innings" describes winning the war.

If you say that someone has had a good innings, you mean that they have had a long and successful life:
  He was 86 when he died so I suppose he'd had a good innings.
  — HAVE A GOOD INNINGS | meaning in the Cambridge English Dictionary


text:
Q: about java termination program I have a project that should be run forever under unix. But in case we need to stop it, i am thinking about writing an termination program to close it gracefully.
I have no experience in writing this kind of program.
Could anyone please give me some hint. Is there any signal catching scheme in java?
Thank you

A: You need to add a shutdown hook to your application. This is a thread which will be started when your program exits normally or if the JVM is terminated in response to a user interrupt, SIGTERM signal or a system-wide event, such as user logoff or system shutdown. Take a look at the javadocs for more information.
Here are the steps involved when creating shutdown hooks:
1) Create the shutdown hook class:
public class AppShutdownHook extends Thread{
    public void run(){
        logger.info("Running shutdown hook...") ;
        //cleanup e.g. close database connections etc
    }
}

2) Register the shutdown hook:
public class App{
    public App(){
        Runtime.getRuntime().addShutdownHook(new AppShutdownHook()) ;
    }
}

The beauty of this approach is that you don't have a special "stop script" which you need to remember to run every time you have to stop your application or reboot your machine.
Reference: Shutting Down Java Apps

A: There are a couple of options here.
One is that you could have it accept command line input, but that would require you have access to it's input stream which may not happen if you close the terminal etc.  What is probably the best way to do this is to use either a socket and have it listen for a specific stream in order to shut down.  Your termination program would then be responsible for writing to that socket.
Another option would be to use some sort of more complex IPC like shared memory.
And finally another option would be to use a flat file stored somewhere on the system that your process would monitor for changes.  The termination program would then write to that file.

A: I remembered a similar question being asked time ago. One possible course of action is the use of SignalHandler.
You can read the full article here. It appears to be related to IBM JVM but I think it is equally valid for Java Hotspot.

A little-known feature of Java is the
  ability of an application to install
  its own signal handler, which is
  supported through the sun.misc.Signal
  class. However, use caution when using
  classes from the sun.misc package
  because it contains undocumented
  support classes that may change
  between releases of Java. You can
  install a Java handler for any signal
  that is not used by the JVM. These
  signal handlers are similar to native
  handlers because they're invoked when
  a native system signal is raised, but
  they will always run as a separate
  Java thread. Essentially, when a
  signal is raised for which a Java
  signal handler is available, the JVM's
  "signal dispatcher thread" is woken up
  and informed of the signal. The signal
  dispatcher thread then invokes a Java
  method to create and start a new
  thread for the installed Java signal
  handler. To write a Java signal
  handler, define a class that
  implements the sun.misc.SignalHandler
  interface and register the handler by
  using the sun.misc.Signal.handle()
  method.

I had also participated in a discussion about the subject here

A: It is possible to do signal handling in java but it is a feature that relies on using sun.misc.* classes which is something to be approached with caution since they are considered internal classes and subject change between releases.
With that caveat, check this link for more information: http://www.ibm.com/developerworks/ibm/library/i-signalhandling/#N102C8
This article is based on java 1.3.1 but the mechanism is still present in both the sun and ibm  1.6 jvms.
I wonder too if it's feasible to use jni and agentlib to install a native signal handler in your jvm... I've never tried it and would have to look into it. It's possible the jvm already has signal handling that cannot be overridden.


text:
Q: Is Firefox the only browser that supports floating point numbers as width declaration? (e.g. 163.4px)
Possible Duplicate:
Are the decimal places in a CSS width respected?

I have a navigation (li) which needs a pixel value to fit within an ul (has display:block).
So I use width:163.4px for the li's. This does work fine in Firefox (v13.0.1) but in Safari, Chrome and Opera the width is too short. (The width is there like 163px... So I guess those browsers rounding down the value.)
Explain me why only Firefox does support floating point numbers for this case?

A: All browsers round fractional pixel widths, including Firefox: http://jsfiddle.net/fgD7H/1/
You can see in the fiddle that the visible width of the red div increases only once per second, even though the actual width is incremented by 0.1 pixel ten times per second. This happens both in Chrome and in Firefox (haven't tested others).
My guess is there is some difference in rounding strategy between the two browsers (e.g. Chrome might be rounding down while Firefox might be rounding up). If you can provide a demo in jsfiddle, perhaps your problem might be more apparent. In all cases, the actual width rendered will be an integer number of pixels, so you should be able to fix the problem by setting your width to either 163px or 164px.


text:
Q: output from regex python i have this data:
result =
Operator       #Hosts   Avg Time   Max Time   #Rows  Est. #Rows  Peak Mem  Est. Peak Mem  Detail
--------------------------------------------------------------------------------------------------------------
01:EXCHANGE         1  136.668ms  136.668ms   1.02K          -1         0              0  UNPARTITIONED
00:SCAN HDFS        1  115.097ms  115.097ms  36.86K          -1  99.97 MB      960.00 MB  edw.dw_loan_int_amt

I came up with this regex (r".?([0-9]+.[0-9]+\ .B).?[0-9]+.[0-9]+\ .?B.*) to get the information i need from "Peak Mem" in this case output is 99.97MB
What Im trying to do: If result > 90 MB then #do this
Any help appreciated.
This is what i have so far, but im getting: None
result = sum_data['summary']
    print result
    m = re.match(r".*?([0-9]+\.[0-9]+\ .B).*?[0-9]+\.[0-9]+\ .?B.*", result)
    print m

A: You could split it in lines and then with a simple regular expression like \s{2,} (meaning at least two whitespaces, possibly more).

In Python:

import re

data = """
Operator       #Hosts   Avg Time   Max Time   #Rows  Est. #Rows  Peak Mem  Est. Peak Mem  Detail
--------------------------------------------------------------------------------------------------------------
01:EXCHANGE         1  136.668ms  136.668ms   1.02K          -1         0              0  UNPARTITIONED
00:SCAN HDFS        1  115.097ms  115.097ms  36.86K          -1  99.97 MB      960.00 MB  edw.dw_loan_int_amt
"""

rx = re.compile(r'\s{2,}')

for line in data.split('\n'):
    parts = rx.split(line)
    if len(parts) > 2:
        print(parts[6])

This yields

Peak Mem
0
99.97 MB

Or - if you prefer a list comprehension:
memory_peaks = [parts[6]
                for line in data.split('\n')
                for parts in [rx.split(line)]
                if len(parts) > 2]

print(memory_peaks)


text:
Q: Search In paths of the control flow graph Many times I'm having a problem with printing in function foo, and I want to look for all occurences of Print in code which is reachable in the Control Flow Graph from function foo. Or in all code in the paths between foo and bar (as I verified an assumption is true before I call foo, and false after I reach bar, so I want to find out what's happening in between).
Is there any tool that allows me to do that easily. I'm not going to compile all my C code with CIL, and write an OCaml module to do search with the CFG. I want something that works with minimum hassle.
Eclipse CDT should be able to do that (you can calculate the CFG with show function hiererchy), but I didn't find something similar there.
I'm now targeting C/C++, but I'll be glad to hear about similar tools? I'm not sure CQL have a way to express that.


text:
Q: How can I find the mean of a posterior probability? There is a comet whose model show it is moving along a straight line
$$ x(t) = mt + b $$
I have the posterior predictive distribution of a comet's position, which is
$$ PPD(x) = p(x|t,d) ∝ \exp\left( -\frac{1}{2} \frac{[x-Mt-B]^2}{σ^2t^2 + ξ^2}\right) $$
where $x$ is the position of the comet at some future time $t$. $M$ and $σ^2$ are the mean and variance of orbital parameter $m$, and $B$ and $ξ^2$ are the mean and variance of orbital parameter $b$.
How could I determine the most likely position of the comet at $t$ and the mean of the PPD as a function of $t$?
For the mean of the PPD, I thought the solution could be just
$$ \int t \exp\left( -\frac{1}{2} \frac{[x-Mt-B]^2}{σ^2t^2 + ξ^2}\right)dt$$
but I'm not sure if this is correct.


text:
Q: how to disable excel interaction completely when any modal box is open Hii I am working on a excel addin which has a custom UI box . so I want to disable interaction with excel until the UI box does not close. As you can see below in the attached image when the COM Addins box is open the interaction with excel is disabled . so how can we achieve this although my addin is in python using pyxll any vba solutions or any other language solutions will also be acceptable.

A: Solution:
Sub test():
    Application.Interactive = False
    '(optional code here ->) Application.WindowState = xlMinimized
    Application.Wait (Now + TimeValue("0:00:10"))
    '(optional code here ->) Application.WindowState = xlNormal
    Application.Interactive = True
End Sub

Ta,
J


text:
Q: How to count unique elements in the array? Need only idea For example: String[] str = {"M1","M1","M1","M2","M3"};
The most recommended is the answer - HashSet. Which methods or you have better idea?

A: Unless you want to implement this yourself, a Set is the way to go. A set will only allow unique elements to be added and will automatically filter duplicates.
The HashSet functionality works as follows:
The hash is computed for the object. Next the set checks if any of the objects with the same hash-value .equals() the new value. If so, the new value is ignored. If not, it is added to the set.
If you add everything to the set and then ask for its size, you will get the amount of unique elements.

A: new HashSet(Arrays.asList(str)).size();

A: I prefer to use things that are already provided natively. Which in your requirement is Set.
You can do the following -
Set<String> set = new HashSet<String>(Arrays.asList(str));
set.size();

A: You can try this too
    String[] str = {"M1","M1","M1","M2","M3"};
    HashMap<String,String> map=new HashMap<>();
    for(String i:str){
        map.put(i, i);
    }
    System.out.println(map.keySet().size());

A: Instead of creating a temporary list as in other answers, you can also use:
Set<String> set = new HashSet<> ();
Collections.addAll(set, str);
int countUnique = set.size();


text:
Q: Check if user +1ed the URL I'd like to check if a visitor has +1ed a certain URL (and show him a +1 button if he hasn't).  Any ideas?

A: There's a hidden API for the counts, available at the following URL:

https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ

It expects POST data in JSON-RPC format, so you'll need to send a request like this:
[{
    "method": "pos.plusones.get",
    "id": "p",
    "params": {
        "nolog": true,
        "id": "http://www.mydomain.com/mypage",
        "source": "widget",
        "userId": "@viewer",
        "groupId": "@self"
    },
    "jsonrpc": "2.0",
    "key": "p",
    "apiVersion": "v1"
}]

However, you won't be able to use this in JavaScript due to the Same-Origin policy.  This means you'll have to set up a server-side solution unless you go for Option 2.
Option 2 is what I use on a couple custom social plugins.  A very simple API is available at http://sharedcount.com, which offers the result as JSON-P if a callback is specified:
var scr = document.createElement("script");
    myUrl = encodeURIComponent("http://mydomain.com/mypage"),
    apiUrl = "http://api.sharedcount.com/?url="+myUrl+"&callback=shareCounts";

scr.src = apiUrl;
document.body.appendChild(scr);

function shareCounts(data) {
    alert(data.GooglePlusOne);
}


text:
Q: Android Studio, AndroidX, "Cannot resolve method.." on ViewModelProviders.of(this) As I can see this is pretty common misunderstanding. I am currently following one online guide, so I can get into the things in android studio. So the problem is that on cotactViewModel = ViewModel.Providers.of(this).get(ContactViewModel.class);, on this it notes Cannot resolve method of(this). I browse the web, if the activity is a Fragment/ViewModel activity, it actually works, but the guy on the guide does it using Empty Activity.
Thanks!

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.courseproject_pmiu">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" />
    </application>
</manifest>

MainActivity.java
package com.example.courseproject_pmiu;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import androidx.lifecycle.ViewModelProviders;

public class MainActivity extends AppCompatActivity {

    private ContactViewModel contactViewModel;

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

        contactViewModel = ViewModelProviders.of(this).get(ContactViewModel.class);
    }
}

build.gradle(Module:app)
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.courseproject_pmiu"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    def lifecycle_version = "2.0.0-rc01"
    def room_version = "2.0.0-rc01"

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"

    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

}

A: The problem is that you're using androidX lifecycle libraries but you're not migrate to androidX.
If you want to migrate to androidX then remove support libs and use AndroidX libs.
To solve this import androidX instead of support.
Use:
import androidx.appcompat.app.AppCompatActivity;

instead of:
import android.support.v7.app.AppCompatActivity;

For this you have to remove all support libraries from your build.gradle app level and add androidX appCompact.
After modify your build.gradle look like this.
dependencies {
def lifecycle_version = "2.0.0-rc01"
def room_version = "2.0.0-rc01"

implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
annotationProcessor "androidx.lifecycle:compiler:$lifecycle_version"

implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
}

Important:
And at last check your gradle.properties these below properties are there if not add them:
android.useAndroidX=true
android.enableJetifier=true

Else
Not recomended
If you prefer to use support libraries then import these pre-androidX libs for lifecycle.


text:
Q: We are unable to download iOS enterprise apps after upgrading devices to iOS 14 We distribute enterprise apps via our own web site.  Starting with iOS 14, we are unable to download apps.  The error message is "Unable to install appname.  Please try again later."

A: The error was resolved by updating the server's TLS to v1.2.

A: Check your app.plist and make sure you use https in software-package url setting.
Same thing for install url (itms-services://?action=download-manifest&url=https:\...)
This should resolve the issue


text: Q: Литература для сервлетов+postgres Имеется база postgreSQL с колонками id, username и password. Всё думаю как мне написать сервлет так, чтобы через постман я мог регистрировать нового пользователя и заходить под существующим. Я только учусь, поэтому в голове каша, может кто-то подскажет литературу.


text:
Q: Flex Air: Missing "Export Release Build" button So I was working normally, and accidentally hit the profiling button... after that, I later decided to export my current .air
This is what I saw:
http://i.stack.imgur.com/qw6nd.png
Why would the export button disappear all the sudden? I cannot find it at all. It seems rather interesting... not being able to export a .air and provide an installer.. anyone know where I might be able to get this back?
Thanks,
J

A: Different perspectives in eclipse change things.  The "Export Release Build" is not in the profiler perspective, but it is in the Debug and Flash perspectives.
Switch back to one of the other perspectives or select "File--> Export-->Release Build"; which is available on all perspectives.


text:
Q: Could not install from "@mui\material\generateUtilityClass" as it does not contain a package.json file I am unable to install @mui\material\generateUtilityClass library for my React application.
On running npm install @mui\material\generateUtilityClass, I am receiving the following error:
Could not install from "@mui\material\generateUtilityClass" as it does not contain a package.json file.
On running yarn add @mui\material\generateUtilityClass, receiving the following error:
An unexpected error occurred: "https://registry.yarnpkg.com/@mui%2fmaterial/generateUtilityClass: Request "https://registry.yarnpkg.com/@mui%2fmaterial/generateUtilityClass" returned a 405"

A: The following libraries need to be installed: @mui/lab and @mui/material
yarn add @mui/lab @mui/material

More: https://mui.com/material-ui/about-the-lab/


text:
Q: Product Reviews is redirecting to shopping cart when i click on "Submit Review Button" I am using "rwd" theme in new magento installation, i am facing an issue with product reviews tab in this theme.
When i click on "Be the first to review this product." It opens up a form and which i click on "Submit Review" after filling up the form it redirects me to the shopping cart page and adds that product into cart automatically. Where as it should give a message that "Your review is awaiting for moderation" and after admin approves the review it should get displayed on the product details page.

A: As as comment,it was issue with wrong calling for review form at view.phtml file.
There review form block ,is call under add to cart <form>...</from>.
<form action="<?php echo $this->getSubmitUrl($_product) ?>" method="post" id="product_addtocart_form"<?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>
....
<?php // $this->getChildHtml('review_form'); /* remove from here */?>

</form>
<?php  $this->getChildHtml('review_form'); //call here  ?>

You need move from there and out below  end


text:
Q: how I can send Arabic character inside json from android to PHP When I create json in android then I put arabic character in json like code below:
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost(url);
 JSONObject json = new JSONObject();
 try {
       json.put("jsonValue", "بسم الله ");
 } catch(Exception e) {
 }
 JSONArray postjson = new JSONArray();
 postjson.put(json);

 httppost.setHeader("json", json.toString());
 httppost.getParams().setParameter("jsonpost", postjson);

 HttpResponse response = httpclient.execute(httppost);

The php code contains charset_utf_8 but the result is not correct.
php code is shown below
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <?php

   $json = $_SERVER['HTTP_JSON'];
   var_dump($data);
   $data = json_decode($json);
   $jsonValue= $data->jsonValue;

   echo $jsonValue;
 ?>

The result printed like this "(3E 'DDG", could any one show help plz?

A: You can use URLEncoder in android like below:
json.put("jsonValue",URLEncoder.encode(jsonValue, "utf-8"));

and in your php code use urldecode:
$jsonValue= urldecode($data->jsonValue);

A: Encode string using URLEncoder before sending to server
URLEncoder.encode(str, "UTF-8");

You can change encoding format from UTF to other format e.g. JSON_UNESCAPED_UNICODE etc

A: It Is Fixed by This :
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));


text:
Q: pymongo full text search how to return only stats? I am using free text search of mongo2.4 with pymongo.
What I want is to get the number of documents having some text. In the mongo shell, increasing the limit is a good turnaround, but from python it gets very slow since all documents have to be sent. For indication, the query is ~50 times slower in pymongo compared to mongo shell.
I use a command similar to this:
>>>res=db.command('text','mytable',search='eden',limit=100000)
>>>numfound = res['stats']['nfound']

But as I said, since all documents are returned, it is really slow. Is there a command to specify that you don't need documents, just the stats??
What is the list of all available options??
thx,
colin

A: I couldn't find a server ticket for this feature - so please add a feature request to: jira.mongodb.org then you'll get updates and feedback from the core server developers.
You can project when doing a text query, so you can reduce the amount sent over the wire - but still sends some information eg:
db.mytable.runCommand( "text", { search: "eden", project: {_id: 0, b: 1}})


text:
Q: Java Simulated Annealing from Pseudocode I am currently working on a project (TSP) and am attempting to convert some simulated annealing pseudocode into Java.  I have been successful in the past at converting pseudocode into Java code, however I am unable to convert this successfully.
The pseudocode is:
T0(T and a lowercase 0)    Starting temperature
Iter    Number of iterations
λ    The cooling rate

1.  Set T = T0 (T and a lowercase 0)
2.  Let x = a random solution
3.  For i = 0 to Iter-1
4.  Let f = fitness of x
5.  Make a small change to x to make x'
6.  Let f' = fitness of new point
7.  If f' is worse than f then
8.      Let p = PR(f', f, Ti (T with a lowercase i))
9.      If p > UR(0,1) then
10.         Undo change (x and f)
11.     Else
12.         Let x = x'
13.     End if
14.     Let Ti(T with a lowercase i) + 1 = λTi(λ and T with a lowercase i)
15. End for
Output:  The solution x

If somebody could show me a basic mark-up of this in Java I would be extremely grateful - I just can't seem to figure it out!
I am working across multiple classes using a number of functions (which I will not list as it is irrelevant for what I am asking).  I already have a smallChange() method and a fitness function - could there be a chance that I would need to create a number of different versions of said methods?  For example, I have something like:
public static ArrayList<Integer> smallChange(ArrayList<Integer> solution){

//Code is here.

}

Could I possibly need another version of this method which accepts different parameters?  Something along the lines of:
public static double smallChange(double d){

//Code is here.

}

All I require is a basic idea of how this would look when written in Java - I will be able to adapt it to my code once I know what it should look like in the correct syntax, but I cannot seem to get past this particular hurdle.

A: The basic code should look like this:
public class YourClass {
  public static Solution doYourStuff(double startingTemperature, int numberOfIterations, double coolingRate) {
    double t = startingTemperature;
    Solution x = createRandomSolution();
    double ti = t;

    for (int i = 0; i < numberOfIterations; i ++) {
      double f = calculateFitness(x);
      Solution mutatedX = mutate(x);
      double newF = calculateFitness(mutatedX);
      if (newF < f) {
        double p = PR(); // no idea what you're talking about here
        if (p > UR(0, 1)) { // likewise
          // then do nothing
        } else {
          x = mutatedX;
        }
        ti = t * coolingRate;
      }
    }
    return x;
  }

  static class Solution {
    // no idea what's in here...
  }
}

Now as far as wanting different versions of smallChange() method - totally doable, but you have to read up on inheritance a little bit

A: You can compare your answer to the code provided for the textbook
Artificial Intelligence a Modern Approach.

*

*SimulatedAnnealingSearch.java

A: Also, a Java-based approach to teaching simulated annealing (with sample code) is here:
Neller, Todd. Teaching Stochastic Local Search, in I. Russell and Z. Markov, eds. Proceedings of the 18th International FLAIRS Conference (FLAIRS-2005), Clearwater Beach, Florida, May 15-17, 2005, AAAI Press, pp. 8-13.
Related resources, references, and demos are here: http://cs.gettysburg.edu/~tneller/resources/sls/index.html


text:
Q: JSP code for FB credit callback url i am developing a Facebook iframe app with Facebook credit API. i am using FB JavaScript SDK for that. but i am unable to find out any sample code in java or JSP for FB credit callback URL. all i found is te PHP code and i dont know PHP much.. can anyone convert it for me in JSP or Java?
here is the php sample code
    **
* Copyright 2004-Present Facebook. All Rights Reserved.
*
* You should reference https://developers.facebook.com/docs/credits/ as you
* familiarize yourself with callback.php. In particular, read all the steps
* under "Credits Tutorial" and "Credits Callback".
*
* Your application needs the following inputs and outputs
*
* @param int order_id
* @param string status
* @param string method
* @param array order_details (JSON-encoded)
*
* @return array A JSON-encoded array with order_id, next_state
* (optional: error code, comments)
*/

// Enter your app information below
$app_secret = '<app_secret>';

// Prepare the return data array
$data = array('content' => array());

// Parse the signed_request to verify it's from Facebook
$request = parse_signed_request($_REQUEST['signed_request'], $app_secret);

if ($request == null) {
// Handle an unauthenticated request here
}

// Grab the payload
$payload = $request['credits'];

// Retrieve all params passed in
$func = $_REQUEST['method'];
$order_id = $payload['order_id'];

if ($func == 'payments_status_update') {

// Grab the order status
$status = $payload['status'];

// Write your apps logic here for validating and recording a
// purchase here.
//
// Generally you will want to move states from `placed` -> `settled`
// here, then grant the purchasing user's in-game item to them.
if ($status == 'placed') {
$next_state = 'settled';
$data['content']['status'] = $next_state;
}

// Compose returning data array_change_key_case
$data['content']['order_id'] = $order_id;

} else if ($func == 'payments_get_items') {
// remove escape characters
$order_info = stripcslashes($payload['order_info']);
$item_info = json_decode($order_info, true);
if ($item_info == "abc123") {

// Per the credits api documentation, you should pass in an item
// reference and then query your internal DB for the proper
// information. Then set the item information here to be
// returned to facebook then shown to the user for confirmation.
$item['title'] = 'BFF Locket';
$item['price'] = 1;
$item['description'] = 'This is a BFF Locket...';
$item['image_url'] = 'https://www.facebook.com/images/gifts/21.png';
$item['product_url'] = 'https://www.facebook.com/images/gifts/21.png';
} else {

// For the sake of the sample, we will default to this item if
// the `order_info` reference passed from your JS call is not matched
// above.
$item['title'] = 'A Facebook Hat';
$item['price'] = 1;
$item['description'] = 'The coolest hat you\'ve ever seen.';
$item['image_url'] = 'https://www.facebook.com/images/gifts/740.png';
$item['product_url'] = 'https://www.facebook.com/images/gifts/740.png';
}

// Put the associate array of item details in an array, and return in the
// 'content' portion of the callback payload.
$data['content'] = array($item);
}

// Required by api_fetch_response()
$data['method'] = $func;

// Send data back
echo json_encode($data);

// You can find the following functions and more details
// on https://developers.facebook.com/docs/authentication/canvas.
function parse_signed_request($signed_request, $app_secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);

// Decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);

if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}

// Check signature
$expected_sig = hash_hmac('sha256', $payload, $app_secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}

return $data;
}

function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}

A: One sample, I will link more as I get.
https://github.com/facebook/facebook-android-sdk
http://code.google.com/p/facebook-java-sdk/


text:
Q: Best place(s) to share my scripts with others? Would anyone recommend a site (or sites) where one could share scripts they have written that they think may be helpful to others? There are so many, and so many that appear defunct, I am hesitant to arbitrarily pick one. My scripts are mostly PowerShell with the occasional VBS or .NET mixed in for good measure.
Having finally achieved the level of Advanced Scripting Padewan, I think I'm ready to share some of my work with the community at large. :)

A: GitHub gist is a nice place to share code snippets. If your scripts are small, you can pick one. Or just create an open repository on GitHub.


text:
Q: accessing kotlin Suspend function from Java code I have Room database interface which is a Kotlin file and as I dont want the calls to run on mainthread I am using kotlin Suspend. how can I use suspend function from java
I have two method where I want to insert a User and another to retrieve the users
these are the errors I get in my java file

Code
Room Dao interface
UserDao
@Dao
interface UserDao {

    fun getAllUsersAsync(): CompletableFuture<List<User>> =
        GlobalScope.future { getAllUsers() }

    @Query("SELECT * FROM user")
    suspend fun getAllUsers(): List<User>

    @Insert
    suspend fun insertUser(user: User): Long
}

Java code
private Long addUser(com.i6systems.in2plane.AppDatabase.User user) {
    return userDao.insertUser(user);
}

private List<com.i6systems.in2plane.AppDatabase.User> getUsers () {
    return userDao.getAllUsersAsync();
}

your help is much appreciated
Thanks
R


text:
Q: Does GridSearchCV use predict or predict_proba, when using auc_score as score function? Does GridSearchCV use predict or predict_proba, when using auc_score as score function?
The predict function generates predicted class labels, which will always result in a triangular ROC-curve. A more curved ROC-curve is obtained using the predicted class probabilities. The latter one is, as far as I know, more accurate. If so, the area under the 'curved' ROC-curve is probably best to measure classification performance within the grid search.
Therefore I am curious if either the class labels or class probabilities are used for the grid search, when using the area under the ROC-curve as performance measure. I tried to find the answer in the code, but could not figure it out. Does anyone here know the answer?
Thanks

A: To use auc_score for grid searching you really need to use predict_proba or decision_function as you pointed out. This is not possible in the 0.13 release. If you do score_func=auc_score it will use predict which doesn't make any sense.
[edit]Since 0.14[/edit] it is possible to do grid-search using auc_score, by setting the new scoring parameter to roc_auc: GridSearch(est, param_grid, scoring='roc_auc'). It will do the right thing and use predict_proba (or decision_function if predict_proba is not available).
See the whats new page of the current dev version.
You need to install the current master from github to get this functionality or wait until April (?) for 0.14.

A: After performing some experiments with Sklearn SVC (which has predict_proba available) comparing some results with predict_proba and decision_function, it seems that roc_auc in GridSearchCV uses decision_function to compute AUC scores. I found a similar discussion here: Reproducing Sklearn SVC within GridSearchCV's roc_auc scores manually


text:
Q: Why isn't my code filling down? Dim SLR As Range
Dim ELR As Range

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
On Error Resume Next

Select Case UCase(Target.Value)

Case "START-LOCATION"
    Target.Offset(0, 0).Select
    Selection.ClearContents
    SLR = ActiveCell.Address
    Target.Offset(-1, 1).Select

Case "END-LOCATION"
    Target.Offset(0, 0).Select
    Selection.ClearContents
    ELR = ActiveCell.Address
    Target.Offset(0, -1).Select
    ActiveSheet.Range(SLR, ELR).FillDown

End Select
End Sub

Hello all, I have the above code, it is supposed to set the variable on start location for the first cell, and on end location it sets the second variable and then fills down the cells from SLR to ELR, however it isn't working and isn't providing me with an error message, any ideas?

A: Try to change the followings:
SLR= Activecell.Address

into
Set SLR = Activecell

and do the same for ELR:
Set ELR = Activecell

A: On Error Resume Next is always a bad idea.  If I was king of the world I would make this command illegal, the error handler should be for when something unexpected happens that crashes your code.
The most import thing with your macro is that the data the user gets at the end of it is correct.  If that means that when the code crashes and the user call you over then that's what it takes.  But having On Error Resume Next means that no one will ever know if your code has crashed and no one will ever know that the data is wrong.
Never ever use On Error Resume Next!!!!!
As for this bit of code you'll learn more about your problem if you remove On Error Resume Next.


text:
Q: react-chartjs-2 bar touches the top When the data is filled it hits the top of the line. is there any option to limit the top, and I need the show the number with money symbol.
I need to change the x-axis to show more than the top limit. is there any option to it

          <Bar
            data={incomePropertyData}
            width={100}
            height={450}
            options={{
              maintainAspectRatio: false,
              legend: {
                display: true,
                fontColor: "#686868",
                fontFamily: "kanit, sans-serif",
              },
              tooltips: {
                titleAlign: "center",
                titleMarginBottom: 8,
                bodyFontFamily: "'Nunito', sans-serif",
                callbacks: {
                  label: function (tooltipItem, data) {
                    var label =
                      data.datasets[tooltipItem.datasetIndex].label || "";
                    if (label) {
                      label += " : ";
                    }
                    label += "₹ " + tooltipItem.yLabel;
                    return label;
                  },
                },
              },
              responsive: true,
              scales: {
                yAxes: [
                  {
                    ticks: {
                      fontFamily: "'Nunito', sans-serif",
                      fontSize: 14,
                    },
                  },
                ],
                yAxes: [
                  {
                    ticks: {
                      fontFamily: "'Nunito', sans-serif",
                      fontSize: 14,
                      beginAtZero: true,
                      callback: function (value, index, values) {
                        return "₹ " + value;
                      },
                    },
                  },
                ],
              },
            }}
          />

A: I think you could try something like in the example i made here:
https://stackblitz.com/edit/react-boilerplate-scalabw-45793890
You can use the max in the scales: { yAxes : [{max: maxvalue}] }
You just need to add a function which get the maximum value and add the "padding value".
i also simplified you code in my example because you got a repetition between yAxes and yAxes.


text:
Q: ActiveRecord::RecordInvalid: Validation failed: Technologies portfolio must exist I was trying to save nested attributes for technologies with portfolio, I have the following code:
portfolio.rb (model)
class Portfolio < ApplicationRecord
  has_many :technologies
  # do not accept the insertion if name is blank
  accepts_nested_attributes_for :technologies,
                                 reject_if: lambda{ |attrs| attrs['name'].blank? }
  validates_presence_of :title, :body, :main_image, :thumb_image
  include Placeholder
  validates_presence_of :title, :body, :main_image, :thumb_image

  # class method - custom scope
  def self.angulars
    where(subtitle: "Angular")
  end

  # lambda - custom scope
  scope :ruby_on_rails_p_items, -> { where(subtitle: "Ruby on Rails") }

  # callbackss
  after_initialize :set_defaults

  def set_defaults
    self.main_image ||= Placeholder.image_generator(height:'600', width:'400')
    self.thumb_image ||= Placeholder.image_generator(height:'350', width:'200')
  end
end

technology.rb model:
class Technology < ApplicationRecord
  belongs_to :portfolio
end

Now when I go to the rails console and try to insert multiple attributes:
Portfolio.create!(title: "Web App", subtitle: "asadasd", body: "sadsadas", technologies_attributes: [{name: "Ruby"}, {name: "Rails"}, {name: "Angula"}, {name: "Ionic"}])

It gave me this error:
ActiveRecord::RecordInvalid: Validation failed: Technologies portfolio must exist
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/validations.rb:78:in `raise_validation_error'

Any idea what am I missing here?
Schema for both technology and portfolio:
  create_table "portfolios", force: :cascade do |t|
    t.string   "title"
    t.string   "subtitle"
    t.text     "body"
    t.text     "main_image"
    t.text     "thumb_image"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "technologies", force: :cascade do |t|
    t.string   "name"
    t.integer  "portfolio_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.index ["portfolio_id"], name: "index_technologies_on_portfolio_id", using: :btree
  end

COMPLETE ERROR MESSAGE:
ActiveRecord::RecordInvalid: Validation failed: Technologies portfolio must exist
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/validations.rb:78:in `raise_validation_error'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/validations.rb:50:in `save!'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/attribute_methods/dirty.rb:30:in `save!'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/transactions.rb:324:in `block in save!'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/transactions.rb:395:in `block in with_transaction_returning_status'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/connection_adapters/abstract/database_statements.rb:232:in `block in transaction'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/connection_adapters/abstract/transaction.rb:189:in `within_new_transaction'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/connection_adapters/abstract/database_statements.rb:232:in `transaction'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/transactions.rb:211:in `transaction'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/transactions.rb:392:in `with_transaction_returning_status'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/transactions.rb:324:in `save!'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/suppressor.rb:45:in `save!'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.7/lib/active_record/persistence.rb:51:in `create!'
    from (irb):3
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/railties-5.0.7/lib/rails/commands/console.rb:65:in `start'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/railties-5.0.7/lib/rails/commands/console_helper.rb:9:in `start'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/railties-5.0.7/lib/rails/commands/commands_tasks.rb:78:in `console'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/railties-5.0.7/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/railties-5.0.7/lib/rails/commands.rb:18:in `<top (required)>'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.7/lib/active_support/dependencies.rb:293:in `require'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.7/lib/active_support/dependencies.rb:293:in `block in require'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.7/lib/active_support/dependencies.rb:259:in `load_dependency'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.7/lib/active_support/dependencies.rb:293:in `require'
    from /Users/mac/Desktop/DevCampPortfolio/bin/rails:9:in `<top (required)>'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.7/lib/active_support/dependencies.rb:287:in `load'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.7/lib/active_support/dependencies.rb:287:in `block in load'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.7/lib/active_support/dependencies.rb:259:in `load_dependency'
    from /Users/mac/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.7/lib/active_support/dependencies.rb:287:in `load'
    from /Users/mac/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from /Users/mac/.rvm/rubies/ruby-2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
    from -e:1:in `<main>'
2.3.1 :004 > Portfolio.create!(title: "Web App", subtitle: "asadasd", body: "sadsadas", main_image: 'some value', thumb_image: 'some image')

A: Making the belongs_to :portfolio association optional is not solving the problem. All you are doing by passing in optional: true is skipping validation, which is not useful if you actually want to set up a database schema with Model associations.
The underlying cause of the problem is that Active Record is attempting to create a Technology object before the Portfolio object has been committed to the database. accepts_nested_attributes_for is special in that it creates an instance of the associated model (Technology in this case) through the parent model (Portfolio). To do this Active Record needs to know about the relation between the two models, and it must also have a foreign key to tie the associated Technology object to a specific Portfolio.
If you were to create a Portfolio object first, and then a Technology object separately you wouldn't have a problem:
portfolio = Portfolio.create!(title: "Web App", subtitle: "asadasd", body: "sadsadas")

Technology.create!(name: 'aoeifjeao', portfolio_id: portfolio.id)
=> #<Technology id: 10, name: "aoeifjeao", portfolio_id: 17, created_at: "2019-12-07 03:54:47", updated_at: "2019-12-07 03:54:47">

The reason this works is clear if you inspect the SQL queries generated by the Technology.create code:
(0.4ms)  BEGIN
Portfolio Load (0.7ms)  SELECT  "portfolios".* FROM "portfolios" WHERE "portfolios"."id" = $1 LIMIT $2  [["id", 17], ["LIMIT", 1]]
SQL (1.6ms)  INSERT INTO "technologies" ("name", "portfolio_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["name", "aoeifjeao"], ["portfolio_id", 17], ["created_at", "2019-12-07 03:54:47.668662"], ["updated_at", "2019-12-07 03:54:47.668662"]]
(41.0ms)  COMMIT

Note that the first thing that happens is Active Record looks for a Portfolio from the database with a specific id. It then inserts a new record into the technologies table with the same portfolio_id.
This is what happens when you create a model with an association using Active Record. It looks for the parent model in the database first using the id you specified, and then that becomes the foreign key of the child model.
Returning to your code, when you call Portfolio.create, what you are actually trying to do is create both the parent and child objects, plus set up their association, all before any records are saved to the database.
What is actually happening is that Portfolio.create gets broken up into two steps. First Portfolio.new is called, which instantiates (but doesn't save) the Portfolio Object:
portfolio = Portfolio.new(title: "Web App", subtitle: "asadasd", body: "sadsadas", technologies_attributes: [{name: "Ruby"}])
=> #<Portfolio id: nil, title: "Web App", subtitle: "asadasd", body: "sadsadas", main_image: "http://placehold.it/600x400", thumb_image: "http://placehold.it/350x200", created_at: nil, updated_at: nil>

Note that our nested attributes have already been used to instantiate a Technology Object through the Portfolio association, but the foreign key portofolio_id is nil:
portfolio.technologies
=> #<ActiveRecord::Associations::CollectionProxy [#<Technology id: nil, name: "Ruby", portfolio_id: nil, created_at: nil, updated_at: nil>]>

Next, Portfolio.save is called, which throws ActiveRecord::RecordInvalid validation error. This is telling you that the Technology object requires a Portfolio association, which it does not have because portfolio_id is still nil.
When setting up belongs_to and has_many relationships, Active Record attempts to automatically guess the inverse association based on heuristics, typically by looking at the table names. It's usually pretty good at it, but sometimes you need to be explicit and declare the inverse_of relationships between the two models.
# portfolio.rb

class Portfolio < ApplicationRecord
  has_many :technologies, inverse_of: :portfolio
end

# technology.rb

class Technology < ApplicationRecord
  belongs_to :portfolio, inverse_of: :technologies
end

A: You have validation on Portfolio
validates_presence_of :title, :body, :main_image, :thumb_image

And you are passing only :title, :subtile, :body but not :main_image, :thumb_image
Portfolio.create!(title: "Web App", subtitle: "asadasd", body: "sadsadas", technologies_attributes: [{name: "Ruby"}, {name: "Rails"}, {name: "Angula"}, {name: "Ionic"}])

Above code expecting saving of Portfolio should be successful, so it can use portfolio_id in Technology, but it isn't happening here you need to pass in all required parameter to Portfolio.create!
Portfolio.create!(title: "Web App", subtitle: "asadasd", body: "sadsadas", main_image: 'some value', thumb_image: 'some image',
  technologies_attributes: [{name: "Ruby"}, {name: "Rails"}, {name: "Angula"}, {name: "Ionic"}])

Update:
As you are using Rails 5.x, In Rails 5.x (onwards) all belongs_to association validates(belongs_to association) presence true by default, add optional: true to your Technology Model. Read more about this
class Technology < ApplicationRecord
  belongs_to :portfolio, optional: true
end


text:
Q: C# For Loop Confusion Why does "num" turn into 0 at some time?
int num = 16;
for (int i = 1; i < 1000; i++)
{
    Console.WriteLine(num *= i);
}

A: At your 31st iteration, num will be -1073741824 due to overflowing which you say you already understand.
In the next (32nd) iteration you multiply num by 32 which is b100000 as binary. This multiplication is the same as shifting the value 5 bits to the left.
-1073741824 is 0xC0000000, and if you shift that 5 bits to the left, your 32bit value ends up being 0x00000000 => zero.

A: Each time i is a multiple of 2, multiplying n by it gives n that many more 0 bits on the end.  Eventually, it has enough to fill the variable, making it 0.

A: Every time you multiply by an even number, you add one or more binary zeros to the right side of the number, but you will never remove one. Eventually you hit a point where all of the digits are zero.
This is the sequence you get, note that the right side only ever gets a longer sequence of zero digits:
01:                              10000  <= 4 zeros
02:                             100000  <= 5 zeros
03:                            1100000  <= 5 zeros
04:                          110000000  <= 7 zeros
05:                        11110000000  <= 7 zeros
06:                     10110100000000  <= 8 zeros
07:                  10011101100000000  <= 8 zeros
08:               10011101100000000000  <= 11 zeros
09:            10110001001100000000000  <= 11 zeros
10:         11011101011111000000000000  <= 12 zeros
11:     100110000100010101000000000000  <= 12 zeros
12:   11001000110011111100000000000000  <= 14 zeros
13:     110010100011001100000000000000  <= 14 zeros
14:   11000011101100101000000000000000  <= 15 zeros
15:    1110111011101011000000000000000  <= 15 zeros
16:    1110111010110000000000000000000  <= 19 zeros
17:   11101100110110000000000000000000  <= 19 zeros
18:   10100111001100000000000000000000  <= 20 zeros
19:    1101000100100000000000000000000  <= 20 zeros
20:     101011010000000000000000000000  <= 22 zeros
21:   10001100010000000000000000000000  <= 22 zeros
22:       1101100000000000000000000000  <= 23 zeros
23:     110110100000000000000000000000  <= 23 zeros
24:      11100000000000000000000000000  <= 26 zeros
25:   10111100000000000000000000000000  <= 26 zeros
26:      11000000000000000000000000000  <= 27 zeros
27:   10001000000000000000000000000000  <= 27 zeros
28:   11100000000000000000000000000000  <= 29 zeros
29:    1100000000000000000000000000000  <= 29 zeros
30:    1000000000000000000000000000000  <= 30 zeros
31:   11000000000000000000000000000000  <= 30 zeros


text:
Q: flotgraph using functions for conditional radius I have a dataset where each node contains a date and a value.
I don't want flot to draw a circular point at ever value, especially if the value is zero
so in my graph's options I have:
points: {
          show: true,
          radius: 3
        },

but how do I have `radius: function (x) { return x.value>0?3:0 };
is this possible in flot, if so what is the syntax?

A: Flot expects radius to be a number.  The simplest way to achieve this would be to create two series with the same color.  The first contains all the datapoints and points: { show: false } and the second contains only those datapoints where y > 0 and lines: { show: false }.


text:
Q: Eclipse performance tuning for multiple CPUs and lots of memory? I have a dual quad core machine with 12 Gigs of memory on which I run eclipse, does anyone know what JVM Options will give the most responsive / performant experience?
I am currently running:
-Xms256m
-Xmx2048m
-Xss2m
-XX:PermSize=128m
-XX:MaxPermSize=384m
Would changing -Xmx to 4096 give better performance? Or is there some point when more memory will deteriorate performance?
Also can I have a garbage collector running on a separate core to stop lags in the UI during GC?

A: The most important thing to make sure is that you are running 64-bit version of Eclipse on 64-bit version of JVM. Your are already allocating more memory than I have ever seen allocated to Eclipse. Unless you have ginormous code base loaded in Eclipse, chances are that you will not come close to hitting that limit. You can keep an eye on Eclipse memory consumption in your OS process monitor. If you see it approaching the limit, then you know that you can give it more memory.
JVM will automatically use all available cores. Eclipse is highly multi-threaded. There are no facilities to pin Java threads or the GC to specific cores.
If you are seeing UI lag on a modern JVM, it is not due to GC unless you ran out of memory and GC must pause the process.


text:
Q: Show that the set of sets {$A_n$} has $n$ elements and that it is transitive We define by recursion the set of sets {$A_n : n∈ℕ$} this way:
$A_0 = ∅$
$A_{n+1} = A_n ∪$ {$A_n$}.
I want to prove by induction that for all $n∈ℕ$, the set $A_n$ has $n$ elements and that $A_n$ is transitive (i.e. if $x∈y ∈ A_n$, then  $x∈A_n$).
My thoughts:
for $n=0$, $A_1$ = $∅ ∪$ {$∅$} = {$∅$}
then, for $n+1$: $A_{n+2}$ $= A_{n+1} ∪$ {$A_{n+1}$}
I'm confused on how to proceed.

A: Remember that for induction problems, you must show (in addition to the base case) that if a claim holds for some $n \in \mathbb{N}$, then it also holds for $n+1$. In this problem, our claim is:
$$
\forall x : x \in y \in A_n \implies x \in A_n
$$
The base case ($n = 0$) is not difficult: Since there are no elements in $A_n$, there are no elements for which this is false! Therefore, it is true.
Next, we will assume that this claim holds for some $n \in \mathbb{N}$. Consider some $x$ such that $x \in y \in A_{n+1} = A_n \cup \{A_n\}$. By the definition of the union, we see that either $y \in A_n$ or $y = A_n$.
If $x \in y = A_n$, then, by definition of $A_{n+1}$ ($z \in A_n \text{ or } z \in \{A_n\} \implies z \in A_{n+1}$), we see that $x \in A_{n+1}$.
Otherwise, $x \in y \in A_n$. But this is true by our assumption!
Therefore, by induction the claim holds for all $n \in \mathbb{N}$.
Edit: I missed the section regarding $| A_n | = n$
To show that $A_n$ has $n$ elements, use induction again. First, we need to show that:
$$\forall n : A_n = \{ A_i : i < n \}$$
For $n=0$, we see that this is trivially true, since there are no natural numbers less than $0$. Let us assume this claim holds for some $n \in \mathbb{N}$. Then:
$$A_{n+1} = A_n \cup \{A_n\} = \{ A_i : i < n \} \cup \{A_n\} = \{ A_i : i \le n \} = \{ A_i : i < n+1 \}$$
Now that we know the above fact, we can show $| A_n | = n$.
For $n= 0$, $A_0 = \emptyset$ clearly has no elements. Next, assume that $A_n$ has $n$ elements for some $n \in \mathbb{N}$. Then $A_{n+1} = A_n \cup \{A_n\} = \{ A_i : i < n \} \cup \{A_n\}$. Since $A_n$ contains sets with at most $n-1$ elements, and since $A_n$ contains $n$ elements, we see that $A_n$ and $\{A_n\}$ are necessarily disjoint. Therefore, $| A_{n+1} | = n + 1$ ($n$ elements from $A_n$ and one element from $\{A_n\}$).


text:
Q: How do I keep smartgwt from polluting the window namespace? I have existing javascript in a project that creates a 'Calendar' object. The object is a member of window.
When I added smartgwt to my project, the original Calendar object was overwritten by a smartclient calendar (ISC_Calendar) packaged in smartgwt.
Using a browser-based JS debugger, I found that all the JS objects from smartgwt were contained both in window and in window.isc. I definitely don't want them all at window level because many of them have generic names like Calendar.
The offending file in my case is ISC_Calendar.js, which ends up in war/<projectname>/sc/modules after a gwt compile. It calls the following line: isc.ClassFactory.defineClass("Calendar","Canvas","DataBoundComponent");
GWT compiled location: war/projectname/sc/modules/ISC_Calendar.js
Jar location: com.smartclient public/sc/modules/ISC_Calendar.js
Src location: can't find it
I suppose I can just change the javascript file in the jar I'm using, but that doesn't really solve the larger problem. I don't want to worry about running into namespace issues down the road

A: Say you want to rename smartgwt's Calendar to Calendar2.
First, check out the source code for smartgwt. See here: http://code.google.com/p/smartgwt/wiki/BuildingFromSVN
Then, in the source code, open up trunk/main/src/com/smartgwt/client/widgets/calendar/Calendar.java. Find this code snippet:
public Calendar(){
    scClassName = "Calendar";
}

And replace "Calendar" with Calendar2.
Now compile the source. Consult this link again to help you compile: http://code.google.com/p/smartgwt/wiki/BuildingFromSVN.
Take the resulting smartgwt.jar and open it up in a jar editor. Navigate to com.smartclient public/sc/modules/ISC_Calendar.js and open it. Find this code snippet:
isc.ClassFactory.defineClass("Calendar","Canvas","DataBoundComponent");

And replace "Calendar" with Calendar2.
Next, in the same file, do a find and replace. Replace isc.Calendar with isc.Calendar2. Also do the find and replace in ISC_Core.js.
Now save the jar. The calendar should be functional and the window.Calendar namespace will be untouched.

A: You must set
var isc_useSimpleNames = false;

in script tag before any SmartClient components are loaded. This way SC will register classes only in isc.* namespace.


text:
Q: Get last invoice date and first branch user visit (first invoice date) invoices Table

id
date
branch_id
patient_id

1
2021-09-03
1
1

2
2021-09-08
2
1

3
2021-09-15
3
2

4
2021-09-16
2
2

5
2021-09-17
1
3

6
2021-09-19
2
3

end result

id
date
branch_id
patient_id

1
2021-09-03
1
1

2
2021-09-16
3
2

3
2021-09-19
1
3

get last invoice date with first branch user vistt(first invoice date)
I use this to get last invoice for each patient
SELECT patient_id ,max(date)
            FROM  invoices
            GROUP BY patients.id

how to get with it first branch user visit

A: select patient_id
       , max(date) lastinvoicedate
       , first_Value(branch_id) over (order by date asc) firstbranch
from tablename
group by patient_id


text:
Q: hyperref fillable forms - breaking the rules The hyperref manual states clearly:

You must put your fields inside a Form environment (only one per file).

However,

*

*I can put form fields outside of a Form and

*I can put more than one Form in a file
and it seems to work just fine (apart from the general problem even within the rules that the font in the fillable fields seems uncontrollable). See MWE. It is not possible for me to get all my fillable bits in one place. What terrible things will befall me if I breach (1) and (2) above?
\documentclass{article}
\usepackage{hyperref}
\begin{document}

%outside a form
\TextField[name=one, width=3cm, borderwidth=0]{type here:}

%Form 1
\begin{Form}
\TextField[name=two, width=3cm, borderwidth=0]{type here:} \\

\TextField[name=three, width=3cm, borderwidth=0]{type here:} \\
\end{Form}

%And another one
\begin{Form}
\TextField[name=four, width=3cm, borderwidth=0]{type here:} \\

\TextField[name=five, width=3cm, borderwidth=0]{type here:} \\
\end{Form}
\end{document}

A: This is not a complete answer, but small subtle things seem to happen/break.
For example, let's say that you are creating a PDF document, but that you don't provide a Form environment at all. If you use Adobe Acrobat Reader DC (version 2015.007.20033) to read your generated document, then when you enter your first character the whole GUI freezes approximately one second for some reason (but after that everything seems to work fine). If you instead use Foxit Reader (version 7.1.5.425) you will not get the notification saying "This document contains interactive form fields." that the program usually displays.
So it seems best to follow the manual, as other PDF readers might break in other ways.


text:
Q: Server missing "ldap.so" I want to connect to ldap in php. However I'm getting this error

exception 'adLDAPException' with message 'No LDAP support for PHP.
  See: http://www.php.net/ldap'

I need to reference "ldap.so" in php.ini file. But I'm not sure how to get the file. Installed openldap but still no luck. I'm not sure what I'm missing here. Do I need to recompile php ldap? if yes, what packages I need to install

A: Run either of these as root to install the missing extension.
Apt:
apt-get update
apt-get install php5-ldap

Yum-based systems:
yum install php-ldap
echo "extension=ldap.so" >> /etc/php.ini
service httpd restart

For you, specifically, try installing directly from RPM:
x86_64:
wget http://mirror.centos.org/centos/6/os/x86_64/Packages/php-ldap-5.3.3-22.el6.x86_64.rpm
deb -i php-ldap-5.3.3-22.el6.x86_64.rpm

i386:
wget http://mirror.centos.org/centos/6/os/i386/Packages/php-ldap-5.3.3-22.el6.i686.rpm
deb -i php-ldap-5.3.3-22.el6.i686.rpm


text:
Q: Is possible to programmatically scale Azure instances? Are there some Azure APIs that allow me to access the scaling functionalities from my C# code in Visual Studio?
For example, I need to scale from 2 to 5 instances when some football matches end, and go back to 2 after 1 hour.

A: This indeed possible using The Autoscaling Application Block, that enables to auto-scale using custom metrics. Nevertheless, note that this library is no longer maintained.
You may want to also read the updated Autoscaling guidance, which also describes the Autoscaling Application Block mentioned above.