Q: Filttering json data in html-table I have to display json data in HTML-table and have succeeded in it. My problem is that I also need to filter this data by genders and studyfields using radiobuttons and dropdown list in the webpage. I have managed to do so but the filters clash with each other and mess the results in the table.
HTML:

Filter by Gender

    All
    <input class="filter-by-gender" checked="checked" type="radio" id="filterByGenderAll" value="all" name="filter_by_gender">
    Males
    <input class="filter-by-gender"  type="radio" id="filterByGenderM" value="male" name="filter_by_gender">
    Females
    <input class="filter-by-gender" type="radio" id="filterByGenderF" value="female" name="filter_by_gender">

Filter by Studies

    <select id="filterByStudiesAll" input class="filter-by-studies" name="filter-by-studies">
        <option value="All" name="filter-by-studies">All</option>
        <option value="Computer Science"name="filter-by-studies">Computer science</option>
        <option value="Business"name="filter-by-studies">Business</option>
        <option value="Art"name="filter-by-studies">Art</option>
    </select>

        Name
        Gender
        Age
        Studyfield
        Email
        Phone
        Address

Json is like this:
var students = [
{
"student_id": "123456",
"age": 20,
"firstname": "Horne",
"lastname": "Hess",
"gender": "male",
"study_field": "Computer Science",
"email": "hornehess@magnafone.com",
"phone": "+1 (877) 436-3132",
"address": "745 Livingston Street, Cassel, South Dakota, 103"}]

and lastly javascript:
       function filterStudentsByGender(gender)
            {
            var filteredStudents = students
            switch(gender)
            {
        case "male":

            filteredStudents = students.filter(function(student){
                return student.gender === "male"
            })
        break;

        case "female":
            filteredStudents = students.filter(function(student){
                return student.gender === "female"
            })
        break;
    }

    var studentsHtml = filteredStudents.map(function(student){
        return '
'+student.firstname+" "+student.lastname+'	'+student.gender+'	'+student.age+'	'+student.study_field+"	"+student.email+"	"+student.phone+"	"+student.address+"
";
    })
    $("#students").find('.tbody').html(studentsHtml)

}
function filterStudentsByStudy(study_field)
{
    var filteredStudents=students
    switch(study_field){
        case "Computer Science":
        filteredStudents=students.filter(function(student){
            return student.study_field=="Computer Science"
        })
        break;

        case "Art":
        filteredStudents=students.filter(function(student){
            return student.study_field=="Art"
        })
        break;

        case "Business":
        filteredStudents=students.filter(function(student){
            return student.study_field=="Business"
        })
        break;
    }
    var studentsHtml = filteredStudents.map(function(student){
        return '
'+student.firstname+" "+student.lastname+'	'+student.gender+'	'+student.age+'	'+student.study_field+"	"+student.email+"	"+student.phone+"	"+student.address+"
";
    })

    $("#students").find('.tbody').html(studentsHtml)
}

/* ########################## event listeners */
$(".filter-by-studies").on("change", function(e){
    var checked = $(this).val();
    filterStudentsByStudy(checked)
})

$(".filter-by-gender").on("change", function(e){
    var checkedValue = $(this).val();
    filterStudentsByGender(checkedValue)
})


Q: Programmatically Position Views in RelativeLayout I want my TextView to appear below my ImageView in a RelativeLayout that is going into a GridView.  I've tried:
public override View  GetView(int position, View convertView, ViewGroup parent)
    {
        RelativeLayout rl = new RelativeLayout(context);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.FillParent);
        ImageView imageView;
        TextView tv;

        imageView = new ImageView(context);
        imageView.LayoutParameters = new GridView.LayoutParams(250, 250);
        imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
        imageView.SetPadding(8, 8, 8, 8);
        imageView.SetImageResource(thumbIds[position]);
        imageView.Id = position;

        lp.AddRule(LayoutRules.Below, position);
        lp.AddRule(LayoutRules.CenterHorizontal);

        tv = new TextView(context);
        tv.Text = stringIds[position].ToString();
        tv.SetTextSize(Android.Util.ComplexUnitType.Dip, 20);
        tv.SetTextColor(Android.Graphics.Color.WhiteSmoke);
        tv.LayoutParameters = lp;

        rl.AddView(imageView);
        rl.AddView(tv);

        return rl;
    }

But the TextView always shows up on top of the ImageView.

A: Check out this question.
When you call rl.AddView(tv), you should include the LayoutParams rl.AddView(tv, lp).

A: You have to use
imageView.setLayoutParams(lp) in order to assign the params to your view.
How do you setLayoutParams() for an ImageView?

A: Since my content is not dynamic, I worked around the issue by simply editing my image in Paint and placing text below the image.  Then I made that the background for the ImageView.


Q: SQLite returned: error code = 1 I have a pre-filled database in assets folder, which I move to internal storage on first run. It works fine on some devices, but on some I get the following error: sqlite returned: error code = 1, msg = no such table: FTSgesla, db=/data/data/com.example.enigmar/databases/gesla
The mentioned table definately exist, so I don't know where the problem is.
SQLiteOpenHelper code:
public static class DictionaryOpenHelper extends SQLiteOpenHelper
{

    private final Context mHelperContext;
    private SQLiteDatabase mDatabase;

    //private static String DB_PATH="/data/data/com.example.enigmar/databases/";
    private static String DB_PATH="";
    private static final String DB_NAME = "gesla";

    DictionaryOpenHelper(Context context)
    {
        super(context, DB_NAME, null, 1);
        //
        DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
        //
        this.mHelperContext = context;

    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {

    }

    public void createDataBase() throws IOException
    {

        boolean mDataBaseExist = checkDataBase();

        if(!mDataBaseExist)
        {
            this.getReadableDatabase();
            this.close();
            new Thread(new Runnable()
            {
                public void run()
                {
                    try
                    {
                        copyDataBase();
                        Log.e(TAG, "createDatabase database created");
                        BAZA_NAREJENA=true;
                    }
                    catch (IOException e)
                    {
                        throw new RuntimeException(e);
                    }
                }
            }).start();

        }

    }

    private boolean checkDataBase()
    {

        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();

    }

    private void copyDataBase() throws IOException
    {

        InputStream mInput = mHelperContext.getAssets().open(DB_NAME);
        //final Resources resources = mHelperContext.getResources();

        String outFileName = DB_PATH + DB_NAME;

        OutputStream mOutput = new FileOutputStream(outFileName);
        //InputStream mInput = resources.openRawResource(R.raw.gesla);

        byte[] mBuffer = new byte[1024];
        int mLength;
         while ((mLength = mInput.read(mBuffer))>0)
         {
             mOutput.write(mBuffer, 0, mLength);
         }
         mOutput.flush();
         mOutput.close();
         mInput.close();

        }

    public boolean openDataBase() throws SQLException
    {

        String mPath = DB_PATH + DB_NAME;
        mDatabase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        return mDatabase != null;
    }

    @Override
    public synchronized void close() {

    if(mDatabase != null)
        mDatabase.close();

    super.close();

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

}
What is wrong?

A: In your  public void createDataBase() , you are using a Thread to copy your database in. Are you sure you have finished the copy before you try to access it?  This is my working copy of the code which is very similar to yours you may want to see. Another thing is
byte[] mBuffer = new byte[1024];

try 4096 , I had problems with 1024 before.

A: Check that the table really exists in the database. Most likely, the actual database is empty, since you don't do anything in the onCreate function (where one should initialize the database). Instead, you probably one of the following:
Instead of passing SQLiteDatabase.CREATE_IF_NECESSARY to openDatabase, call your (currently unused) function createDataBase.
Alternatively, create the database in onCreate by copying over the data of the default database. For that, you'll need another function to convert your existing in-asset database to SQL commands.


Q: ArgumentException vs. ArgumentNullException? I’m refactoring some code and adding a method which will replace a (soon-to-be) deprecated method.  The new method has the following signature:
FooResult Foo(FooArgs args) { ... }

The deprecated method contained a growing list of parameters.  These parameters are now properties on the FooArgs class.  The deprecated method has several guard conditions which checked for null values with the following structure:
if (parameter1 == null)
    throw new ArgumentNullException(“parameter1”);
if (parameter... == null)
    throw new ArgumentNullException(“parameter...”);
if (parameterN == null)
    throw new ArgumentNullException(“parameterN”);

Now that the parameters have been collapsed into the FooArgs class should I throw an ArgumentNullException for the individual properties of the FooArgs parameter:
if (args.Property1 == null)
    throw new ArgumentNullException(“args.Property1”);
if (args.Property... == null)
    throw new ArgumentNullException(“args.Property...”);
if (args.PropertyN == null)
    throw new ArgumentNullException(“args.PropertyN”);

Or to throw a more general ArgumentException for the entire FooArgs parameter:
if (args.Property1 == null)
    throw new ArgumentException(“Property1 cannot be null.”, “args”);
if (args.Property... == null)
    throw new ArgumentException(“Property... cannot be null.”, “args”);
if (args.PropertyN == null)
    throw new ArgumentException(“Property2 cannot be null.”, “args”);

Thanks!

A: You need to add a check for the args itself to be non-null. The ANE is not appropriate for individual components, so you need to use more general AE, like this:
if (args == null)
    throw new ArgumentNullException(“args”);
if (args.Property1 == null)
    throw new ArgumentException(“Property1 cannot be null.”, “args”);
if (args.Property... == null)
    throw new ArgumentException(“Property... cannot be null.”, “args”);
if (args.PropertyN == null)
    throw new ArgumentException(“Property2 cannot be null.”, “args”);

A: In this case, it may be best to check for a null reference of the FooArgs parameter inside that method, and throw an ArgumentNullException if a null reference has been passed in. Then if other methods or sections of code use the parameters contained within the args class, they should be the ones to check this and throw exceptions as necessary. However, if your method that takes in the args class is the one to use all the arguments, then it would be better to check for valid parameters in that method, as you suggested.
Also, use ArgumentNullException only for arguments that are null references. If it's simply an invalid value (for example an empty string), then you should use the more generic ArgumentException.

A: This kind of depends on your tooling and how you feel about your tooling (resharper, fxcops and the like).  Some static code analysis tools accept this:
throw new ArgumentNullException(“args.Property...”,"args");

and reject this
throw new ArgumentNullException(“args.Property...”,"args.Property");

So if you want to use the tooling, then assertions of null-hood against a parameter property must throw an ArgumentException
It's also valid to just make it up as you go along. What ever communicates the right message to the maintenance developer to help him pass the parameters correctly is the correct message.

A: While I agree completely with dasblinkenlight's answer, you may also want to consider moving the validation for FooArgs into the FooArgs class itself.  If this class is designed specifically to move arguments around, it is likely not valid for it to have null proeprties, in which case, I would allow its constructor to do its validation.


Q: Make intersection of two methods in typescript I have intersection type GetSet and instances of Get and Set. How can I compose the GetSet instance? get & set gives two errors:

*

*TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type

*TS2345: Argument of type 'number' is not assignable to parameter of type 'GetSet'. Type 'number' is not assignable to type 'Get'

type Get = (<T>(a: RecoilValue<T>) => T)
type Set = (<T>(s: RecoilState<T>, u: (((currVal: T) => T) | T)) => void)
export type GetSet = Get & Set;

// some external functions
let get: Get;
let set: Set;

function callback(getSet: GetSet) {
}

function perform() {
    callback(get & set); // <--- error here
}

A: calback(get & set) is plain wrong it will change to 0 in JavaScript (try (function () {}) & (function() {}) in chrome console), there is no & operator that will combine functions in JavaScript. type GetSet = Get & Set is a type definition in TypeScript which only means that the definition is a combination of both. However, there is no such thing in JavaScript.
If you want to pass two functions in JavaScript, you have to either use Tuple/Array or Object Literal.
   callback([get, set]);
   // or
   callback({ get, set });

However, In this case, the callback definition should change as follow,
type Get = (<T>(a: RecoilValue<T>) => T)
type Set = (<T>(s: RecoilState<T>, u: (((currVal: T) => T) | T)) => void)
export type GetSet = { get: Get, set: Set };

// some external functions
let get: Get;
let set: Set;

function callback({ get, set }: GetSet) {
}

function perform() {
    callback({ get , set }); // <--- this is correct way
}

You can combine get set as a single function as shown below...
function getOrSet(... a: any[]) {
    if (a.length === 1) {
        return get(a[0]);
    }
    return set(a[0], a[1]);
}

If you look at how jQuery was organized, you can call same method without parameter to get value and if you pass a parameter, it will set the value.
This might require rewriting many definitions.


Q: PHP MySQL SELECT from 2 tables not working I am trying to select records from two tables.
Please see the screenshots for the table structures:
Table listing

Table c_profile

I want to display  the records of listing table and few from c_profile table..
SELECT c_profile.c_name,c_profile.logo, c_profile.email, listing.id, listing.title, listing.type,listing.job_desc,listing.c_id, listing.time, listing.vote_up from c_profile,listing where c_uid=c_id

The above statement works fine but only problem is it doesn't select "vote_up" results.
However, if I use a normal SELECT statement without WHERE, it seems to work.
How can I solve this problem?

A: I think what you want is a left join, because you want all the records of listing table and a few from c_profile table.
SELECT c_profile.c_name,
       c_profile.logo,
       c_profile.email,
       listing.id,
       listing.title,
       listing.type,
       listing.job_desc,
       listing.c_id,
       listing.time,
       listing.vote_up
FROM listing
LEFT JOIN c_profile ON c_uid=c_id

this way you keep all records for listing and only join where you can find a matching c_profile

A: SELECT c_profile.c_name,c_profile.logo, c_profile.email, listing.id, listing.title, listing.type,listing.job_desc,listing.c_id, listing.time, listing.vote_up from listing left join c_profile ON c_profile.c_uid=listing .c_id


Q: Copy HTML to UIPasteboard with React Native I have a simple react-native app that has some functionality to copy HTML to the global clipboard such that it preserves the styling. The expected result is I copy HTML and can paste it into another app with the styling intact. Note, I’m not looking to paste HTML source code, that is easy and can be done simply by copying as a string.
For iOS 13 I made a minor modification to the react-native clipboard native module to change it from copying plain text to copying HTML. This code worked as expected with iOS 13, but since updating to 14 it doesn't seem to work - no value seems to be present in the clipboard.
CustomClipboard.m
#import "CustomClipboard.h"

#import <UIKit/UIKit.h>
#import <React/RCTBridge.h>
#import <React/RCTEventDispatcher.h>
#import <MobileCoreServices/MobileCoreServices.h>

@implementation CustomClipboard

RCT_EXPORT_MODULE();

- (dispatch_queue_t)methodQueue
{
  return dispatch_get_main_queue();
}

RCT_EXPORT_METHOD(setString:(NSString *)content)
{
  UIPasteboard *clipboard = [UIPasteboard generalPasteboard];
  NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
  [clipboard setData:data forPasteboardType:(NSString *)kUTTypeHTML];
}

RCT_EXPORT_METHOD(getString:(RCTPromiseResolveBlock)resolve
                  reject:(__unused RCTPromiseRejectBlock)reject)
{
  UIPasteboard *clipboard = [UIPasteboard generalPasteboard];
  resolve((clipboard.string ? : @""));
}

@end

CustomClipboard.h
#import <React/RCTBridgeModule.h>

@interface CustomClipboard : NSObject <RCTBridgeModule>

@end

The native module is imported in JS through:
import { NativeModules } from 'react-native';

export default NativeModules.CustomClipboard;

And the exposed to the rest of the app via a Clipboard module:
import NativeClipboard from './NativeClipboard';

/**
 * `Clipboard` gives you an interface for setting and getting content from Clipboard on both iOS and Android
 */
export const Clipboard = {
  /**
   * Get content of string type, this method returns a `Promise`, so you can use following code to get clipboard content
   * ```javascript
   * async _getContent() {
   *   var content = await Clipboard.getString();
   * }
   * ```
   */
  getString(): Promise<string> {
    return NativeClipboard.getString();
  },
  /**
   * Set content of string type. You can use following code to set clipboard content
   * ```javascript
   * _setContent() {
   *   Clipboard.setString('hello world');
   * }
   * ```
   * @param the content to be stored in the clipboard.
   */
  setString(content: string) {
    NativeClipboard.setString(content);
  },
};

The code all seems to run correctly, but no value is copied to the clipboard. I haven't been able to find any known bugs on this. Any ideas?

A: EDIT
This is the second attempt. Earlier I understood you wanted to copy and paste the HTML as text but after your comments and edits to the question I now understand that you have some text that you format using HTML and you want to paste that text while retaining the formatting.
More or less as shown below.

This also illustrates how to wire it up in storyboard. Here is the code.
#import "ViewController.h"

#import <MobileCoreServices/UTCoreTypes.h>
#import <WebKit/WebKit.h>

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UILabel    * statusLabel;
@property (weak, nonatomic) IBOutlet WKWebView  * webView;
@property (weak, nonatomic) IBOutlet UITextView * textView;

@end

@implementation ViewController

#pragma mark -
#pragma mark Actions

- (IBAction)reloadButtonAction:(id)sender {

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.webfx.com/blog/images/assets/cdn.sixrevisions.com/0435-01_html5_download_attribute_demo/samp/htmldoc.html"]]];

}

- (IBAction)copyButtonAction:(id)sender {

    if ( self.webView.loading ) {

        self.statusLabel.text = @"Loading";

    } else {

        self.statusLabel.text = @"Copying ...";

        [self.webView evaluateJavaScript:@"document.documentElement.outerHTML.toString()"
                   completionHandler: ^ ( id content, NSError * error ) {

            if ( error ) {

                self.statusLabel.text = @"Error";

            } else if ( [content isKindOfClass:NSString.class] ) {

                [UIPasteboard.generalPasteboard setData:[( NSString * ) content dataUsingEncoding:NSUTF8StringEncoding]
                                  forPasteboardType:( NSString * ) kUTTypeHTML];
                self.statusLabel.text = @"Copied HTML";

            } else {

                self.statusLabel.text = @"Unknown type";

            }

        }];

    }

}

- (IBAction)pasteButtonAction:(id)sender {

    if ( [UIPasteboard.generalPasteboard containsPasteboardTypes:@[( NSString * ) kUTTypeHTML]] ) {

        // Convert to attributed string
        NSError * cvtErr;
        NSData  * data = [UIPasteboard.generalPasteboard dataForPasteboardType:( NSString * ) kUTTypeHTML];
        NSAttributedString * attr = [[NSAttributedString alloc] initWithData:data
                                         options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType }
                                  documentAttributes:NULL
                                           error: & cvtErr];

        if ( cvtErr ) {

            self.statusLabel.text = @"Convert error";

        } else if ( attr ) {

            self.statusLabel.text = @"Attributed";
            self.textView.attributedText = attr;

        } else {

            self.statusLabel.text = @"Unable to decode";

        }

    } else {

        NSString * content = UIPasteboard.generalPasteboard.string;

        if ( content ) {

            // Paste plain text
            self.textView.text = content;
            self.statusLabel.text = @"Pasted";

        } else {

            self.statusLabel.text = @"No string content";

        }

    }

}

@end

The code is very similar to before. The problem is that HTML = plain text so to copy HTML and retain the style or formatting also depends on the destination app into which you paste it. That destination app needs to handle the HTML correctly for what you want to achieve.
Anyhow, here are the changes from earlier.
On the copy side: the text is now copied as HTML and not as a string. There is very little difference there except that now, unlike before, the string is converted to data and the type is marked as kUTTypeHTML.
On the paste side: the real difference is here. If the pasteboard contains HTML then it is retrieved and formatted using an attributed string. It also works fine if you e.g. paste into Notes BTW.
This illustrates the problem you are dealing with here. I could just as well have used the code I used earlier and everything would work but in stead of formatted HTML I would get the unformatted / source HTML.
Here I assume that you are interested in fairly simple but formatted text. You did not mention text specifically and if you e.g. wanted to copy an HTML formatted table then my example is not adequate as I use a UITextView as destination.
For more complex HTML I'd use a WKWebView as destination as well and set its HTML string to the pasted in HTML, but again, this shows how the destination app also needs to cooperate in handling the HTML correctly.
Finally, looking at the updated answer and your code it is difficult to spot a difference, so I suspect your problem could be earlier with content itself in
RCT_EXPORT_METHOD(setString:(NSString *)content)

UPDATE
I also looked at the git repository you mention. There I found the following
RCT_EXPORT_METHOD(hasString:(RCTPromiseResolveBlock)resolve
                  reject:(__unused RCTPromiseRejectBlock)reject)
{
  BOOL stringPresent = YES;
  UIPasteboard *clipboard = [UIPasteboard generalPasteboard];
  if (@available(iOS 10, *)) {
    stringPresent = clipboard.hasStrings;
  } else {
    NSString* stringInPasteboard = clipboard.string;
    stringPresent = [stringInPasteboard length] == 0;
  }

  resolve([NSNumber numberWithBool: stringPresent]);
}

It looks wrong, I think that one line should be
stringPresent = [stringInPasteboard length] != 0;

HTH

A: I found the answer here: http://www.andrewhoyer.com/converting-html-to-nsattributedstring-copy-to-clipboard/
The string needed to be converted to RTF before it was put in the clipboard.
RCT_EXPORT_METHOD(setString:(NSString *)content)
{
  // Source: http://www.andrewhoyer.com/converting-html-to-nsattributedstring-copy-to-clipboard/

  UIPasteboard *clipboard = [UIPasteboard generalPasteboard];

  // Sets up the attributes for creating Rich Text.
  NSDictionary *documentAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                      NSRTFTextDocumentType, NSDocumentTypeDocumentAttribute,
                                      NSCharacterEncodingDocumentAttribute, [NSNumber numberWithInt:NSUTF8StringEncoding],
                                      nil];

  // Create the attributed string using options to indicate HTML text and UTF8 string as the source.
  NSAttributedString *atr = [[NSAttributedString alloc]
                              initWithData: [content dataUsingEncoding:NSUTF8StringEncoding]
                              options: @{
                                  NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                  NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
                              }
                              documentAttributes:nil error:nil];

  // Generate the Rich Text data using the attributed string and the previously created attributes.
  NSData *rtf = [atr dataFromRange:NSMakeRange(0, [atr length]) documentAttributes:documentAttributes error:nil];

  // Set the Rich Text to the clipboard using an RTF Type
  // Note that this requires <MobileCoreServices/MobileCoreServices.h> to be imported
  [clipboard setData:rtf forPasteboardType:(NSString*)kUTTypeRTF];

}


Q: Need to commit open transaction? Is it need to commit opened hibernate transaction.What will happen if someone didn't?
Is it caused to some issues?
thanks

A: Commit will make the database commit. The changes to persistent object will be written to database. If you don't commit you will loose the changes you made in the database.

A: A transaction MUST ends, either by a commit or by a rollback.
Why ?
A transaction is consuming resources:

*

*some bytes in memory

*usually a JBDC connection. (or any kind of connection to a transnational external resource)

So,  if a tx never ends : it will use a JDBC connection forever and there a good chances that you run out of database connections.
Conclusion : you don't need to commit every tx, but you need to terminate them : either by a commit or a rollback (there is no other end state for a tx)

A: Well it is not only with hibernate transaction but with all database transactions. Commit/ Rollback are Atomicity of ACID (Atomicity, Consistency, Isolation, Durability) properties which actually represent/specifies TRANSACTION. Atomicity is more like do or die.
Answer to your question:
//creates something like cache/temporary space for you to perform all your operations. Note   this changes will not be reflected in your database at this point.
 Session.beginTransaction();

//perform some db operations

//this line flushes/post your changes from temporary stuff to database. If your changes contains error then this will not be affected/made changes to the database else the changes will be affected.
Session.commit();

Hope this is helpful!

A: A transaction must be closed. So by committing the transaction would automatically be closed as long as current context property mentioned in hibernate.cfg.xml is is thread and not managed.
This is to maintain the ACID properties of transaction. Also a when a transaction is begin it is allocated a lot of memory and resources.
What the best practices suggest is you should roll back the entire transaction and close the session if there's exception in catch block and you should commit the transaction in the last part of try block rather than finally block.


Q: Correcting country names to make them match a different naming convention I want to make a world map with ggplot as follows:
library(ggplot2)
library(countrycodes)
library(dplyr)
library(tidyverse)

worldmap_AMIS_Market <- map_data("world")
# Set colors
vec_AMIS_Market <- c("Canada", "China","United States of America", "Republic of Korea", "Russian Federation")
worldmap_AMIS_Market <- mutate(worldmap, fill = ifelse(region %in% vec_AMIS_Market, "green", "lightgrey"))

# Use scale_fiil_identity to set correct colors
ggplot(worldmap_AMIS_Market, aes(long, lat, fill = fill, group=group)) +
  geom_polygon(colour="gray") + ggtitle("Map of World") +
  ggtitle("Availability of AMIS Supply and Demand Data - Monthly") +
  scale_fill_identity()

As you can see the US does not light up in green, because in the worldmap_AMIS_Market data, the US is written as USA, while the vector uses United States of America. The same goes for Russia and South Korea. As I am going to go through this process for around 50 different datasets, I would prefer to not manually correct all countries that do no match.
Is there any way to solve issues like this? I have a couple of ideas, but not an actual solution:

*

*I could do fuzzy matching, but that won't work for USA -> United States.

*I know the package countrycodes can convert countries to iso codes etc, but I don't think it has the option to correct country names (https://github.com/vincentarelbundock/countrycode).

*I could somehow collect all alternative naming conventions for all countries, and then do a fuzzy match on that. But I don't know where to get the alternative names from, and I am not sure I would be able to write the fuzzy code for this scenario anymore.

Could someone perhaps help me fix this?

A: One option would be countrycode::countryname to convert the country names.
Note: countrycode::countryname throws a warning so it will probably not work in all cases. But at least to me the cases where it fails are rather exotic and small countries or islands.
library(ggplot2)
library(countrycode)
library(dplyr)
library(tidyverse)

worldmap <- map_data("world")
# Set colors
vec_AMIS_Market <- c("Canada", "China","United States of America", "Republic of Korea", "Russian Federation")

worldmap_AMIS_Market <- mutate(worldmap, region = countryname(region), fill = ifelse(region %in% countryname(vec_AMIS_Market), "green", "lightgrey"))
#> Warning in countrycode_convert(sourcevar = sourcevar, origin = origin, destination = dest, : Some values were not matched unambiguously: Ascension Island, Azores, Barbuda, Canary Islands, Chagos Archipelago, Grenadines, Heard Island, Madeira Islands, Micronesia, Saba, Saint Martin, Siachen Glacier, Sint Eustatius, Virgin Islands

# Use scale_fiil_identity to set correct colors
ggplot(worldmap_AMIS_Market, aes(long, lat, fill = fill, group=group)) +
  geom_polygon(colour="gray") + ggtitle("Map of World") +
  ggtitle("Availability of AMIS Supply and Demand Data - Monthly") +
  scale_fill_identity()


Q: Sticker App : UnsatisfiedLinkError after releasing app AsyncTask I am getting error as I got following crash from Play Console.
Its sticker application and I just updated, before that I have updated many times but didn't get any error.
In this updates I just changed assets folder by adding one folder with 25 images.
java.lang.RuntimeException:
  at android.os.AsyncTask$3.done (AsyncTask.java:353)
  at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:383)
  at java.util.concurrent.FutureTask.setException (FutureTask.java:252)
  at java.util.concurrent.FutureTask.run (FutureTask.java:271)
  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:245)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1162)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:636)
  at java.lang.Thread.run (Thread.java:764)
Caused by: java.lang.UnsatisfiedLinkError:
  at com.facebook.soloader.SoLoader.b (Unknown Source:254)
  at com.facebook.soloader.SoLoader.a (Unknown Source:106)
  at com.facebook.soloader.SoLoader.a (Unknown Source:94)
  at com.facebook.soloader.SoLoader.a (Unknown Source:1)
  at com.facebook.imagepipeline.nativecode.d.a (Unknown Source:20)
  at com.facebook.animated.webp.WebPImage.a (Unknown Source)
  at com.wastickers.stickers.j.a (Unknown Source:17)
  at com.wastickers.stickers.j.a (Unknown Source:19)
  at com.wastickers.stickers.j.a (Unknown Source:467)
  at com.wastickers.stickers.i.a (Unknown Source:109)
  at com.wastickers.stickers.EntryActivity$a.a (Unknown Source:11)
  at com.wastickers.stickers.EntryActivity$a.doInBackground (Unknown Source:2)
  at android.os.AsyncTask$2.call (AsyncTask.java:333)
  at java.util.concurrent.FutureTask.run (FutureTask.java:266)

I am following this repository to make this app.
build.gradle: you can also check here
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    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 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.facebook.fresco:fresco:1.12.0'
    implementation 'com.facebook.fresco:webpsupport:1.12.0'
    implementation 'com.facebook.fresco:animated-webp:1.12.0'
}

Can anyone help me out, please?

A: Here I got the solution:
As per this comment the problem with fresco, where app bundle is not well supported.

The problem was that app bundle builds multiple dexes, but Fresco was
  only looking at one to find the so file. There were no problems with
  using apk to send to play store.

From that link I found to update following libraries.
implementation 'com.facebook.fresco:fresco:1.12.0'
implementation 'com.facebook.fresco:webpsupport:1.12.0'
implementation 'com.facebook.fresco:animated-webp:1.12.0'

Update:
implementation 'com.facebook.fresco:fresco:1.12.1'
implementation 'com.facebook.fresco:webpsupport:1.12.1'
implementation 'com.facebook.fresco:animated-webp:1.12.1'

For Me, Following version worked.
Reference Link:
https://github.com/WhatsApp/stickers/issues/410
https://github.com/WhatsApp/stickers/issues/413


Q: Can I use pure SQL in ASP.net MVC? hello guys i need to use pure SQL queries for my database project
at the same time i wanna use ASP.net MVC so i can learn a new technology !!!
can i use SQL with ASP.net MVC WITHOUT using " LINQ to SQL " ?!
i'm still learning so i'm sorry if it so stupid using things the OLD SCHOOL
but my instructor insists that he want to see a PURE SQL Queries

A: Yes. You can use whatever you want for your model layer. Note, you can use raw SQL queries with LINQ To SQL as well.
Northwnd db = new Northwnd(@"c:\northwnd.mdf");
IEnumerable<Customer> results = db.ExecuteQuery<Customer>
(@"SELECT c1.custid as CustomerID, c2.custName as ContactName
    FROM customer1 as c1, customer2 as c2
    WHERE c1.custid = c2.custid"
);

Or perhaps your instructor wants straight up ADO.NET, which works fine too.
There is an example here.

A: You can use raw SQL queries in ASP.Net MVC the same way you use them anywhere else.
It can be helpful to use idioms like
using (var reader = command.ExecuteReader())
    return View(reader.Select(dr => new { Name = dr["Name"], ... }));

EDIT: It appears that you're asking how to use ADO.Net in general.
Try this tutorial.

A: Of course you can use SQL in ASP.NET MVC. I'd consider keeping the SQL code on stored procedures rather than hard-coding the SQL directly in the application code. It's better to maintain and it's a good practice that will probably be looked upon by your instructor.

A: SQL has nothing to do with ASP.NET MVC. ASP.NET MVC is a web framework for building web sites and applications. My suggestion is that you try to abstract as much as possible, the MVC application shouldn't know if you're using SQL (stored procedures), Entity Framework, Linq-to-sql or if you get your data from a web-service.


Q: How to extract information from the command line? I would like to analyze the options passed via the command line using C++ and QT, without using external libraries. In particular, assuming that the possible lines of command are the following ones, what is the easiest way to analyze and extract the required information (path, string, int_1, int_2, int_3)?
--intrinsic <path> <int_1> <int_2> <int_3>
--extrincic <path> -solve -3D <string> -2D <string>
--extrincic <path> -verify -3D <string>

A: Maybe the new class QCommandLineParser can help you.


Q: The web server hangs while calling 3rd party Web API from my Web API I need to call a 3 party Web Api from my ASP.net Web API, when it runs the line
HttpResponseMessage response = await client.PostAsJsonAsync("api/ArTrx/postDocument", poMaster);

the web server hangs. I have tried to put below code in to a console program, it runs well. What is wrong with below code when run in ASP.net Web API project?
client.BaseAddress = new Uri(webAPIAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

string token = Crypto.EncryptStringAES("abcd1234");
client.DefaultRequestHeaders.Add("X-Token", token);

HttpResponseMessage response = await client.PostAsJsonAsync("api/ArTrx/postDocument", poMaster);
if (response.IsSuccessStatusCode)
{
    ...
}

A: You probably have a Task<T>.Result or Task.Wait call further up your call stack. This will cause a deadlock on ASP.NET that I describe in more detail on my blog.
In summary, await will capture a "context" - in this case, an ASP.NET request context, which only allows one running thread at a time. When its awaitable completes (that is, when the POST finishes), the async method will continue in that context. If your code is blocking further up the call stack (e.g., Result or Wait), then it will block a thread in that ASP.NET request context, and the async method cannot enter that context to continue executing.
You don't see the deadlock in the Console app because there's no context being captured, so the async method resumes on a thread pool thread instead.


Q: Create maven dependency instead of .jar Is there a way where I can take an existing java project (it's an automation framework) and actually export it out in a way that another project can consume it using the maven GAV instead of having to add it as an external jar?
I was able to create a jar of the framework project and then tested adding the jar to a 2nd project and all that works fine. I really would just prefer to be able to reference the framework project as a maven dependency in the pom instead of having to add the jar. I also think this will be easier when it comes to making updates to the framework and having the consuming projects just update the version of the maven dependency in the pom.
Of course I could be way off with my thinking here. I'm primarily in the c# world where I can just export my project out as a nuget package that gets consumed easily so that's what I'm used to.
Thanks!


Q: CURL to C# HttpWebRequest I need help with converting PHP's CURL to C# HttpWebRequest. My c# code doesn't work well, the request loads all the time ending with timeout exception. Here is my PHP code:
    $curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_URL, 'https://api.example.com/');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Origin: http://media.example.com/',
        'Accept-Encoding: gzip,deflate,sdch',
        'Host: api.example.com',
        'Accept-Language: en-US,en;q=0.8',
        'Authorization: FD 08306ECE-C36C-4939-B65F-4225F37BD296:905664F40E29B95CF5810B2ACA85497C7430BB1498E74B52',
        'Content-Type: application/json',
        'Accept: */*',
        'Referer: http://example.com',
        'User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36',
        'Connection: keep-alive'
    )
);

curl_setopt($curl, CURLOPT_POSTFIELDS, '{"language":"en","original_text":"' . $text . '","product":"pen"}' . chr(10));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$data = curl_exec($curl);
curl_close($curl);

And here is my c# code:
            var request = WebRequest.Create("https://api.example.com/social/autocomplete/v2/search/messages") as HttpWebRequest; ;

        request.ContentType = "application/json";
        request.Method = "POST";
        request.Headers["Origin"] = "http://media.example.com";
        request.Headers["Accept-Encoding"] = "gzip,deflate,sdch";
        //request.Headers["Host"] = "api.example.com"
        request.Host = "api.example.com";
        request.Headers["Accept-Language"] = "en-US,en;q=0.8";
        request.Headers["Authorization"] = "FD 08306ECE-C36C-4939-B65F-4225F37BD296:905664F40E29B95CF5810B2ACA85497C7430BB1498E74B52";
        request.ContentType = "application/json";
        request.Accept = "*/*";
        request.Referer = "http://example.com/";
        request.UserAgent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
        request.KeepAlive = true;
        byte[] buffer = Encoding.UTF8.GetBytes("{\"language\":\"en\",\"original_text\":\"hello\",\"product\":\"pen\"}");
        string result = System.Convert.ToBase64String(buffer);
        Stream reqstr = request.GetRequestStream();
        reqstr.Write(buffer, 0, buffer.Length);
        reqstr.Close();

        WebResponse response = request.GetResponse();
        Console.WriteLine(response.ToString());
        Console.ReadKey();

I hope someone can help me. Thanks in advance.

A: You need to read the response stream from the web server.
Use the response.GetResponseStream() function.
If the response contains Unicode text, you can read that text using a StreamReader.


Q: My website is accessible to some users but throws "this site can't be reached" for others I recently set up a website http://shehara.co and it works fine on my pc and phone and some of my friends, when working properly it should display "nothing to see here" on the top left corner, But for most users, it does not load.
I tried pinging it through my command prompt and that fails too(all packets lost), then I tried the site downforeveryoneorjustme.com which again tells the site is down, I'm confused to as what is happening, I'm using a free host service called byet.host, can someone explain how to fix this

A: Now site is working but showing nothing is here I think at that time server has got to many requests that's why it cannot be reached .


Q: Images and Icons for Apps (Android - iOS) I am creating my first App for the iOS and Android platforms and want to start with some good icons and images. I do not want to spent a lot of money on them. I also do not have experience with softwares like photoshop to create my own images and icons.
I am trying to find some websites that can provide me with sports related UI resources.
What are some popular/good sites that I can utilize for my project.

A: I recommend two sites: IconArchive and Icon8.
They both have free icon sets that can help you to get you started with your designs!
Cheers

A: Depends on what kind of resources your looking for, if it's mainly icons I suggest: http://iconfinder.com
If your looking for photo resources I would try http://gettyimage.com


Q: raspberry pi camera motion detection I'm programming a motion detection system using Raspberry Pi, the official Raspberry Pi Camera and OpenCV with Python. While I'm using the absdiff and bitwise_and operation it comes up with this:

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor,
  file /home/pi/opencv-2.4.10/modules/imgproc/src/color.cpp, line 3739
  Traceback (most recent call last):   File "icanseeu-diff.py", line 18,
  in
      t_minus = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY) cv2.error:
  /home/pi/opencv-2.4.10/modules/imgproc/src/color.cpp:3739: error:
  (-215) scn == 3 || scn == 4 in function cvtColor

Here is the code:
import cv2
from picamera.array import PiRGBArray
from picamera import PiCamera
import time

camera = PiCamera()
camera.resolution = (320, 240)
camera.framerate = 30
camera.rotation = 180
rawCapture = PiRGBArray(camera, size = (320, 240))

def diffImg(t0, t1, t2):
    d1 = cv2.absdiff(t2, t1)
    d2 = cv2.absdiff(t1, t0)
    return cv2.bitwise_and(d1, d2)

# Read three images first
frame1 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY)
frame2 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY)
frame3 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY)

while True:
    cv2.imshow( motions, diffImg(t_minus, t, t_plus) )

    # Read next image
    frame1 = frame2
    frame2 = frame3
    frame3 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY)

    key = cv2.waitKey(10)
    if key == 27:
        cv2.destroyWindow(motions)
        break

Seems like an assignation problem, but I don't know how to deal with it. What should I do? Thanks!

A: The error message that you are getting is informing you that image that you are passing does not have 3 or 4 channels. This is the assestion that has failed.
This is because camera.capture function does not return any values (API Documentation). Instead the rawCapture gets updated, it is this that you should be passing to cvtColor.
Instead of
frame1 = cv2.cvtColor(camera.capture(rawCapture, format = "bgr", use_video_port = True), cv2.COLOR_RGB2GRAY)

Use
rawCapture.truncate()
camera.capture(rawCapture, format = "bgr", use_video_port = True)
frame1 = cv2.cvtColor(rawCapture.array, cv2.COLOR_BGR2GRAY)

And the same for each time you capture an image.
I haven't been able to test this as I don't currently have my Raspberry Pi and Camera on me but it should fix the problem.

A: I think you didn't close your camera, so python thinks that the camera is used by another program. Try to restart your Pi. The program should work after the restart. The second start of the program after the restart won't work. If this happens, close the camera in the last if-statement.

A: To save your time, I have built a completed application to detect motion and notify to the iOS/Android. The notification will have text, image, and video.
Check this out


Q: Selenium Webdriver error: An item with the same key has already been added Can someone advice me how to prevent this error: "An item with the same key has already been added."?
I have two tests that runs fine when run individually, but when I "run all" in visual studio, I get that error.
[Binding]
public sealed class Steps
{
    private Squish squish = new Squish();
    private Tools tools = new Tools();

    [Given(@"I navigated to the Squish homepage")]
    public void GivenINavigatedToTheSquishHomepage()
    {
        squish.NavigateToURL("Squish.com");
        ScenarioContext.Current["siteTitle"] = squish.GetPageTitle();
    }

Is there any alternatives to FeatureContext.Current.Add(key, value)? So I don't have to be directly be storing anything?

A: I guess you should read specflow documentation about parallel test runs http://specflow.org/documentation/Parallel-Execution/
It's said:

You may not be using the static context properties
  ScenarioContext.Current, FeatureContext.Current or
  ScenarioStepContext.Current.

Actually your error is self-descriptive - you've created item in dictionary with key "siteTitle"


Q: How to read this data into a .json file format? private ArrayList<Double> celciusList = new ArrayList<Double>();
private ArrayList<Double> farenList = new ArrayList<Double>();
private ArrayList<Double> LDRlist = new ArrayList<Double>();
private ArrayList<Double> inchList = new ArrayList<Double>();
private ArrayList<Double> cmList = new ArrayList<Double>();

How do i possibly use this data information as my headings to print out in a .json file format?

A: I would use some kind of Java JSON Serializer, there a few of them out there.

*

*GSON

*FlexJson

Here is a simple example with FlexJson on how you could convert an object to JSON String.
final JSONSerializer serializer = new JSONSerializer();
final String output = serializer.transform(new ProtocolCalculatorTransformer(),ProtocolCalculation.class).exclude("*.class").deepSerialize(this);
return output;


Q: how do i make my website background a gradient colour? I am currently trying to create a website.
I have created the logo for the website but I'm not sure how to make my header and footer background a gradient color on Dreamweaver CS6.
I can only put it as a solid color and I am not sure if I need to use CSS or HTML to change it.
Does anyone know if it is possible, and if it is how to do it?
thanks :)

A: There is a online tool from which you can generate css gradient -
http://www.colorzilla.com/gradient-editor/
On left side of screen you have options to choose colors and on right you have code which you need to copy in your css.

A: Try www.css3generator.com and then select gradient and select color and equivalent code will be generated ..copy the code and use in your CSS.
This site is very helpful.

A: Use CSS3:
  body {
    background-image: -webkit-linear-gradient(top left, white 0%, #9FBFD2 100%);
    background-image: -moz-linear-gradient(top left, white 0%, #9FBFD2 100%);
    background-image: -o-linear-gradient(top left, white 0%, #9FBFD2 100%);
    background-image: linear-gradient(top left, white 0%, #9FBFD2 100%);
  }


Q: Dynamically serving users from one of the multiple servers behind a single domain? When someone registers to my SaaS app they are assigned to a region (US/EU/Pacific), and it is saved into the DB. In this example I have 3 servers, 1 for each region.
When a user logs in (it could be a single central server/subdomain for the whole world), I want to get their region from DB, and serve them from that server directly (so I do not just want to make a load balancer, I actually want the traffic to go directly to the assigned server).
Handling it using Round Robin on the DNS level is not a viable solution, because the servers in different regions will have different database content, and possibly different software versions, so random distribution is unwanted.
Obviously I could make different subdomains like us.app.com and eu.app.com, but what I would like to do is to solve this problem with a minimum number of subdomains.
Is there an elegant way to do this?

A: You need either a geo IP capable or latency based DNS service (e.g. AWS Route 53) to make shure visitors from a distinct region connect to the right server. See  http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html if it's an option for you to use Route53.


Q: How to keep ui-router parameters on browser refresh I'm using a ui-sref which takes two strings and an object as parameters.  All works fine under normal circumstances, however when I refresh the browser on the page which I have navigated to the object becomes null.
The two strings in the URL are fine after a refresh.  Is there a way to get the object to persist in the $stateparams after a page refresh.  I have tried several options such as $rootscope.$stateparams = $stateparams, I've tried using a service too but it gets wiped on a refresh.  Using local storage is not an option.
.state('edit', {
        url: '/editItem/:id?userId',
        templateUrl: 'app/items/edit.html',
        controller: 'editController',
        controllerAs: 'vm',
        params: {
            id: "",
            userId: "",
            userObject: null,
        }
})

I really just need the object to persist on reload.  I'm using UI-router 1.0.0-beta.2

A: If you want to use your url params in your state everytime, you can use the resolve function:
.state('edit', {
        url: '/editItem/:id/:userId',
        templateUrl: 'app/items/edit.html',
        controller: 'editController',
        controllerAs: 'vm',
        resolve: {
          testObject: function($stateParams) {
             return {
              id: $stateParams.id,
              userId: $stateParams.userId
             }
          }
        }

    })

Now, you can pass testObject as a dependency to your editController and every time this route is resolved, the values will be available within your controller as testObject.id and testObject.userId
If you want to pass an object from one state to the next, use $state.go programatically:
$state.go('myState', {myParam: {some: 'thing'}})

$stateProvider.state('myState', {
                url: '/myState',
                params: {myParam: null}, ...

The only other option is to cache, trough Localstorage or cookies


Q: Min Fibonacci Heap - How to implement increase-key operation? I have been trying to implementing heap data structures for use in my research work. As part of that, I am trying to implement increase-key operations for min-heaps. I know that min-heaps generally support decrease-key. I was able to write the increase-key operation for a binary min-heap, wherein, I exchange increased key with the least child recursively.
In the case of the Fibonacci heap, In this reference, they say that the Fibonacci heap also supports an increase-key operation. But, I couldn't find anything about it in the original paper on Fibonacci Heaps, nor could I find anything in CLRS (Introduction to Algorithms by Cormen).
Can someone tell me how I can go about implementing the increase-key operation efficiently and also without disturbing the data structure's amortized bounds for all the other operations?

A: First, note that increase-key must be (log) if we wish for insert and find-min to stay (1) as they are in a Fibonacci heap.
If it weren't you'd be able to sort in () time by doing  inserts, followed by repeatedly using find-min to get the minimum and then increase-key on the head by  with ∀:> to push the head to the end.
Now, knowing that increase-key must be (log), we can provide a straightforward asymptotically optimal implementation for it. To increase a node  to value , first you decrease-key(,−∞), then delete-min() followed by insert(,).
Refer here


Q: Invalid hook call inside arrow functional component although the code runs I'm learning react and am trying to get a simple pop-up to show whenever the Show Toast button is clicked using Toast. However, I'm receiving this error:
Error in /turbo_modules/react-dom@16.13.1/cjs/react-dom.development.js (12408:27)
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

I'm assuming it's something simple although I'm not used to hooks. The error states that hooks can only be called inside the body of a functional component, so:

*

*Where is technically the body of a functional component? I assume where I've put this comment: //body of functional component here

*Why is this error also appearing in the JS console: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method

*How can I get the pop-up to show? The console.log('click') shows in the console so I assume it's the succeeding toast code that's incorrect

Here is a stackblitz demo
And here is the code:
import React from "react";
import { useForm } from "react-hook-form";
import { useToast } from "@chakra-ui/core";

const App = () => {
  const { register, handleSubmit, watch, errors } = useForm();
  //const toast = useToast();
  const onSubmit = data => {
      console.log('data', data);
    };

  // body of functional component here?

  const toastTest = () =>
    {
      const toast = useToast();
      return (
      <button
        onClick={() =>
          {
            console.log('click');
            toast({
              title: "Account created.",
              description: "We've created your account for you.",
              status: "success",
              duration: 9000,
              isClosable: true,
            })
          }
        }
      >
        Show Toast
      </button>
    )
  };

  console.log(watch("example"));

  return (
    <>

    {toastTest()}

    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="example" defaultValue="test" ref={register} />

      <input name="exampleRequired" ref={register({ required: true })} />
      {errors.exampleRequired && This field is required}

      <input type="submit" />
    </form>
    </>
  );
}

export default App

I've seen similar other posts from other users but cannot get this to work. Any beginner advice to hooks would be appreciated, thank you.

A: Technically you are violating the Rules of Hooks. You should move out useToast from the function's body called toastTest into the root of your function component.
See my suggested solution below:
const App = () => {
  const toast = useToast(); // useToast moved here from the function
  const { register, handleSubmit, watch, errors } = useForm();

  const onSubmit = data => {
      console.log('data', data);
  }

  const toastTest = () =>
     // please notice useToast is removed from here
     // ... rest of the function's body
  }

  return <> { /* your return */ }</>
}


Q: Calculating 3D pixel variance from 4D array Let there be some 4D array [x,y,z,k] comprised of k 3D images [x,y,z].
Is there any way to calculate the variance of each individual pixel in 3D from the 4D array?
E.g. I have a 10x10x10x5 array and would like to return a 10x10x10 variance array; the variance is calculated for each pixel (or voxel, really) along k
If this doesn't make sense, let me know and I'll try explaining better.
Currently, my code is:
tensors = []
while error > threshold:
    for _ in range(5): #arbitrary
        new_tensor = foo(bar) #always returns array of same size
        tensors.append(new_tensor)

tensors = np.stack(tensors, axis = 3)
#tensors.shape

And I would like the calculate a variance array for tensors

A: There is a simple way to do that if you're using numpy:
variance = tensors.var(axis=3)


Q: Dictionary comprehension inside insert() method not working I am making a MappingList class which is a list implemented as an OrderedDict.
This is the MappingList class (some methods omitted):
class MappingList(MutableSequence):
    """
    A MappingList is a regular list implemented as a dictionary
    """

    def __repr__(self):
        return str(list(self.seq.values()))

    def __getitem__(self, item):
        try:
            return self.seq[item]
        except KeyError:
            _traceback_from_none(IndexError, "list index out of range")

    def __setitem__(self, key, value, *, usage=None):
        if key > max(self.seq.keys()) and usage != "append":
            raise IndexError("list index out of range")
        self.seq[key] = value

    def __delitem__(self, key):
        try:
            del self.seq[key]
        except KeyError:
            _traceback_from_none(IndexError, "list index out of range")

    def __len__(self):
        return len(self.seq)

    def __eq__(self, other):
        if not isinstance(other, MappingList):
            return NotImplemented
        return self.seq == other.seq

    @classmethod
    def _dict_from_seq(cls, seq):
        return OrderedDict(enumerate(seq))

    def _next_available_slot(self):
        return max(self.seq) + 1

    def insert(self, index, value):  # todo: insert() should not overwrite
        """Insert a value into the MappingList"""
        if index > max(self.seq.keys()):
            raise IndexError("list index out of range")

        for k, v in {k: v for k, v in self.seq.items() if k > index}:
            del self.seq[k]
            self.seq[k + 1] = v

        self[index] = value

When I try to insert an item into a MappingList, I get the following error:
  File "C:\...\My Python Programs\free_time\mappinglist.py", line 103, in test_insert
    self.li.insert(1, MappingList(["blah", 1, 5.8]))
  File "C:\...\My Python Programs\free_time\mappinglist.py", line 85, in insert
    for k, v in {k: v for k, v in self.seq.items() if k > index}:
TypeError: cannot unpack non-iterable int object

Why is this error happening? Does OrderedDict.items() return an integer?

A: The error doesn't happen due to that.
When you don't provide keys(), values(), items(), python iterates over the keys by default. You need to provide items() to tell python to get the keys and values.
for k, v in {k: v for k, v in self.seq.items() if k > index}.items():


Q: Downloading files from an sftp site - how? I have the username and password.
Using Firefox, the URL ftp://myuid@ftp.xxx.com pops a dialogue asking fo the password. The the response is '503 User not logged in'
Using IE, the URL ftp.xxx.com pops a dialogue asking for username and password; the response is the same as with Firefox.
How do I connect to the site?
If not using a browser, can I connect from the command line?
Thank you for your help.

A: SFTP has nothing to do with FTP, except inasmuch as both are for transferring files.  Firefox out of the box doesn't speak SFTP, last i heard.
In order to download something via SFTP, you'll need an SFTP client, like WinSCP. or PSFTP (part of PuTTY).  Both are free.  Or, apparently, there's a FF addon called FireFTP.


Q: What naming convention for a method/function that both sets and gets a value? This may come across as a strange question, since the convention is usually to have separate set and get methods.  But in my case, it is a bit different: an argument to a function decides whether that function is a getter or a setter, so I am looking for a function name that will indicate such function.
Some names I have found were getset, setget, rw, and etc but i find these names rather strange.  What kind of naming convention would fit for such functions?

A: Until Java beans came along with the get/set naming convention, one quite often saw functions (particularly methods in C++ and other OO languages) that did exactly as you describe.
They were often named after the variable that they set or got, e.g.:
int counter_;

int counter () {
    return counter_;
}

int counter (int c) {
    counter_ = c;
    return counter_;
}

In languages with different namespaces for variables and functions, you could even have the variable and the get/set functions have exactly the same name (without the need for a trailing _ as I've shown here).
In languages with default parameters, you could potentially write the getter and setter as one function, e.g. something like this:
int counter (int c = MAX_INT) {
    if (c != MAX_INT) {
        counter_ = c;
    }
    return counter_;
}

... though I wasn't particularly keen on that approach because it led to subtle bugs if someone called counter (MAX_INT), for instance.
I always thought that this naming approach made some sense and I've written some libraries that worked that way.
This naming convention did, however, potentially confuse the reader of the code, particularly in languages where one could call a parameterless function without the trailing parentheses, so it was hard to see if a function was being called or if a public variable was being accessed directly. Of course some would call the latter a feature rather than a problem ...

A: How about just name the function after the name of the variable it populates? Like a property, when the parameter passed is null or other special value, then it is get, otherwise it is set.


Q: Is shallow copy sufficient for structures with char[]? I have a structure containing character arrays with no any other member functions. I am doing assignment operation between two instances of these structures. If I'm not mistaken, it is doing shallow copy. Is shallow copy safe in this case?
I've tried this in C++ and it worked but I would just like to confirm if this behavior is safe.

A: Assigning structs does a member-wise assignment, and for arrays this means assigning each item.  (And this is done recursively for "multiple dimension" arrays, which are really just arrays of arrays.)
You are correct that it does a shallow copy, even on arrays.  (I'm assuming that you have not overloaded op= with respect to C++; if you overload it you can do anything you want.)
Remember that a shallow copy means copying the value of something, while a deep copy means copying the value to which something points or refers.  The value of an array is each item in it.
The difference between shallow and deep is most meaningful when you have a type that does indirection, such as a pointer.  I find my answer the most helpful way to look at this issue, but you could also say "shallow" vs "deep" doesn't even apply to other types, and they are just "copied".
struct S {
  int n;
  int* p;
  int a[2];
  int* ap[2];
  int xy[2][2];
};

void f() {
  S c, d;

  c = d;
  // equivalent to:
  c.n = d.n;
  c.p = d.p;

  c.a[0] = d.a[0];  // S::a is similar to your situation, only using
  c.a[1] = d.a[1];  // int instead of char.

  c.ap[0] = d.ap[0];
  c.ap[1] = d.ap[1];
  c.xy[0][0] = d.xy[0][0];
  c.xy[0][1] = d.xy[0][1];
  c.xy[1][0] = d.xy[1][0];
  c.xy[1][1] = d.xy[1][1];
}

That I used int above doesn't change anything of the semantics, it works identically for char arrays, copying each char.  This is the S::a situation in my code.
Note that p and ap are copied shallowly (as is every other member).  If those pointers "own" the memory to which they point, then it might not be safe.  ("Safe" in your question is vague, and really depends on what you expect and how you handle things.)
For an interesting twist, consider boost::shared_ptr and other smart pointers in C++.  They can be copied shallowly, even though a deep copy is possible, and this can still be safe.

A: If by "shallow copy", you mean that after assignment of a struct containing an array, the array would point to the original struct's data, then: it can't.  Each element of the array has to be copied over to the new struct.  "Shallow copy" comes into the picture if your struct has pointers.  If it doesn't, you can't do a shallow copy.
When you assign a struct containing an array to some value, it cannot do a shallow copy, since that would mean assigning to an array, which is illegal.  So the only copy you get is a deep copy.
Consider:
#include <stdio.h>

struct data {
    char message[6];
};

int main(void)
{
    struct data d1 = { "Hello" };
    struct data d2 = d1; /* struct assignment, (almost) equivalent to
                            memcpy(&d2, &d1, sizeof d2) */

    /* Note that it's illegal to say d2.message = d1.message */

    d2.message[0] = 'h';
    printf("%s\n", d1.message);
    printf("%s\n", d2.message);
    return 0;
}

The above will print:
Hello
hello

If, on the other hand, your struct had a pointer, struct assignment will only copy pointers, which is "shallow copy":
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct data {
    char *message;
};

int main(void)
{
    struct data d1, d2;
    char *str = malloc(6);
    if (str == NULL) {
        return 1;
    }
    strcpy(str, "Hello");
    d1.message = str;
    d2 = d1;

    d2.message[0] = 'h';
    printf("%s\n", d1.message);
    printf("%s\n", d2.message);
    free(str);
    return 0;
}

The above will print:
hello
hello

In general, given struct T d1, d2;, d2 = d1; is equivalent to memcpy(&d2, &d1, sizeof d2);, but if the struct has padding, that may or may not be copied.
Edit: In C, you can't assign to arrays.  Given:
int data[10] = { 0 };
int data_copy[10];

data_copy = data;

is illegal.  So, as I said above, if you have an array in a struct, assigning to the struct has to copy the data element-wise in the array.  You don't get shallow copy in this case: it doesn't make any sense to apply the term "shallow copy" to a case like this.


Q: python. how to export to csv file after gather data on web I did some web scraping with selenium and was able to generate to print a table with the data I need to export (see image below). How can now export it to csv (place a .csv in a specific folder with todays date).
Thanks a lot for your inputs.
from selenium import webdriver
from selenium.webdriver.support.ui import Select

path_to_chromedriver = 'C:\python34\chromedriver\chromedriver.exe' # change path as needed
browser = webdriver.Chrome(executable_path = path_to_chromedriver)
url = 'http://test.com'
browser.get(url)

browser.find_element_by_xpath("//select[@name='query_choice']/option[text()='60 days']").click() # working to select DLP

browser.find_element_by_css_selector('input[type=\"submit\"]').click() # working to press submit

for tag in browser.find_elements_by_xpath('//*[@id="page1"]/table'):
    print (tag.text)

A: Assuming your table is a list
with open('saveTo\Directory\file.csv','w') as f:
    f.write(','.join(tableData))

Where you can technically, call the f.write method on each line of the table as soon as you have it, but change the 'w' parameter to 'a' to append to the file


Q: Nested ListView in wicket throwing IndexOutOfBoundsException I have a nested ListView in wicket which for some reason is throwing an IndexOutOfBoundsException. Here is the relevant markup:

and the relevant code:
    ListView<User> dataRow = new ListView<User>("dataRow", new AbstractReadOnlyModel<List<User>>() {
        private static final long serialVersionUID = 1L;
        @Override
        public List<User> getObject() {
            ...
            return getUsers(itemOffset, c, filter, sc, isDescending );
            // returns a List<User> of row objects
        }

    }) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void populateItem(ListItem<User> item) {
            // list of s
            ListView<String> dataCell = new ListView<String>("dataCell",new AbstractReadOnlyModel<List<String>>() {
                private static final long serialVersionUID = 1L;

                @Override
                public List<String> getObject() {
                    return getColumnValues(item.getModelObject());
                    // gets a list of strings to display from the User object
                }
            }) {
                private static final long serialVersionUID = 1L;

                @Override
                protected void populateItem(ListItem<String> stringItem) {
                    Label dataContent = new Label("dataContent", stringItem.getModel());
                    dataContent.setRenderBodyOnly(true);
                    stringItem.add(dataContent);
                }
            };
            dataCell.setReuseItems(true);
            item.add(dataCell);
        }
    };
    dataRow.setReuseItems(true);
    add(dataRow);

No Ajax refresh or anything has been done (yet), but I get an exception at the first rendering already:
Unexpected RuntimeException

Last cause: Index: 10, Size: 10
WicketMessage: Exception in rendering component: [Component id = dataContent]

Stacktrace

Root cause:

java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
 at java.util.ArrayList.rangeCheck(ArrayList.java:653)
 at java.util.ArrayList.get(ArrayList.java:429)
 at org.apache.wicket.markup.html.list.ListItemModel.getObject(ListItemModel.java:59)
 at org.apache.wicket.Component.getDefaultModelObject(Component.java:1605)
 at org.apache.wicket.markup.html.list.ListItem.getModelObject(ListItem.java:92)
 at myadmin.web.panels.TableViewPanel$3$1.getObject(TableViewPanel.java:156)
 at myadmin.web.panels.TableViewPanel$3$1.getObject(TableViewPanel.java:1)
 at org.apache.wicket.Component.getDefaultModelObject(Component.java:1605)
 at org.apache.wicket.markup.html.list.ListView.getModelObject(ListView.java:643)
 at org.apache.wicket.markup.html.list.ListItemModel.getObject(ListItemModel.java:59)
 at org.apache.wicket.Component.getDefaultModelObject(Component.java:1605)
 at org.apache.wicket.Component.getDefaultModelObjectAsString(Component.java:1633)
 at org.apache.wicket.markup.html.basic.Label.onComponentTagBody(Label.java:131)
 at org.apache.wicket.markup.html.panel.DefaultMarkupSourcingStrategy.onComponentTagBody(DefaultMarkupSourcingStrategy.java:71)
 at org.apache.wicket.Component.internalRenderComponent(Component.java:2529)
 at org.apache.wicket.markup.html.WebComponent.onRender(WebComponent.java:56)
 at org.apache.wicket.Component.internalRender(Component.java:2359)
 at org.apache.wicket.Component.render(Component.java:2287)
 at org.apache.wicket.MarkupContainer.renderNext(MarkupContainer.java:1392)
 at org.apache.wicket.MarkupContainer.renderAll(MarkupContainer.java:1557)
 at org.apache.wicket.MarkupContainer.renderComponentTagBody(MarkupContainer.java:1532)
 at org.apache.wicket.MarkupContainer.onComponentTagBody(MarkupContainer.java:1487)
 at org.apache.wicket.markup.html.panel.DefaultMarkupSourcingStrategy.onComponentTagBody(DefaultMarkupSourcingStrategy.java:71)
 at org.apache.wicket.Component.internalRenderComponent(Component.java:2529)
 at org.apache.wicket.MarkupContainer.onRender(MarkupContainer.java:1496)
 at org.apache.wicket.Component.internalRender(Component.java:2359)
 at org.apache.wicket.Component.render(Component.java:2287)
 at org.apache.wicket.markup.html.list.ListView.renderItem(ListView.java:584)
 at org.apache.wicket.markup.html.list.ListView.renderChild(ListView.java:573)
 at org.apache.wicket.markup.repeater.AbstractRepeater.onRender(AbstractRepeater.java:101)
 at org.apache.wicket.Component.internalRender(Component.java:2359)
 at org.apache.wicket.Component.render(Component.java:2287)
 at org.apache.wicket.MarkupContainer.renderNext(MarkupContainer.java:1392)
 at org.apache.wicket.MarkupContainer.renderAll(MarkupContainer.java:1557)
 at org.apache.wicket.MarkupContainer.renderComponentTagBody(MarkupContainer.java:1532)
 at org.apache.wicket.MarkupContainer.onComponentTagBody(MarkupContainer.java:1487)
 at org.apache.wicket.markup.html.panel.DefaultMarkupSourcingStrategy.onComponentTagBody(DefaultMarkupSourcingStrategy.java:71)
 at org.apache.wicket.Component.internalRenderComponent(Component.java:2529)
 at org.apache.wicket.MarkupContainer.onRender(MarkupContainer.java:1496)
 at org.apache.wicket.Component.internalRender(Component.java:2359)

...
I don't see what I'm doing wrong. Any help would be greatly appreciated.


Q: -Replace Operator not accepting capture group variable and user variable at once In the below example if I use single quotes for the -Replace operator ('Tag000: (.*)', 'Tag000: $1 hello $scategory') the capture group variable ($1) gets resolved at run time, while $scategory does not.
If I use double quotes (-replace "Tag000: (.*)", "Tag000: $1 hello $scategory") the $scategory variable works but then the capture group varibale is not recognised
$scategory = "my car is red "
$Read_Opus_Category= Get-Content -Path "C:\Temp\Chapter 6.ps1" -Stream multitags.txt -Raw
$Modified_Opus_Category= $Read_Opus_Category -replace 'Tag000: (.*)', "Tag000: $1 hello $scategory"

Am at a loss here, any help would be wonderfull

A: Use ` to escape the $ in an expandable string literal:
$Read_Opus_Category -replace 'Tag000: (.*)', "Tag000: `$1 hello $scategory"


Q: Hadoop, MapReduce Custom Java Counters Exception in thread "main" java.lang.IllegalStateException: Job in state DEFINE instead of RUNNING Error is:
Exception in thread "main" java.lang.IllegalStateException: Job in state DEFINE instead of RUNNING
    at org.apache.hadoop.mapreduce.Job.ensureState(Job.java:294)
    at org.apache.hadoop.mapreduce.Job.getCounters(Job.java:762)
    at com.aamend.hadoop.MapReduce.CountryIncomeConf.main(CountryIncomeConf.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)

The error shows that the problem lies in the line:

Counter counter =
       job.getCounters().findCounter(COUNTERS.MISSING_FIELDS_RECORD_COUNT);

Also I do have a enum with the name COUNTERS.
Mapper :
     import java.io.IOException;

        import org.apache.hadoop.io.DoubleWritable;
        import org.apache.hadoop.io.Text;
        import org.apache.hadoop.mapreduce.Mapper;
        import org.apache.log4j.Logger;

  public class CountryIncomeMapper extends Mapper<Object, Text, Text, DoubleWritable> {

      private Logger logger = Logger.getLogger("FilterMapper");

      private final int incomeIndex = 54;
      private final int countryIndex = 0;
      private final int lenIndex = 58;

      String seperator = ",";

      public void map(Object key, Text line, Context context) throws IOException,
          InterruptedException {

        if (line == null) {
          logger.info("null found.");
          context.getCounter(COUNTERS.ERROR_COUNT).increment(1);
          return;
        }
        if (line.toString().contains(
            "Adjusted net national income per capita (current US$)")) {
          String[] recordSplits = line.toString().split(seperator);

          logger.info("The data has been splitted.");

          if (recordSplits.length == lenIndex) {

            String countryName = recordSplits[countryIndex];
            try {

              double income = Double.parseDouble(recordSplits[incomeIndex]);

              context.write(new Text(countryName), new DoubleWritable(income));

            } catch (NumberFormatException nfe) {

              logger.info("The value of income is in wrong format." + countryName);
              context.getCounter(COUNTERS.MISSING_FIELDS_RECORD_COUNT).increment(1);
              return;
            }

          }
        }
      }
    }

Driver Class :
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

public class CountryIncomeConf {

  public static void main(String[] args) throws IOException,
      InterruptedException, ClassNotFoundException {

    Path inputPath = new Path(args[0]);
    Path outputDir = new Path(args[1]);

    // Create configuration
    Configuration conf = new Configuration(true);

    // Create job
    Job job = new Job(conf, "CountryIncomeConf");
    job.setJarByClass(CountryIncomeConf.class);

     Counter counter =
     job.getCounters().findCounter(COUNTERS.MISSING_FIELDS_RECORD_COUNT);

     System.out.println("Error Counter = " + counter.getValue());

    // Setup MapReduce
    job.setMapperClass(CountryIncomeMapper.class);
    job.setNumReduceTasks(1);

    // Specify key / value
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(DoubleWritable.class);

    // Input
    FileInputFormat.addInputPath(job, inputPath);
    job.setInputFormatClass(TextInputFormat.class);

    // Output
    FileOutputFormat.setOutputPath(job, outputDir);
    job.setOutputFormatClass(TextOutputFormat.class);

    // Delete output if exists
    FileSystem hdfs = FileSystem.get(conf);
    if (hdfs.exists(outputDir))
      hdfs.delete(outputDir, true);

    // Execute job
    int code = job.waitForCompletion(true) ? 0 : 1;
    System.exit(code);

  }

}

A: Looks like you're trying to get the counter before you submitted the job.

A: I had the same error at the time of an sqoop export.
The error was generated because the hdfs directory was empty.
Once I populated the directory (corresponding to a hive table), the sqoop ran without problems.


Q: MS Access SQL Query to Concatenate or Consolidate Related Fields If I had the following MS Access table and sample data,
Status tbl
UpdateID PK
CustomerNo text
StatusType text
UpdateDate date
UpdateID, CustomerNo, StatusType, UpdateDate
001, 0099, Open, 2011-01-01
002, 0099, Pend, 2011-01-02
003, 0100, Open, 2011-01-03
004, 0099, Appr, 2011-01-04
005, 0100, Pend, 2011-01-05
006, 0099, Clsd, 2011-01-07
then how could I write a query that would result in the following consolidated/concatenated output?
CustomerNo, UpdateDate
0099, 2011-01-01;2011-01-02;2011-01-04;2011-01-07
0100, 2011-01-03;2011-01-05

A: There is no convenient way to do this in Access without using code to iterate over the returned rows and build the string yourself.
Here is some code that will help you do this:
Public Function ListOf(sSQL As String, Optional sSeparator As String = ", ") As String

  Dim sResults As String
  Dim rs As DAO.Recordset

  Set rs = CurrentDb.OpenRecordset(sSQL)

  While Not rs.EOF

    If sResults = "" Then
      sResults = Nz(rs.Fields(0).Value, "???")
    Else
      sResults = sResults + sSeparator & Nz(rs.Fields(0).Value, "???")
    End If

    rs.MoveNext

  Wend

  ListOf = sResults

End Function

And here is how you can use it in an Access query:
 SELECT [CustomerNo],
 (ListOf('SELECT [UpdateDate] FROM StatusTbl WHERE CustomerNo = ' + CStr([CustomerNo]))) AS UpdateDates
 FROM StatusTbl

Note that this only works if you're executing the query in Access, queries executed from (for instance) an ADO connection will not have access to the ListOf function.

A: This comes up fairly often, here is a previous take: Combine rows / concatenate rows


Q: ruby on rails new project gemfile error I recently installed and created a new project, I followed rails tutorial (http://guides.rubyonrails.org/getting_started.html) and everything was ok.
Now, when I tried to create a new project and start the server I get this:
=> Booting WEBrick
=> Rails 4.0.0 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2013-09-09 15:28:55] INFO  WEBrick 1.3.1
[2013-09-09 15:28:55] INFO  ruby 2.0.0 (2013-06-27) [x64-mingw32]
[2013-09-09 15:28:55] INFO  WEBrick::HTTPServer#start: pid=12064 port=3000

Started GET "/" for 127.0.0.1 at 2013-09-09 15:28:56 +0100

Gem::LoadError (Specified 'sqlite3' for database adapter, but the gem is not loa
ded. Add `gem 'sqlite3'` to your Gemfile.):
  activerecord (4.0.0) lib/active_record/connection_adapters/connection_specific
ation.rb:58:in `rescue in resolve_hash_connection'
  activerecord (4.0.0) lib/active_record/connection_adapters/connection_specific
ation.rb:55:in `resolve_hash_connection'
  activerecord (4.0.0) lib/active_record/connection_adapters/connection_specific
ation.rb:46:in `resolve_string_connection'
  activerecord (4.0.0) lib/active_record/connection_adapters/connection_specific
ation.rb:30:in `spec'
  activerecord (4.0.0) lib/active_record/connection_handling.rb:39:in `establish
_connection'
  activerecord (4.0.0) lib/active_record/railtie.rb:175:in `block (2 levels) in
<class:Railtie>'
  activesupport (4.0.0) lib/active_support/lazy_load_hooks.rb:38:in `instance_ev
al'
  activesupport (4.0.0) lib/active_support/lazy_load_hooks.rb:38:in `execute_hoo
k'
  activesupport (4.0.0) lib/active_support/lazy_load_hooks.rb:45:in `block in ru
n_load_hooks'
  activesupport (4.0.0) lib/active_support/lazy_load_hooks.rb:44:in `each'
  activesupport (4.0.0) lib/active_support/lazy_load_hooks.rb:44:in `run_load_ho
oks'
  activerecord (4.0.0) lib/active_record/base.rb:322:in `<module:ActiveRecord>'
  activerecord (4.0.0) lib/active_record/base.rb:22:in `<top (required)>'
  activerecord (4.0.0) lib/active_record/query_cache.rb:50:in `restore_query_cac
he_settings'
  activerecord (4.0.0) lib/active_record/query_cache.rb:43:in `rescue in call'
  activerecord (4.0.0) lib/active_record/query_cache.rb:32:in `call'
  activerecord (4.0.0) lib/active_record/connection_adapters/abstract/connection
_pool.rb:626:in `call'
  activerecord (4.0.0) lib/active_record/migration.rb:369:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/callbacks.rb:29:in `block in
 call'
  activesupport (4.0.0) lib/active_support/callbacks.rb:373:in `_run__342058401_
_call__callbacks'
  activesupport (4.0.0) lib/active_support/callbacks.rb:80:in `run_callbacks'
  actionpack (4.0.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/reloader.rb:64:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `c
all'
  actionpack (4.0.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `ca
ll'
  railties (4.0.0) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.0.0) lib/rails/rack/logger.rb:21:in `block in call'
  activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `block in tag
ged'
  activesupport (4.0.0) lib/active_support/tagged_logging.rb:25:in `tagged'
  activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `tagged'
  railties (4.0.0) lib/rails/rack/logger.rb:21:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.0.0) lib/active_support/cache/strategy/local_cache.rb:83:in `
call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/static.rb:64:in `call'
  railties (4.0.0) lib/rails/engine.rb:511:in `call'
  railties (4.0.0) lib/rails/application.rb:97:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
  C:/Ruby200-x64/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
  C:/Ruby200-x64/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
  C:/Ruby200-x64/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'

  Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_d
ispatch/middleware/templates/rescues/_source.erb (2.0ms)
  Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_d
ispatch/middleware/templates/rescues/_trace.erb (2.0ms)
  Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_d
ispatch/middleware/templates/rescues/_request_and_response.erb (2.0ms)
  Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.0/lib/action_d
ispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (122.
1ms)

When I open a browser window I get
Gem::LoadError
Specified 'sqlite3' for database adapter, but the gem is not loaded. Add gem 'sqlite3' to your Gemfile.
What can I do to fix this?

A: According to the error, you need to add sqlite3 gem to your Gemfile (it's just a plain text file that should be on your Redmine root folder). Edit it and add something like.-
gem 'sqlite3'

You may also find this thread useful.-
Ruby on Rails - "Add 'gem sqlite3'' to your Gemfile"


Q: What is the GET function on AWS S3 Are Get functions read-only? like if a  GetObject, GetBucketPolicy or GetBucketLogging event is executed on an s3 then does that mean the user only read the information
Thanks!

A: Yes that is a standard practice. While building any REST API;  ( just like when we create beans and implement getter and setter methods ) get api are for "select" while set api are for update/delete.. Similarly you have PutObject also to update an object onto S3


Q: Minimum code coverage threshold in Jacoco Gradle on the whole project level(not on the module level) Our project is using Gradle 3.5, jacoco 0.8.1
It has 3 modules -- module-A, module-B and module-C, and its code coverage is 50%, 6% and 42% separately, and the code coverage for the whole project is 38%.
Now we want to use the current code coverage for the whole project as the threshold, that means if the code coverage of the whole project is less than 38%, the build will fail.
I tried the solution in
Minimum code coverage threshold in Jacoco Gradle
jacocoTestCoverageVerification {
violationRules {
    rule {
        limit {
            minimum = 0.38
        }
    }
}

but failed, it hints that module-B violates the rules, instruction covered ratio is 0.06, but expect is 0.38, seems it only suits for the module level, not the whole project level.
Also I tried to use element = 'GROUP', but seems no effect.
(https://www.eclemma.org/jacoco/trunk/doc/api/org/jacoco/core/analysis/ICoverageNode.ElementType.html)
Anyone knows how to set the minimum code coverage threshold for the whole project and not for the module level?
thanks,

A: I suggest having a separate project (module) within your multi-module build for reporting on the whole project. You might need the JacocoMerge task too. Let's assume a, b and c are java projects. Eg
Eg:
def javaProjects = [':a', ':b', ':c']
javaProjects.each {
   project(it) {
      apply plugin: 'java'
      apply plugin: 'jacoco'
   }
}
project(':report') {
    FileCollection execData = files(javaProjects.collect { project(it).tasks.withType(Test).jacoco.destinationFile })
    FileCollection sourceDirs = files(javaProjects.collect { project(it).sourceSets.main.java.srcDirs })
    FileCollection classDirs = files(javaProjects.collect { project(it).sourceSets.main.java.output.classesDirs })
    def testTasks = javaProjects.collect { project(it).tasks.withType(Test)}

   task jacocoMerge(type: JacocoMerge) {
      dependsOn testTasks
      executionData execData
      jacocoClasspath = classDirs
   }
   task coverageVerification(type: JacocoCoverageVerification) {
      dependsOn jacocoMerge
      executionData jacocoMerge.destinationFile
      sourceDirectories srcDirs
      classDirectories classDirs
      violationRules.rule.limit.minimum = 0.38
   }
   task jacocoReport(type: JacocoReport) {
      dependsOn jacocoMerge
      executionData jacocoMerge.destinationFile
      sourceDirectories srcDirs
      classDirectories classDirs
   }
}

A: Yes, I find another solution for it, that is  to write limit rule in each module, such as for module-A, its code coverage is 50%, so in the build.gradle file in module-A, the rule is as following:
// for moudle-A module
jacocoTestCoverageVerification {
violationRules {
    rule {
        limit {
            minimum = 0.5
        }
    }
}


Q: Date and Json in type definition for graphql Is it possible to have a define a field as Date or JSON in my graphql schema ?
type Individual {
    id: Int
    name: String
    birthDate: Date
    token: JSON
}

actually the server is returning me an error saying :
Type "Date" not found in document.
at ASTDefinitionBuilder._resolveType (****node_modules\graphql\utilities\buildASTSchema.js:134:11)

And same error for JSON...
Any idea ?

A: Have a look at custom scalars: https://www.apollographql.com/docs/graphql-tools/scalars.html
create a new scalar in your schema:
scalar Date

type MyType {
    created: Date
}

and create a new resolver:
import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';

const resolverMap = {
    Date: new GraphQLScalarType({
        name: 'Date',
        description: 'Date custom scalar type',
        parseValue(value) {
            return new Date(value); // value from the client
        },
        serialize(value) {
            return value.getTime(); // value sent to the client
        },
        parseLiteral(ast) {
            if (ast.kind === Kind.INT) {
            return parseInt(ast.value, 10); // ast value is always in string format
            }
            return null;
        },
    })
};

A: Primitive scalar types in GraphQL are Int, Float, String, Boolean and ID. For JSON and Date you need to define your own custom scalar types, the documentation is pretty clear on how to do this.
In your schema you have to add:
scalar Date

type MyType {
   created: Date
}

Then, in your code you have to add the type implementation:
import { GraphQLScalarType } from 'graphql';

const dateScalar = new GraphQLScalarType({
  name: 'Date',
  parseValue(value) {
    return new Date(value);
  },
  serialize(value) {
    return value.toISOString();
  },
})

Finally, you have to include this custom scalar type in your resolvers:
const server = new ApolloServer({
  typeDefs,
  resolvers: {
    Date: dateScalar,
    // Remaining resolvers..
  },
});

This Date implementation will parse any string accepted by the Date constructor, and will return the date as a string in ISO format.
For JSON you might use graphql-type-json and import it as shown here.


Q: Spring Boot 2.1.0 Web app and Java 11 fail to maven clean install The following web app fail to maven clean install: https://github.com/cassiusvm/sfg-pet-clinic
The error is below:
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/cassius/git/sfg-pet-clinic/pet-clinic-web/src/main/java/guru/springframework/sfgpetclinic/controllers/PetController.java:[3,47] package guru.springframework.sfgpetclinic.model does not exist

The following web app don't fail to maven clean install: https://github.com/cassiusvm/spring5-recipe-app
On Eclipse IDE 2018-09, both are successfully constructed and they run fine.
Both use Spring Boot 2.1.0 and Java 11.
How to maven install the sfg-pet-clinic web app with success, please ?

A: Solved it.
I did include id repackage to plugin spring-boot-maven-plugin on module pet-clinic-data.
I did include the dependency mockito-core to plugin wro4j-maven-plugin on module pet-clinic-web.

A: I'm on the same project pet-clinic-web, and for me was enough to add the dependency mockito-core to wro4j-maven-plugin.
Though when the project was on jdk 8 I didn't have this problem. The problem started when I update to jdk 11.


Q: unable to find matching constructor for: java.time.ZonedDateTime() i have a very simple code base and i feel really silly here. Why am i getting the error groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.time.ZonedDateTime()
import org.testng.annotations.Test
import java.time.ZonedDateTime
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
class timeTests {
    Logger log = LogManager.getLogger(this.class.getName())
    def startTime(){
        return new ZonedDateTime().now()
    }
    def endTime(){
        def start = startTime()
        def end = start.plusSeconds(5)
        return end
    }
    @Test
    void test(){
        log.info(endTime())
    }
}

example taken from: https://www.geeksforgeeks.org/zoneddatetime-now-method-in-java-with-examples/

A: The constructor does not exist. Use ZonedDateTime.now() or one of the equivalents. See the relevant JavaDoc.


Q: Querystring for Paypal I am making the following get request to Paypal Sandbox. But it says some problem with merchant account.
Is there any way that i can see what i am sending wrong? Here is the request URL
https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_cart&business=raheel.exile@gmail.com&invoice=1949&currency_code=USD&item_name=localhost&item_number=1&quantity=1&amount=100.00&return=http://localhost/drupal/user/register&cancel_return=http://localhost/drupal/paypal/cancel

A: You are missing one of the variables:
The string should be :
https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_cart&business=raheel.exile@gmail.com&invoice=1949&currency_code=USD&item_name=localhost&item_number=1&quantity=1&amount=100.00&return=http://localhost/drupal/user/register&cancel_return=http://localhost/drupal/paypal/cancel&add=1
add=1 is missing
Check the variables associated with cart command here


Q: using blocks that returns and takes a parameter So in AFNetworking there is a function as follows:
+ (AFImageRequestOperation *)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                         imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock
                                                    cacheName:(NSString *)cacheNameOrNil
                                                      success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
                                                      failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure
{

I am trying to use it as follows:
 [AFImageRequestOperation imageRequestOperationWithRequest:nil imageProcessingBlock:^UIImage * (UIImage *) {

        }cacheName:@"nsurl" success:^(NSURLRequest *request, NSHTTPURLResponse * response, UIImage * image){

        }failure:^(NSURLRequest *request, NSHTTPURLResponse * response, NSError * error){

        }];

However it doesn't seem to be correct in the UIImage part.. any ideas?

A: You are almost there - your code was missing a parameter name for the image in the first block:
[AFImageRequestOperation imageRequestOperationWithRequest:nil imageProcessingBlock:^UIImage * (UIImage *image) { // <<== HERE

} cacheName:@"nsurl" success:^(NSURLRequest *request, NSHTTPURLResponse * response, UIImage * image){

}failure:^(NSURLRequest *request, NSHTTPURLResponse * response, NSError * error){

}];

I think this is a bug in Xcode, because it expanded the signature into precisely what you posted, without the parameter name.