text:
Q: Debugging mode for Qt GUI application I would like to add a debugging mode for Qt GUI application. In debugging mode, any GUI widget events would dump out debug information rather than doing the original functionality. For example, clicking button A would print out the checkbox options being selected, where button A's original function is process something to the selected options.
I was thinking to add a menu option "debug mode", or a secret keyboard shortcut to enable it. And in the callback functions associated with widget signals (clicked/ textEdited), use if(isDebugMode)/else to distinguish regular function mode code.
Is this a good model to test GUI functionality? Is there any better way?

A: You might want to use the Signal/Slot system for your debugging. It reminds me of aspect-oriented programming.

*

*Write a Debug class derived from QObject that holds several slots with the typical signatures.

*In these slots, use the QObject::sender() function to retrieve the originator of the event

*Connect all signals to the debug slots additionally to their original receivers. Do this in code blocks that are run on condition of your debug mode flag.

*Connect additional signals from the Qt objects to allow you follow the state of the application. E.g. if a button reads a checkbox option, also connect the change signals from the checkboxes to your debug slots so you can read their state from previous output when the button is clicked.

*(If you don't want original action to be performed, simply make the connection of signals equally conditioned on the debug flag, this time in reverse.)

This will help you in keeping most of your code clean of the debug stuff.
For an inspiration, here is some example code that tracks focus changes within the application:
debug.hpp
class Debug : public QObject
{
    Q_OBJECT
    ...
    // method for debugging focus
    void focusChange(QWidget * old, QWidget * now);
};

debug.cpp
void Debug::focusChange(QWidget *old, QWidget *now)
{
    if (!old || !now)
        return;
    std::cerr << "Focus changed from " << old->objectName().toStdString()
              << " to " << now->objectName().toStdString() << std::endl;
}

main.cpp
QApplication app(argc, argv);
Debug dbg;
...
app.connect(&app, SIGNAL(focusChanged(QWidget*, QWidget*)),
            &debug, SLOT(focusChange(QWidget*, QWidget*)));
// run Qt event loop
return app.exec();


text:
Q: Pause loading elements until previous one finishes in list view I am new to Flutter and am trying to make an app with an infinite list view that loads images from the network using a Future builder for each image. The problem is that the list view loads a lot of future builders at once and this creates a lot of lag on slower devices. So, is there ant way to pause the rendering and add the new Future builder only when the build function of the previous one has returned?
Edit:
Async/Await on builder function does not work and results in the following error.
(the code works fine without the "async" in the builder method of FutureBuilder)
The code:
import "package:flutter/material.dart";
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:gallery_saver/gallery_saver.dart';

void main() => runApp(MyyApp());

class MyyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Cats!",
      theme: ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: Catshomepage(title: "Cats!"),
    );
  }
}

class Catshomepage extends StatefulWidget {
  final String title;

  Catshomepage({Key key, this.title}) : super(key: key);

  @override
  _CatshomepageState createState() => _CatshomepageState();
}

class _CatshomepageState extends State<Catshomepage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  fetchAlbum() async {
    var rresponse = http.get('https://api.thecatapi.com/v1/images/search');

    var joon;
    Map<String, dynamic> jsonoutput;

    await rresponse
        .then(
            (value) => {joon = value.body.substring(1, value.body.length - 1)})
        .then((value) {
      jsonoutput = jsonDecode(joon);
    });

    var finalval = jsonoutput['url'];

    url = finalval;

    // setState(() {});

    return finalval;
  }

  savephoto(inpurl) {
    if (inpurl.isNotEmpty) {
      GallerySaver.saveImage(inpurl, albumName: 'Media').then((value) {
        _scaffoldKey.currentState.showSnackBar(SnackBar(
          content: Text("Image Saved!"),
          duration: Duration(seconds: 3),
        ));
      }).catchError((error) {
        _scaffoldKey.currentState.showSnackBar(SnackBar(
          content: Text("Error! Can not save image."),
          duration: Duration(seconds: 3),
        ));
      });
    }
  }

  var url;

  @override
  Widget build(BuildContext context) {
    var futureing;
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: ListView.builder(
          padding: EdgeInsets.all(10),
          itemBuilder: (BuildContext context, int index) {
            futureing = fetchAlbum();
            return Padding(
              padding: EdgeInsets.all(10),
              child: imgrenderer(futureing, _scaffoldKey, savephoto),
            );
          },
        ),
      ),
    );
  }
}

Widget imgrenderer(incomingfuture, scaffolddkeyinp, savephoto) {
  return Center(
    child: Stack(
      children: <Widget>[
        FutureBuilder(
          future: incomingfuture,
          builder: (context, snapshot) async {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                scaffolddkeyinp.currentState.showSnackBar(SnackBar(
                  content: Text("Error!"),
                  duration: Duration(seconds: 3),
                ));
              } else {
                return Stack(
                  children: <Widget>[
                    SingleChildScrollView(
                      child: GestureDetector(
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(100),
                          child: Image.network(
                            snapshot.data,
                            loadingBuilder: (BuildContext context, Widget child,
                                ImageChunkEvent loadingProgress) {
                              if (loadingProgress == null) return child;
                              return Center(
                                child: SizedBox(
                                  child: CircularProgressIndicator(
                                    backgroundColor: Colors.deepOrange,
                                  ),
                                  height: 100,
                                  width: 100,
                                ),
                              );
                            },
                            // "https://source.unsplash.com/random/800x3000",
                          ),
                        ),
                        onTap: () {
                          // setState(() {});
                        },
                      ),
                      // shrinkWrap: true,
                      scrollDirection: Axis.vertical,
                    ),
                    FloatingActionButton(
                      child: Icon(
                        Icons.favorite,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        savephoto(snapshot.data);
                      },
                    ),
                  ],
                );
              }
            }
            return SizedBox(
              child: CircularProgressIndicator(),
              height: 100,
              width: 100,
            );
          },
        ),
      ],
    ),
  );
}

The error:
Compiler message:
lib/main.dart:103:20: Error: The argument type 'Future<RenderObjectWidget> Function(BuildContext, AsyncSnapshot<dynamic>)' can't be assigned to the parameter type 'Widget Function(BuildContext, AsyncSnapshot<dynamic>)'.
 - 'Future' is from 'dart:async'.
 - 'RenderObjectWidget' is from 'package:flutter/src/widgets/framework.dart' ('../../../FFlutter/flutterr_files/flutter/packages/flutter/lib/src/widgets/framework.dart').
 - 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('../../../FFlutter/flutterr_files/flutter/packages/flutter/lib/src/widgets/framework.dart').
 - 'AsyncSnapshot' is from 'package:flutter/src/widgets/async.dart' ('../../../FFlutter/flutterr_files/flutter/packages/flutter/lib/src/widgets/async.dart').
 - 'Widget' is from 'package:flutter/src/widgets/framework.dart' ('../../../FFlutter/flutterr_files/flutter/packages/flutter/lib/src/widgets/framework.dart').
          builder: (context, snapshot) async {

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redirect unless current_user owns object - Rails I have a canvas model and a user model. I only want users to be able to view the canvases edit action if they own the canvas.
So if the user visits the canvases edit action, I want to redirect them to the canvas show action unless they own the canvas.
So far I have this in my canvas controller edit action:
unless @canvas.user_id = current_user.id
  redirect_to @canvas
end

It doesn't seem to have any effect though. Should I be using a before_filter?

A: = is assignment. == is equality.  It's always important to know which one to use when.


text:
Q: How to take thumb impression in android
Possible Duplicate:
Does iphone provide any API to detect human thumb Impression?
Is fingerprint supported in android devices?

every one.
i want to take thumb impression in my android phone by using pressing on mobile screen.
is there any API for thumb impression.?

A: Thumb impressions used to scan for fingerprints require specialized devices/components that are not part of standard android cell phone screens.
Hence, there is no API and this functionality is not supported by android at this time.


text:
Q: Why do correlations matter in simulating data to compare classifiers when p >> N? In genomics and computational biology, expression data sets contain a much larger number of features (p) than the number of observations (N). I wanted to simulate data where p>>N to compare the performance of classifier methods (e.g., regularized methods, automatic feature selection methods, and filtering/feature selection before applying any methods). In hopes of mimicking gene expression data, the informative genes were sampled from the Asymmetric Laplace Distribution (ALD) (Purdom, Holmes, 2005, suggested that gene expression data follows the ALD better than the normal distribution) and the uninformative/noisy genes were sampled from the standard normal distribution. For case 1, with n = 100 and p = 1000, 300 informative genes were sampled from X ~ ALD(-3, 0.5, 1) for class 1 and from Y ~ ALD(3, 2, 1) for class 2, and 700 uninformative/noisy genes were sampled from e ~ N(0,1). Then, 5% of the informative gene expression were transformed into outliers by increasing the scale parameter from 1 to 10. Finally, the samples (rows) were shuffled. We have E(X) = -1.93934, E(Y) = 1.93934, and Var(X) = Var(Y) = 4.761039. Here are the density curves:

The red line (left pointy hat) is X, the blue line (right pointy hat) is Y, the black line is e, the orange line is X transformed into outliers, and the green line is Y transformed into outliers.
After talking to a professor about this, she suggested that I add in correlations within the features because since I am sampling independently each time, my covariance matrix for the features is the identity matrix. She suggested transforming my covariance matrix to be rho^|i-j|, where 0
My questions are:

*

*Why is it better to have the covariance matrix to be rho^|i-j| for simulation? Is that more realistic in gene expression data? Is there a specific reason why it's not all just rho in the off diagonal and 1's in the diagonal?

*If I have the first 300 features to be informative and the 301th-1000th features to be noninformative (~N(0,1)), would I only add in correlations to the first 300 features? If so, would I have the covariance matrix to be {rho^|i-j| for 1 < i,j <300 if i does not equal to j, and 0 for i, j > 300 and i does not equal to j}?
This suggestion might have been related to when I told her that my CART result revealed only one different feature in R...


text:
Q: Why can I replace a new fragment but not a initialized fragment? This is my custom Fragment:
Interface:
public interface NotVerifiedWifiCardFragment{
    void loadSSIDName(String ssid);

    void setArguments(Bundle bundle);
}

Class:
public class NotVerifiedWifiCardFragmentImpl extends Fragment implements NotVerifiedWifiCardFragment {

    private TextView ssid;
    private View view;

    //@Inject
    //NotVerifiedWifiCardPresenter presenter;

    @Override
    public void setArguments(Bundle args) {
        super.setArguments(args);
    }

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

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_card_connected_not_verified, null);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        ssid = (TextView) view.findViewById(R.id.card_not_verified_wifi_ssid);

        Bundle bundle = getArguments();
        ssid.setText(bundle.getString("SSID"));
        //presenter.setView(this);
    }

    @Override
    public void loadSSIDName(String ssid) {
        this.ssid.setText(ssid);
    }
}

When I replace a new CustomFragment with FragmentTransaction I can do it without any problem:
@Override
    public void showNotVerifiedWifiCard(String ssid) {
        // Begin the transaction
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        // Replace the contents of the container with the new fragment
        ft.setCustomAnimations(R.anim.slide_up_anim, R.anim.slide_down_anim);
        ft.replace(R.id.main_small_card, new NotVerifiedWifiCardFragmentImpl());

        // or ft.add(R.id.your_placeholder, new FooFragment());
        // Complete the changes added above
        ft.commit();
    }

But when I try to call the Fragment Transaction with the same fragment but initialized (to pass a Bundle), replace method doesn't allow me. How do you solve it when you need to pass a bundle with data?
@Override
    public void showNotVerifiedWifiCard(String ssid) {
        Bundle bundle = new Bundle();
        bundle.putString("SSID", ssid);

        NotVerifiedWifiCardFragment fm = new NotVerifiedWifiCardFragmentImpl();
        fm.setArguments(bundle);

        // Begin the transaction
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        // Replace the contents of the container with the new fragment
        ft.setCustomAnimations(R.anim.slide_up_anim, R.anim.slide_down_anim);
        ft.replace(R.id.main_small_card, fm);

        // or ft.add(R.id.your_placeholder, new FooFragment());
        // Complete the changes added above
        ft.commit();
    }

Probably it is a silly object oriented concexpt misunderstood.
EDIT: Error show is:
Error: Wrong 2nd argument type. Found:'com.blabla.NotVerifiedWifiCardFragment', required: 'android.support.v4.app.Fragment'

A: If i understood your question correctly, you can try to use
public static Fragment instantiate(Context context, String fname, @Nullable Bundle args)
like this :
NotVerifiedWifiCardFragment fm = (NotVerifiedWifiCardFragment) Fragment.instantiate(context, "some_name", your_args);

A: Since not any object implementing the NotVerifiedWifiCardFragment is actually a fragment (you can declare any object class and make it implement this protocol), you can't treat NotVerifiedWifiCardFragment as a Fragment (the name you gave the interface is mistaking).
For example:
class Test implements NotVerifiedWifiCardFragment {
void loadSSIDName(String ssid){}

void setArguments(Bundle bundle){}
....
}

Test is just a simple class, not a fragment.
A quick solution would be replacing
NotVerifiedWifiCardFragment fm = new NotVerifiedWifiCardFragmentImpl();

with
NotVerifiedWifiCardFragmentImpl fm = new NotVerifiedWifiCardFragmentImpl()

What you really want in that case is to create an abstract Fragment class called NotVerifiedWifiCardFragment and make other fragments extend it.
Example code
abstract class NotVerifiedWifiCardFragment extends Fragment {
     abstract void loadSSIDName(String ssid);
     abstract void setArguments(Bundle bundle);
}


text:
Q: Button inside UITableCell - passing data to selector This subject is all over the stackoverflow but I couldn't find a fitting solution.
I have button on each UITableViewCell.
Here is how I create the cell.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExaminationCell"];
    UIButton *clipButton = (UIButton *)[cell viewWithTag:3];

    MedicalExamination *examination = [objects objectAtIndex:indexPath.row];

    [clipButton addTarget:self action:@selector(examinatonClicked:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

Here is the method thah should handle the button click:
-(void)examinatonClicked:(MedicalExamination*)examination
{

}

How do I pass examination object to examinatonCommentsClicked method? Obviously the object is different for each cell...

A: A somewhat hacky thing that I'll do, is I'll use the UIButton's tag attribute to pass the row number so I can pull the object from the array that's backing my table.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExaminationCell"];
    UIButton *clipButton = (UIButton *)[cell viewWithTag:3];
    clipButton.tag = indexPath.row //Set the UIButton's tag to the row.

    MedicalExamination *examination = [objects objectAtIndex:indexPath.row];

    [clipButton addTarget:self action:@selector(examinatonClicked:) forControlEvents:UIControlEventTouchUpInside];

    return cell;
}

-(void)examinatonClicked: (id)sender
{
     int row = ((UIButton *)sender).tag;
     MedicalExamination *examination = [objects objectAtIndex: row];
     //Profit!
}

A: I think you have to add button in uitableviewCell through xib(custum cell) and then connect it through iboutlet.


text:
Q: Set php.ini directives for each site I have multiple sites running on Apache2 and PHP on Ubuntu Server. I know PHP has a php.ini file that lets you set values for upload_max_filesize, max_file_uploads , upload_tmp_dir etc. But that applies one value to all sites.
How can set directives for each site? For Eg: I'd like to set upload_max_filesize to 50M for sitea.com and upload_max_filesize to 5M for siteb.com.
Similarly, I'd like to set unique a session.name for each sites. How can this be done? I read there's something called PHP_INI_USER, PHP_INI_PERDIR, PHP_INI_SYSTEM, PHP_INI_ALL, so how can I do this?

A: You can use .htaccess files per site (or even per-folder) to set PHP  configuration values - at least for most settings: if you look in the configuration directives documentation, for every setting that is marked as either PHP_INI_PERDIR or PHP_INI_ALL you can set these in a .htaccess file using the php_value or php_flag commands as documented in PHP's "How to change configuration settings" document.
For example to set upload_max_filesize in a website, create a .htaccess file at the document root of that website and put in it the text:
php_value upload_max_filesize 24M

Unfortunately, max_file_uploads and upload_tmp_dir are settings marked as PHP_INI_SYSTEM and you cannot change them in a .htaccess file...

A:
How can set directives for each site? For Eg: I'd like to set upload_max_filesize to 50M for sitea.com and upload_max_filesize to 5M for siteb.com.

The comment by Mike 'Pomax' Kamermans explicitly states how this should be done. However PHP manual documentation can be a little off-putting.
Also some clarifiers re the other answers here:

*

*Using a PHP parser file (as described by Lajos Arpad) adds some security risks and a pile of coding, syntax and some processing overhead that really isn't needed.

*.htaccess does work for setting custom ini directives for some PHP installations but if you're using "FastCGI" or "CGI" (and possibly suPHP) PHP installations then this will infact crash your website with a 500 error, so instead use a local .user.ini file as described here. How do I find out my SAPI?

*ONLY if you are running PHP as an Apache module (eg mod_php), use .htaccess. How do I find out my SAPI?
PHP suPHP/FastCGI/CGI SAPI
So, how should your aspiration be completed?
1) Look up the Core PHP.ini details.
Read your PHP.ini file for your current version of PHP.
Around line 180 (for PHP 8.1) it should say something like this:

;==================;
; php.ini Options  ;
;==================;
; Name for user-defined php.ini (.htaccess) files. Default is ".user.ini"
user_ini.filename = ".account-php81.ini"

Make a note of this value and I would suggest customising this value (as shown in this example). This value is the file name of the file which will sit in each unique account on the server, holding the account specific "local" settings for the global PHP.ini file.
The file typically sits in the public_html folder so should begin with a . so as to set as hidden by default (see more about this later on). If the file doesn't exist an an account no core PHP settings are changed.
2) Remember/Set the Filename and Create the New Rules
So you now know/ have set the name for your custom PHP file; now generate the file in your account and you can then set the PHP.ini settings you want to customise for this account alone.
For example;

file: /home/sitea.com_account/public_html/.account-php81.ini

Would contain the following example information:
;
; Some optional comment text here for human consumption
;
session.cookie_secure=1
session.save_path=/home/sitea.com_account/sessions
session.name=session-sitea
error_log=/home/sitea.com_account/errors/PHP_errors.log
upload_max_filesize=50M

This information is parsed by PHP and overwrites any corresponding values in the core PHP.ini but only for this account.
3) Customise for Each Account as Needed
For example, for your siteb.com php user ini file it would look more like this:

file: /home/siteb.com_account/public_html/.account-php81.ini

Would contain the following example information:
;
; Some optional comment text here for human consumption
;
session.cookie_secure=1
session.save_path=/home/siteb.com_account/session_b
session.name=site-b-UniqueSession
error_log=/home/siteb.com_account/errors/PHP_errors.log
upload_max_filesize=5M

You can then check that these account settings are set correctly by exploring phpinfo() on each account and noting the local and core differences as displayed.
4) Test And Confirm
The core user.ini file in the /public_html/ path should be all you need for every child file/folder on that account to process (This can sometimes depend on your exact LAMP server setup and your PHP handler).
As I say, once you've set a test ini file you should run phpinfo() to check its values are implemented.
If you don't want to use phpinfo() then you can just as easily use [ini_get](https://www.php.net/manual/en/function.ini-get) to dump sensitive data out to the error log rather than to the browser.
<?php
error_log("ini data for this account: ".ini_get('upload_max_filesize'));
exit;

5) Security
The user.ini file is typically started with a . character to hide it in the directory, but that doesn't make it untouchable by browser agents, therefore it's best practise to add a few lines to your .htaccess to deny access to this file.
<Files .account-php81.ini>
    Require all denied
</Files>

Some Final Thoughts:
Core PHP.ini values do change in new versions of PHP and so this is why it's best practise to have different local .ini files for different PHP versions (.account-php80.ini, .account-php81.ini, etc.). Note that each php.ini core will need to explicitly call their respective local user.ini file, as referenced in step 1 above.
The principles of the above are outlined in the PHP Manual and it must be noted:

If you are running PHP as Apache module, use .htaccess files for the same effect.

A: Your settings are in php.ini indeed. Yet, if you have multiple sites to set, then you can set values inside the .htaccess file in the root of the site folder.
However, you can create a json file somewhere on your server, let's assume it's at /path/settings.json of the format of:
{
    sitename1: {
        setting1: value1
        setting2: value2
    },
    sitename2: {
        setting1: value3
        setting2: value4
    }
}

Now, you can create a deploy.php file at all your sites that will run cat /path/settings.json via exec, like
if (exec('cat /path/settings/json', $output, $retval)) {
    $currentSettings = json_decode($output, true)['mysitename'];
}

You will then have an array of key-value pairs that can be looped and the setting will be known, like:
$script = "";
foreach ($currentSettings as $key => $value) {
    $script .= "ini_set('{$key}', '{$value}');\n";
}

and then save $script into a file, let's call it init.php for now. You require_once this file and then you can maintain a single json file and deploy it per site by running a single cli command. You can even create an sh file that runs all deployment commands so you will be able to deploy everything via a one-liner.


text:
Q: Logger is not working in play framework scala? Please find my application.conf and logback.xml
app {
  baseUrl = ""
  username = ""
  password = ""
  clientId = ""
}

logback.xml:
<!-- https://www.playframework.com/documentation/latest/SettingsLogger -->
<configuration>

  <conversionRule conversionWord="coloredLevel" converterClass="play.api.libs.logback.ColoredLevel" />

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>${application.home:-.}/logs/application.log</file>
    <encoder>
      <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%coloredLevel %logger{15} - %message%n%xException{10}</pattern>
    </encoder>
  </appender>

  <appender name="ASYNCFILE" class="ch.qos.logback.classic.AsyncAppender">
    <appender-ref ref="FILE" />
  </appender>

  <appender name="ASYNCSTDOUT" class="ch.qos.logback.classic.AsyncAppender">
    <appender-ref ref="STDOUT" />
  </appender>

  <logger name="play" level="INFO" />
  <logger name="application" level="INFO" />

  <!-- Off these ones as they are annoying, and anyway we manage configuration ourselves -->
  <logger name="com.avaje.ebean.config.PropertyMapLoader" level="OFF" />
  <logger name="com.avaje.ebeaninternal.server.core.XmlConfigLoader" level="OFF" />
  <logger name="com.avaje.ebeaninternal.server.lib.BackgroundThread" level="OFF" />
  <logger name="com.gargoylesoftware.htmlunit.javascript" level="OFF" />

  <root level="WARN">
    <appender-ref ref="ASYNCFILE" />
    <appender-ref ref="ASYNCSTDOUT" />
  </root>

</configuration>

I have used the library import.play.api.Logger and also used logger.info("test") in my code.But I am not getting any logs from my application?


text:
Q: How to embed an standard font into generated PDF with PDFBox I need to add some text to PDF/A files using the Apache PDFBox library for Java. The problem is that, because it needs to be a valid PDF/A file, all the used fonts must be embedded in it. I know that I can embed a TTF font using PDFBox, but I'd like to avoid having to provide a font file with the application, so I was wondering if there's a way to embed one of the standard fonts available in PDFBox as if it was external.
For example, when I write something using one of the standard fonts, the PDF validator complains about this:

I've used the following code to write the text:
  PDFont standardFont = PDType1Font.HELVETICA_BOLD;

  PDPage pag = new PDPage();

  pag.setResources(new PDResources());

  PDPageContentStream contentStream = new PDPageContentStream(pdfFile, pag);

  //Begin the Content stream
  contentStream.beginText();

  //Setting the font to the Content stream
  contentStream.setFont(standardFont, 12);

  //Setting the position for the line
  contentStream.newLineAtOffset(25, 500);

  //Adding text in the form of string
  contentStream.showText("JUST A SAMPLE STRING");

  //Ending the content stream
  contentStream.endText();

  //Closing the content stream
  contentStream.close();

  pdfFile.addPage(pag);

  pdfFile.save(file);

  pdfFile.close();

Is there any option to force the embed of the font when setting it?
Thanks in advance,

A: There is only one font embedded in PDFBox. You can use it this way:
PDFont font = PDType0Font.load(doc, SomePdfboxClass.class.getResourceAsStream(
                   "/org/apache/pdfbox/resources/ttf/LiberationSans-Regular.ttf"));


text:
Q: How would I read a line of user input with cin, split that line by white space, and store those tokens into an array of strings? Basically, yeah, everything as stated above. But I would like to do this without using the vector class.
Thanks in advance

A: Three steps:

*

*Read a line using getline(). Make sure you use the free function, not the member of istream.

*Determine the number of strings in the line. You could use a stringstream combined with istream_iterators and distance().

*Allocate an array of sufficient size and copy the input elements. You could again use a stringstream with istream_iterators and copy().

Alternatively to steps 2 & 3, you could also dynamically enlarge your array or use a maximum size. Note that I'm intentionally not telling you how to do all this in order not to spoil you the learning experience. If you have concrete code, you are welcome to ask more specific questions though.


text:
Q: How To Merge Two Sections Together In HTML/CSS? I need to merge two sections together from my website.I highlighted them in a red box.

as you can see above, the image shows clearly that the sections are separated by some space

#ABC {
  margin-top: 0;
  padding: 0%;
}

a:link {
  text-decoration: none;
}

a:visited {
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

a:active {
  text-decoration: none;
}

body {
  width: 50%;
  margin: auto;
  padding: zero;
  font-family: Arial;
  background-color: lightblue
}

nav {
  padding: 5px;
  color: mediumpurple;
}

header {
  background-image: linear-gradient(lightgray, wheat);
}

#Introduction {
  background-image: linear-gradient(wheat, white);
  padding: 0%;
}

#Numbers {
  background-image: linear-gradient(white, lime);
  padding: 0%;
}

    Visit page 2
    Visit page 3
    Youtube's home page

       Vlad Seboiu

<big>Introduction</big>

hello world

100002

 H2O

(-20)52(-40)95

test

    <big>
                    123
                </big>

A: The margin on your paragraphs is separating the two sections. You can view this is the case by opening dev tools with F12 and inspecting them. The coloured box that pops up shows your margins. A quick fix could be to add a class to the paragraphs in question:
.clear-margin {
  margin: 0;
}

#ABC {
  margin-top: 0;
  padding: 0%;
}

a:link {
  text-decoration: none;
}

a:visited {
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

a:active {
  text-decoration: none;
}

body {
  width: 50%;
  margin: auto;
  padding: zero;
  font-family: Arial;
  background-color: lightblue
}

nav {
  padding: 5px;
  color: mediumpurple;
}

header {
  background-image: linear-gradient(lightgray, wheat);
}

.clear-margin {
  margin: 0;
}

#Introduction {
  background-image: linear-gradient(wheat, white);
  padding: 0%;
}

#Numbers {
  background-image: linear-gradient(white, lime);
  padding: 0%;
}

    Visit page 2
    Visit page 3
    Youtube's home page

       Vlad Seboiu

<big>Introduction</big>

hello world

100002

 H2O

(-20)52(-40)95

test

    <big>
                    123
                </big>

A:
 has default margin.
Add this to your css
p{
    margin:0px;
 }

A: p tag has margin which is not merging two section
just do this:
 p {margin:0px;}

https://codepen.io/Aksshit/pen/dyqMWzd
check this for solution which I tried on codepen.
Tip: Always use Developer Tools to first know the problem.


text:
Q: TFS How to Build Visual Studio-based "Open Folder" CMake project I have an ARM-GCC project, which is configured and built using Visual Studio's native "Open folder..." CMake project support (introduced in VS2017).  All of our needed build settings are stored in CMakeSettings.json.
I would like to build this project using our TFS Continuous Integration server.
I've confirmed that our build server contains all of the prerequisites provided 'out of the box' by the Visual Studio 2017 installer - CMake, Ninja, and ARM-GCC compilers.  These tools are all installed to a 'standard' Visual Studio tooling location:

*

*C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake

*C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Linux\gcc_arm

*etc.

These tools 'just work' out of the box, when we open the project using Visual Studio's "File" -> "Open Folder..." approach.  Within TFS however, we can't seem to get the solution to build.  I've tried a few different approaches within the build definition...
Option 1: 'Visual Studio' task
This approach complains about a missing sln/proj file:

Specify a project or solution file. The current working directory does
  not contain a project or solution file.

There is no project or solution file, because it is an "Open Folder" project, with a CMakeSettings.json file, instead...
Option 2: 'MSBuild' Task
I have not found a set of command-line options capable of building a CMake project folder, using MSBuild.
Option 3: 'CMake' Task
When adding a CMake task to the build definition, the build server complains that it does not fulfill the auto-generated "cmake" ability prerequisite, despite the fact that Visual Studio has installed the cmake tool.
Has anyone successfully completed a TFS automated build of a Visual Studio-hosted "Open Folder..." CMake project?


text:
Q: Use the [Serializable] attribute or subclassing from MarshalByRefObject? I'd like to use an object across AppDomains.
For this I can use the [Serializeable] attribute:
[Serializable]
class MyClass
{
    public string GetSomeString() { return "someString" }
}

Or subclass from MarshalByRefObject:
class MyClass: MarshalByRefObject
{
    public string GetSomeString() { return "someString" }
}

In both cases I can use the class like this:
AppDomain appDomain = AppDomain.CreateDomain("AppDomain");
MyClass myObject = (MyClass)appDomain.CreateInstanceAndUnwrap(
                   typeof(MyClass).Assembly.FullName,
                   typeof(MyClass).FullName);
Console.WriteLine(myObject.GetSomeString());

Why do both approaches seem to have the same effect? What is the difference in both approaches? When should I favor the one approach over the other?
EDIT: At the surface I know that there are differences between both mechanisms, but if someone jumped out of a bush and asked me the question I couldn't give him a proper answer. The questions are quite open questions. I hoped that someone can explain it better than I could do.

A:
Why do both approaches have the same effect?

They do not have the same effect.
With MarshalByRefObject you are referencing one object across AppDomain boundaries. With [Serializable] a copy of the object is being made. This will show up if the state of the object is modified in the child domain and then examined again (or execute the Console.WriteLine inside the child AppDomain).

A: Using MarshallByRef will execute your methods in the remote AppDomain. When you use CreateInstanceAndUnwrap with a Serializable object, a copy of the object is made to the local AppDomain, so any method call will be executed in the local AppDomain.
If what you want is to communicate between AppDomains go with the MarshallByRef approach.
An example:
using System;
using System.Reflection;

[Serializable]
public class SerializableClass
{
    public string WhatIsMyAppDomain()
    {
        return AppDomain.CurrentDomain.FriendlyName;
    }
}

public class MarshallByRefClass : MarshalByRefObject
{
    public string WhatIsMyAppDomain()
    {
        return AppDomain.CurrentDomain.FriendlyName;
    }
}

class Test
{

    static void Main(string[] args)
    {
        AppDomain ad = AppDomain.CreateDomain("OtherAppDomain");

        MarshallByRefClass marshall = (MarshallByRefClass)ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "MarshallByRefClass");
        SerializableClass serializable = (SerializableClass)ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "SerializableClass");

        Console.WriteLine(marshall.WhatIsMyAppDomain());
        Console.WriteLine(serializable.WhatIsMyAppDomain());

    }
}

This code will display "OtherAppDomain" when you call WhatIsMyAppDomain from the MarshallByRef object, and your default AppDomain name when you call from the Serializable object.

A: MarshalByRefValue and Serializable implement different semantics for remoting/cross AppDomain communication. MarshalByRefValue essentially gives you reference semantics through a proxy object, while Serializable gives you value semantics (i.e. the state of the object is copied).
In other words MarshalByRefValue will let you modify the instance across different AppDomains, while Serializable will not. The latter is useful when you just need to get the information from one AppDomain to another, e.g. to get the content of an exception from one AppDomain to another.

A: These approaches have dramatically different effects.
With the MarshalByRef version you are creating 1 instance of your object.  It will live in the newly created AppDomain.  All accesse to the object is done via a TransparentProxy.
With the Serializable version you are created 2 instances of your object.  One is created in the newly created AppDomain.  The CreateInstanceAndUnwrap call will then serialize this object and deserialize it in the original app domain.  This creates a second version of the object that is completely independent from the first. In fact, the very next GC will almost certainly eliminate the original object and you'll be left with one instance.


text:
Q: How does Vec::push work for self referencing types? Quoted from vec::push implementation:
pub fn push(&mut self, value: T) {
    // This will panic or abort if we would allocate > isize::MAX bytes
    // or if the length increment would overflow for zero-sized types.
    if self.len == self.buf.capacity() {
        self.buf.reserve_for_push(self.len);
    }
    unsafe {
        let end = self.as_mut_ptr().add(self.len);
        ptr::write(end, value);
        self.len += 1;
    }
}

Here if T is self referencing type, how is it guaranteed after ptr::write there's a valid object at end?

A: In Rust, all types are movable and thus must be valid after moving; ptr::write essentially just moves the value to a new location.
Self-referential objects can only work by hiding behind Pin to avoid being moved, which works because Pin requires indirection and avoids providing access to &mut T of the "unmovable" value. But the pin itself would still be movable, so passing one to .push() is not an issue.


text:
Q: Resolving ambiguous overload on function pointer and std::function for a lambda using + (unary plus) In the following code, the first call to foo is ambiguous, and therefore fails to compile.
The second, with the added + before the lambda, resolves to the function pointer overload.
#include <functional>

void foo(std::function<void()> f) { f(); }
void foo(void (*f)()) { f(); }

int main ()
{
    foo(  [](){} ); // ambiguous
    foo( +[](){} ); // not ambiguous (calls the function pointer overload)
}

What is the + notation doing here?

A: The + in the expression +[](){} is the unary + operator. It is defined as follows in
[expr.unary.op]/7:

The operand of the unary + operator shall have arithmetic, unscoped enumeration, or pointer type and the result is the value of the argument.

The lambda is not of arithmetic type etc., but it can be converted:
[expr.prim.lambda]/3

The type of the lambda-expression [...] is a unique, unnamed non-union class type — called the closure type — whose properties are described below.

[expr.prim.lambda]/6

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type's function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type's function call operator.

Therefore, the unary + forces the conversion to the function pointer type, which is for this lambda void (*)(). Therefore, the type of the expression +[](){} is this function pointer type void (*)().
The second overload void foo(void (*f)()) becomes an Exact Match in the ranking for overload resolution and is therefore chosen unambiguously (as the first overload is NOT an Exact Match).

The lambda [](){} can be converted to std::function<void()> via the non-explicit template ctor of std::function, which takes any type that fulfils the Callable and CopyConstructible requirements.
The lambda can also be converted to void (*)() via the conversion function of the closure type (see above).
Both are user-defined conversion sequences, and of the same rank. That's why overload resolution fails in the first example due to ambiguity.

According to Cassio Neri, backed up by an argument by Daniel Krügler, this unary + trick should be specified behaviour, i.e. you can rely on it (see discussion in the comments).
Still, I'd recommend using an explicit cast to the function pointer type if you want to avoid the ambiguity: you don't need to ask on SO what is does and why it works ;)


text:
Q: OutOfMemoryError building Apache Sling I get the following error running the maven build for Apache Sling, even with the recommended heap size:
main:
     [echo] **************** WARNING (SLING-443/SLING-1782) ******************************
     [echo] On most platforms, you'll get OutOfMemoryErrors when building unless you set
     [echo] on 32bit platforms: MAVEN_OPTS="-Xmx256M -XX:MaxPermSize=256M", see SLING-443
     [echo] on 64bit platforms: MAVEN_OPTS="-Xmx512M -XX:MaxPermSize=512M", see SLING-1782
     [echo] ******************************************************************************
[INFO] Executed tasks
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ sling-launchpad-webapp-archetype ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/thomasf/slingDownload/sling/maven/archetypes/launchpad-webapp/src/test/resources
[INFO] Copying 3 resources
[INFO]
[INFO] --- animal-sniffer-maven-plugin:1.7:check (default) @ sling-launchpad-webapp-archetype ---
[INFO] Checking unresolved references to org.codehaus.mojo.signature:java15:1.0
[ERROR] Java heap space -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/OutOfMemoryError

Sure enough my heap size is the same that they recommend on the project homepage:
echo $MAVEN_OPTS
-Xmx512M -XX:MaxPermSize=512m

I suspect that the cause is that maven is forking and the jvm in the child process does not have the same heap size - however I cannot identify which plugin is forking from the console output.
Any ideas appreciated !!! Thanks

A: You can try to just increase the memory:
MAVEN_OPTS=-Xmx1024M -XX:MaxPermSize=512m

or set it using JAVA_OPTS (but this affects any JVM process for the executing user!) so the child process will have these settings as well:
JAVA_OPTS=-Xmx512M -XX:MaxPermSize=512m

try to increase the memory with MAVEN_OPTS first.
regards
werner

A: Even if You use the JAVA_OPTS environment variable there is not enough memory? Since this affects any running vm a newly spawned process should have these settings too.
Or try using 1200M of memory? Maybee there is not much heap memory missing, if you run 64 bit JVM you may just need more... interesting question.
I would run the build using -X and maybe its a plugin / goal that executes prior to the heap error. Hopefully that plugin can be configured.

A: You can check in Environment Variables of your Computer, if MAVEN_OPTS variable is declared or not. If not Declare it as
MAVEN_OPTS=-Xmx1024M -XX:MaxPermSize=512m

else if, its already declared, just increase the Memory size.
This way it worked for me.


text:
Q: How do you localize your iPhone applications? I want to localize my iPhone applications into other languages except from English, but I don't know anyone who would speak Italian or French.
How do you translate your application name, description and application contents into other languages? Who may help in this issue? Are there any iPhone-oriented translation companies?
Thank you in advance.

A: There are lots of companies that do this.  From expensive ones that make little sense, to just a guy in the country you're interested in who knows english real well and would be happy with $20 and a thank you.  You could:

*

*Google for the more established services

*release your product and mention in your about page that you are looking for translation assistance from your users and hope they like your product enough that they contact you

*use a service like Amazon's Mechanical Turk to bid it out to an individual

A: I would start by building a framework that makes it easy to localize.  Ultimately, somebody is going to have to translate it, but you might want to start by removing any string literals from the actual application itself and replace them with references to some sort of data source.  I've never done it with iPhone, but this is common with multilingual web-apps where they have all string literals stored in a database and the fields are populated at runtime based on the location.  This makes it exceptionally easy to localize because, if all you are doing is reading an XML file, you only need to swap out the file.


text:
Q: Delete Login details in WebView I am looking to remove all cookies from a WebView (Using Xamarin.Android) however currently on some sites user login information is retained.
I am currently utilizing
CookieManager.Instance.RemoveAllCookies(null)
And this works for most sites however on Some SSO sites or if example you create a base ASP.NET web application and enable Windows Auth and deploy to IIS. When navigating to the created site via a WebView and logging in. When I close the WebView and re open (The above RemoveAll is called) but the user does not have to re enter creds.
I have tried other methods along with the above such as
WebStorage.Instance.DeleteAllData();
and ClearCache(true)
However nothing seems to be clearing them.
Does anyone have any ideas?
Thanks in advance.

A: First, you need to define an interface like this:
public interface IDeviceSpecificService
{
    void ClearCookies();
}

Then use the code like this in Xamarin.Forms:
DependencyService.Get<IDeviceSpecificService>().ClearCookies();

In the Xamarin.Android
 public class DeviceSpecificService : IDeviceSpecificService
    {
        public void ClearCookies()
        {
            Android.Webkit.CookieManager.Instance.RemoveAllCookie();
        }
    }

In the Xamarin.IOS
public class DeviceSpecificService : IDeviceSpecificService
    {
        public void ClearCookies()
        {
              NSHttpCookieStorage CookieStorage = NSHttpCookieStorage.SharedStorage;
              foreach (var cookie in CookieStorage.Cookies)
                      CookieStorage.DeleteCookie(cookie);
        }
    }


text:
Q: Is it possible to access piped variables without forkJoin or combineLatest? Is it possible to access previous pipe variables in RxJs appliances where forkJoin() or combineLatest() cannot be used, in my case due to value accumulation, without nesting pipes?
Or is a nested pipe with switchMap() in the following scenario even fine?
// this.incrementNavigation$ emits always 1
// this.decrementNavigation$ emits always -1

this.searchSuggestions$.pipe(
  // Can't use combineLatest() due to accumulation happening in scan()
  switchMap(search => {
    return merge(this.incrementNavigation$, this.decrementNavigation$).pipe( // Nesting begins...
      startWith(0),
      scan((acc: number, cur: number) => {
        if (acc+cur < 0) return search.length-1 // Need access to search variable
        if (acc+cur > search.length-1) return 0
        return acc+cur
      }),
    )
  })
).subscribe(pos => {
  this.searchNavigationPosition = pos
})


text:
Q: Remove text and lines on specific Rect in a PDF using ABCPdf I have an existing PDF which has couple of lines of text and horizontal line in the top of every page. like full file name, date time, and a horizontal line below that. The positions, height and width are same on all pages/pdf files.
I would like to remove those two lines of text and the horizontal line using ABCPdf.
Thanks

A: Instead of remove the text (what may not possible), consider place a "white rectangle" hidding it. Then you can "stamp" the doc for a better "cammouflage".
Something like that, for each page:
yourDoc.Rect.SetRect ( coordinates ...)
yourDoc.Color.String = "255 255 255"
yourDoc.FillRect()
...
yourDoc.Flatten etc.


text:
Q: setColumnOrder() on Grid in Vaadin Flow seems to cause the getSortOrder() list to increment infinitely in the event of the sort listener I believe I have found a bug in the Vaadin Grid that can be replicated with the code below.
I would like to save the grid's sorting order whenever it's changed and then restore it when the grid is loaded. The main issue is that the GridSortOrder list just keeps incrementing in size for the event in the sort listener rather than replacing the sortorder list. I believe this is a bug within Vaadin 14-20 because it only happens if I call setColumnOrder() in the reset method below (removing that call it works as expected). In other words calling setColumnOrder() seems to add the list of GridSortOrder to the event in the sort listener when it should be replacing it. This is actually also true if you do grid.getSortOrder() in the listener, meaning it's not just the event but also the grid that is compromised.
This can be replicated consistently with the code below. You will first need to change the sort order of Description column by clicking on the column header. Then just click on Reset button 5-10 times. Once this is done click on the Description column header to change the sort order one more time. The System.out for the listener will show a size of a list of 20 GridSortOrder instead of the expected 2 GridSortOrder. There will be replications of columns over and over.
Grid<Car> grid = new Grid<>();

grid.addColumn(Car::getName)
        .setSortable(true)
        .setComparator(Car::getName)
        .setKey("Name")
        .setHeader("Name");
grid.addColumn(Car::getPrice)
        .setSortable(true)
        .setComparator(Car::getPrice)
        .setKey("Price")
        .setHeader("Price");
grid.addColumn(Car::getDescription)
        .setSortable(true)
        .setComparator(Car::getDescription)
        .setKey("Description")
        .setHeader("Description");

grid.setItems(listOfCars);

grid.setColumnReorderingAllowed(true);
grid.setMultiSort(true);

grid.addSortListener(event -> {
    System.out.println("Event: " + event.getSortOrder().size() + " : " + event.isFromClient());
    System.out.println("Grid: " + grid.getSortOrder().size() + " : " + event.isFromClient());
});

defaultSort(grid);

Button resetButton = new Button("Reset", click -> {
    System.out.println("Reset: " + grid.getSortOrder().size());
    defaultSort(grid);
    grid.setColumnOrder(
            grid.getColumnByKey("Name"),
            grid.getColumnByKey("Price"),
            grid.getColumnByKey("Description"));
});

add(grid, resetButton);

private void defaultSort(Grid grid) {
    grid.sort(List.of(
            new GridSortOrder<>(grid.getColumnByKey("Name"), SortDirection.ASCENDING),
            new GridSortOrder<>(grid.getColumnByKey("Price"), SortDirection.ASCENDING)
    ));
}

If I remove grid.setColumnOrder() from the above then the List<GridSortOrder> works as expected and is two in the event listener. What's especially interesting is that event.getSortOrder().size() will increase by 2 every time the resetButton is clicked (but you'll only see it in the sort listener). It doesn't matter if the setColumnOrder() is before or after the call to defaultSort().
With that in mind if you debug grid.setColumnOrder() it seems to call updateClientSideSorterIndicators(sortOrder) which is what I believe is the cause and is where it's being added to the GridSortOrder list. That being said I'm not sure how to proceed from here so that I can reset the grid's setting when clicking on the Reset button.
FYI: This is an issue for me because I'm trying to save the state of the Grid to the database so that when the user reloads the screen (a very complex one) all their grid settings including the sorting order, the column order, and so on are preserved. However with this bug it's impossible to save the sorting order.
PS: This seems to be true in both Vaadin 14 and Vaadin 20.


text:
Q: Why does return inside finally gives empty dictionary? I want to keep a track of exceptions inside a dictionary and return the same. However when I do so, finally block gives me an empty dictionary. The logic pretty much works for scalars. Can someone explain the behavior please.
In scalar context:
def test():
    temp = 1
    try:
        raise ValueError("sdfs")
    except:
        temp = 2
    finally:
        temp = temp + 3
        return temp
test()
5

With dictionary:
def test():
    temp = dict()
    try:
        raise ValueError("something")
    except Exception as error:
        print("error is :{}".format(error))
        temp['except'] = "something" + error
    finally:
        return temp

test()
error is : something
{}

A: You caused another exception to be raised in the exception handler, which is swallowed because there is a finally handler that returns from the function.
You can't just concatenate an exception object and a string, so an additional TypeError is raised, and the assignment to the dictionary is never reached.
Converting the exception to a string first works:
>>> def test():
...     temp = dict()
...     try:
...         raise ValueError("something")
...     except Exception as error:
...         print("error is :{}".format(error))
...         temp['except'] = "something" + str(error)
...     finally:
...         return temp
...
>>> test()
error is :something
{'except': 'somethingsomething'}

From the try statement documentation:

If finally is present, it specifies a 'cleanup' handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return or break statement, the saved exception is discarded[.]

(Bold emphasis mine).

A: The line "something" + error raises an error which is discarded because you returned from finally. Due to the error the assignment to the dictionary temp is never performed giving the impression that nothing happens.
This is stated in the documentation for try-except:

If finally is present, it specifies a 'cleanup' handler. The try
  clause is executed, including any except and else clauses. If an
  exception occurs in any of the clauses and is not handled, the
  exception is temporarily saved. The finally clause is executed. If
  there is a saved exception it is re-raised at the end of the finally
  clause. If the finally clause raises another exception, the saved
  exception is set as the context of the new exception. If the finally
  clause executes a return or break statement, the saved exception is
  discarded.

(Emphasis mine)
Without an error (i.e temp['except'] = error you get the expected behavior:
>>> test()
error is :something
{'except': ValueError('something')}


text:
Q: Displaying output of php within jquery colorbox ... getting undefined index error I hope someone can help me, I have created a simple html form with drop down menu's, the drop down menus are populated from a mysql data base, the user must select from two drop downs and this will then display the data ( both selections make the sql query)
This all works correctly within the HTML however I am trying to jazz it up a bit and have the output display within a jquery colorbox (popup).
I am not sure how to format the syntax for the jquery function .. this is what I have so far

This correctly launches the colorbox pop up and fires the php "action" from my form but the $_POST attributes are not sent across and I just get an unidentified index error from mysql.
Can some one please help me ?
Im sure its something simple, but I cant figure it out.
Many thanks
Adding PHP ...
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("verify") or die(mysql_error());

$result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$_POST[product]' AND CustomerType = '$_POST[customer]'")
or die(mysql_error());

while($row = mysql_fetch_array($result))
{
echo $row['Entitlement'] ;
echo "
";
}

?>

A: try this
  <?php

  // Checking for valid post data
  if (isset($_POST['product']) && isset($_POST['customer']) && !empty($_POST['product']) && !empty($_POST['customer'])) {

    // Cleaning post data
    $proudct = mysql_escape_string($_POST['product']);
    $customer = mysql_escape_string($_POST['customer']);

    // db connnection
    mysql_connect("localhost", "root", "root") or die(mysql_error());
    mysql_select_db("verify") or die(mysql_error());

    // Quering
    $result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$proudct' AND CustomerType = '$customer'") or die(mysql_error());

    // Printing result
    while ($row = mysql_fetch_array($result)) {
      echo $row['Entitlement'];
      echo "
";
    }
  }
  ?>

A: Can you please tell how may this code works with you :)
<?php $result = mysql_query("SELECT Entitlement FROM products WHERE ProductName = '$_POST[product]' AND CustomerType = '$_POST[customer]'");?>

You have 2 error the first one the single quote beside the index in your post variable and must be like this $_POST['product'],$_POST['customer'] then the second error is that you must encapsulate your variable inside the string as following {$_POST['product']},{$_POST['customer']}
Try these work around then tell me the result :)


text:
Q: How to overload stream operators in C++ I need class to overload stream operators << (inserter) and >> (extractor)
that insert or extract a private integer variable

A: One option would be the following:
#include <iostream>

class C
{
private:
    int i;

    friend std::ostream& operator<<(std::ostream& os, const C& rhs)
    {
        os << rhs.i;
        return os;
    }

    friend std::istream& operator>>(std::istream& is, C& rhs)
    {
        is >> rhs.i;
        return is;
    }
};

int main()
{
    C c;
    std::cin >> c;
    std::cout << c << '\n';
    return 0;
}

A: To your own class? Have a look at this link: http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html
In short, you'll add something like this to your class:
ClassName & operator<<(int rhs) {
    mylocalint = rhs;
}
ClassName & operator>> (int *rhs) {
    *rhs = mylocalint;
}

A: class myclass {
private: int variable;
friend std::ostream& operator<<(std::ostream& out, const myclass& inst);
friend std::istream& operator>>(std::istream& out, myclass& inst);
};

std::ostream& operator<<(std::ostream& out, const myclass& inst)
{
    return out << inst.variable;
}

std::istream& operator>>(std::istream& in, myclass& inst)
{
    return in >> inst.variable;
}

int main() {
    myclass obj;
    std::cin >> obj;
    std::cout << obj;
}


text:
Q: Изменить размер изображения в Xamarin Forms Собственно, как изменить размер изображения в Xamarin Forms и сохранить как новый файл.
Уже имеется MediaFile, который был получен с помощью плагина Xam.Plugins от jamesmontemagno и из него нужно сделать второй файл, а конкретней - уменьшенное изображение.

A: Реализовывал такое через платформа зависимый код.
К примеру код в iOS проекте будет работать с UIImage
хороший пример описан в этом посте
https://forums.xamarin.com/discussion/4170/resize-images-and-save-thumbnails
Также можете задавать тут качество выходной картинки через UIImage.
Дальше через DependencyService получаете доступ к этим методом.


text:
Q: Check whether input values are equal I want to use this code for a barcode scanner as follows:
The scanned barcode is entered in the insert_code input and then I want to display "code is ok", when the value in search_code = insert_code.
My code, after validation, clears the input search_code and it is annoying to have to reintroduce the same code in search_code every time again.
What can I do to keep the value in search_code after each validation?
<form action="" method="post">
    Cod I:<input type="text" name="search_code" value=""/>

    Cod II:<input type="" name="insert_code" value=""/>

    <input type="submit" name="button" value="validation" />
</form>

<?php
$search_code = $_POST ["search_code"];
$insert_code = $_POST ["insert_code"];

if ($search_code == $insert_code){
    echo "code is ok";
} else {
    echo "code is not ok";
}
?>

A: If you want to keep search_code input filled with the last submitted value, just echo the value of this post into the input if it was set:
<form action="" method="post">
    Cod I:<input type="text" name="search_code" value="<?php echo isset($_POST['search_code'])?$_POST['search_code']:'' ?>"/>

    Cod II:<input type="" name="insert_code" value=""/>

    <input type="submit" name="button" value="validation" />
</form>

Also, to avoid warnings about undefined index, add this condition to your PHP code (check if those posts are set):
<?php
if(isset($_POST ["search_code"]) && isset($_POST ["insert_code"])){
    $search_code = $_POST ["search_code"];
    $insert_code = $_POST ["insert_code"];

    if ($search_code == $insert_code){
        echo "code is ok";
    }else {
        echo "code is not ok";
    }
}
?>

A: You can do this without PHP, which will give a better user-experience. Here is a live example, just run to see it work:

// identify form elements:
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');

// respond to button click
button.onclick = function validate() {
    // show verification result:
    result.textContent = search_code.value == insert_code.value
        ? 'code is ok'
        : 'code is not ok';
    // clear input when wrong:
    if (search_code.value !== insert_code.value) {
        insert_code.value = '';
    }
    return false;
};

insert_code.oninput = function () {
    result.textContent = ''; // clear result;
};
<form action="" method="post">
    Cod I:<input type="text" name="search_code" id="search_code" value=""/>

    Cod II:<input type="" name="insert_code" id="insert_code" value=""/>

    <input type="submit" id="button" name="button" value="validation" />
</form>

The test is done in Javascript, which responds to the button click and cancels the form's submission to the server (return false).
As a bonus the "ok/not ok" message is cleared as soon as you type a new value in the second input box.
How to use this code
Here is how the code should look in your document:

    <form action="" method="post">
        Cod I:<input type="text" name="search_code" id="search_code" value=""/>

        Cod II:<input type="" name="insert_code" id="insert_code" value=""/>

        <input type="submit" id="button" name="button" value="validation" />
    </form>

Note that the content part has some differences to yours: every input has an id attribute, and there is an extra div.


text:
Q: Contact List Javascript I am working on a contact list script. The list function works fine.
What the function is supposed to do is take the argument name in. If the argument matches any of the first names, bill or steve, it is supposed to log the friend's contact information to the console and return it.
I attempted to do that in my search function, but it is not returning the expected values (contact information - more specifically, the phone number). I am assuming it is my approach and misunderstanding of the object constructor.
// Creating friends object
var friends = new Object();

// Adding friends with name, phone number
friends.bill = new Object();
// Giving data to Bill
friends.bill.firstName = "Bill";
friends.bill.lastName = "Gates";
friends.bill.number = "623523";
friends.bill.address = ['One Microsoft Way','Redmond','WA','98052']

friends.steve = new Object();
// Givin data to Steve
friends.steve.firstName = "Steve";
friends.steve.lastName = "Jobs";
friends.steve.number = "73472"
friends.steve.address = ['1 Infinite Loop','Silicon Valley','CA','64326']

// Search function
var search = function(name) {
    for (var key in friends) {
        if(name === friends.name.firstName) {
           console.log(friends.name.number);
            return friends.name.number;
        }
    };
}

A: You are almost there. A "friend" is a property of the friends object/dictionary. for(var key in friends) iters amongst the name/key of the properties of the friends object (and assigns the key variable to these properties one after the other). To fetch a property/"friend" from friends using its key, you should use friends[key] (where key is a string).
Please not the difference between these examples:
var key = "james";
friends[key];     // Fetch the property with the key "james".
friends.key;      // Fetch the property with the key "key".
friends["james"]; // Fetch the property with the key "james".
friends.james;    // Fetch the property with the key "james".

Here is the solution to you problem:

// Creating friends object
var friends = new Object();

// Adding friends with name, phone number
friends.bill = new Object();
// Giving data to Bill
friends.bill.firstName = "Bill";
friends.bill.lastName = "Gates";
friends.bill.number = "623523";
friends.bill.address = ['One Microsoft Way','Redmond','WA','98052']

friends.steve = new Object();
// Givin data to Steve
friends.steve.firstName = "Steve";
friends.steve.lastName = "Jobs"; // Typo here: bill -> steve.
friends.steve.number = "73472"; // Same as above.
friends.steve.address = ['1 Infinite Loop','Silicon Valley','CA','64326']

// Printing out entries in friend object
var list = function(parameter){
for (var key in friends){
    console.log(key);

}
}

// Search function

var search = function(name){
  for (var key in friends){
    var friend = friends[key];
    if(name === friend.firstName){
      console.log(friend.number);
      return friend.number;
    }
  };
}

search("Steve");


text:
Q: Passing a struct to a dynamically loaded dll I have a dynamically loaded dll that has functions called on it, and i would like to pass it a struct. It is dynamically loaded as i do not know which version of the dll i will be using untill runtime.
Firstly, should i pass by value or reference?
Secondly, where do I declare this struct so it is available to both the dll and its caller (i assume it has to be available to both).
If i declare it in the same dll that accepts it as a parameter, then surly any potential user of the dll will have to statically link against the dll so it has access to the struct declaration, and this is what i originally wanted to avoid.

A:
Firstly, should i pass by value or reference?

That depends, see e.g. this question.

Secondly, where do I declare this struct so it is available to both the dll and its caller

You declare it in a header file that both use. The struct is declared at compile-time, no linking against any library is needed for that.


text:
Q: Disable a select button after clicking on submit button I am trying to disable a select field once I click on Search Submit button.
But after clicking the button, it temporarily disables it and it shows enable.
Here is my jquery code :
$(document).ready(function () {
  $("#search").click(function() {
    $("#cha_name").attr("disabled", true);
 });
});

Help would be appreciated.

A: instead of
$("#cha_name").attr("disabled", true);

use
$( "#cha_name" ).prop( "disabled", true );

or
$("#cha_name").attr("disabled", "disabled");

A: Use
$("#cha_name").prop("disabled", true);

instead of
$("#cha_name").attr("disabled", true);//$("#cha_name").attr("disabled", "disabled"); will work

A: use this below code it may help you.
$(document).click(function() {
  $('#onClickHideButton').prop('disabled',true);
});


text:
Q: AngularJS UI-Router not getting to default state For the life of me, I cannot get anything to load in my index.html's ui-view. I'm using AngularJS/Ui-Router in another project & it's working. This is literally everything in my project at the moment.
It worked when I had put ng-controller='ResumeCtrl' on the .
I'm not getting any errors in the console, but I do see my App Loaded [ null ] console.log.
I've looked at at least 10 different ui-router tutorials & I've REALLY simplified this and am not getting any where. I've spent the last 12hrs looking at this and I'm probably missing something REALLY small, but at this point, I'm not seeing it. :(
Here's my JSFiddle: https://jsfiddle.net/L5csekpq/2/
index.html:

WM TEST

Resume

    []

lib.js is the grunt concat/minified of the bower loaded angular.js (1.5.5)/angular-ui-route.js (0.2.18).
This is the grunt concat of all my JS files, linked above as wm.js:
angular.module('wmApp', [
    'ui.router',
    'wmApp.wmConstants',
    'wmApp.ResumeController'
])

.run(['$rootScope', '$location', '$state', function (
    $rootScope,
    $location,
    $state
) {
    console.log ('App Loaded [', $location.state(), ']');
    $rootScope.$on("$stateChangeError", console.log.bind(console));
}])
;
angular.module('wmApp.wmStates', [])

.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $stateProvider
      .state('home', {
        url: '/home',
        template: '
STATE SUCCESSFUL
'
      })
      .state('resume', {
        url: '/resume',
        template: '
{{ data }}
',
        controller: 'ResumeCtrl'
      })
  ;

  $urlRouterProvider.otherwise('/home');
}])
.run(['$state', function($state) {
  console.log('Current State: ', $state.current);
}])
;

angular.module('wmApp.wmConstants', [])

.constant('wmConstants', {
  sample: {
    api: {
      url: 'http://api.sample.com',
      key: 'xxxxxx'
    }
  }
});

angular.module('wmApp.ResumeController', [])

.controller('ResumeCtrl', ['$scope', 'wmConstants', function($scope, wmConstants) {
  console.log('ResumeCtrl', wmConstants.sample.api.url);

  $scope.data = 'omg data';
}]);

A: Your problem is that you have forgotten to declare the module wmApp.wmStates as being required by your main application module.
This:
angular.module('wmApp', [
    'ui.router',
    'wmApp.wmConstants',
    'wmApp.ResumeController'
])

Should be this:
angular.module('wmApp', [
    'ui.router',
    'wmApp.wmStates',
    'wmApp.wmConstants',
    'wmApp.ResumeController'
])


text:
Q: How to Delay a Javascript Function Until it is in the middle of web page? Hello I have a number animation on my web page and I dont want the animation to start until it is in the middle of the web page. I tried to google onscroll and other options but I could not get this to work properly.
I prefer for the animation not to start until the visitor has scrolled down to 472px. As of right now as soon as the web page loads the number animation starts automatically. Any help I would really appreciate it.

// 472 px  -  Starts Yellow Counter Section

const counters = document.querySelectorAll('.counter');
const speed = 200; // The lower the slower

counters.forEach(counter => {
 const updateCount = () => {
  const target = +counter.getAttribute('data-target');
  const count = +counter.innerText;

  // Lower inc to slow and higher to slow
  const inc = target / speed;

  // console.log(inc);
  // console.log(count);

  // Check if target is reached
  if (count < target) {
   // Add inc to count and output in counter
   counter.innerText = count + inc;
   // Call function every ms
   setTimeout(updateCount, 1);
  } else {
   counter.innerText = target;
  }
 };

 updateCount();
});
.bg-yellow-white {
    background: #f7c51e;
    color: white;
}

.container {
    max-width: 1404px;
    margin: auto;
    padding: 0 2rem;
    overflow: hidden;
}

.l-heading {
    font-weight: bold;
    font-size: 4rem;
    margin-bottom: 0.75rem;
    line-height: 1.1;
}

/* Padding */

.py-1 {
    padding: 1.5rem 0;
}

.py-2 {
    padding: 2rem 0;
}

.py-3 {
    padding: 3rem 0;
}

/* All Around Padding */

.p-1 {
    padding: 1.5rem;
}

.p-2 {
    padding: 2rem;
}

.p-3 {
    padding: 3rem;
}

 /*  ======================== Red Block ======================== */

 .red-block {

    height: 472px;
    width: 100%;
    background-color: red;
 }

 /*  ======================== PROJECS COMPLETED  ======================== */

#projects-completed .container .items {

    display: flex;
    justify-content: center;
    flex-wrap: wrap;

}

#projects-completed .container .items .item .circle {

    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

red block

500

Projects Completed

500

Staff Members

A: wesbos has great video on this https://www.youtube.com/watch?v=uzRsENVD3W8&list=PLu8EoSxDXHP6CGK4YVJhL_VWetA865GOH&index=14&t=0s
Basically what you need to do is listen for scroll and check where user currently is compared to desired place in px
you can check code here and adjust it to your needs https://github.com/wesbos/JavaScript30/blob/master/13%20-%20Slide%20in%20on%20Scroll/index-FINISHED.html

A: By using jquery , first add this reference script above your js code or referenece script


text:
Q: Python hash table for fuzzy matching I am trying to implement a data structure which allows rapid look-ups based on keys.
The python dict is great when my look-ups involve an equality
(e.g. key == somevalue translates to datadict[somevalue].
The problem is that I also need to be able to efficiently look up keys based on a more complex comparison, e.g. key > 50, or key.startswith('abc').
Obviously I can't use the same solution in both cases, but at the moment I can't figure out how to solve either case.  Can anyone suggest a way of doing this?

A: It doesn't sound like you want a hash algorithm - instead some form of binary tree. Or even a list which you use the bisect module with. It'd be worth looking at: Python's standard library - is there a module for balanced binary tree?
Another option (depending on your data), would be to use use an in-memory sqlite3 database and create appropriate indices for possible lookups -- but you'll trade performance/memory and SQL syntax for flexibility...

A: *

*Put all data items in a list.

*Sort the list on the key.

*Use binary search to efficiently find items where key > 50 or where key.startswith('abc').

Of course, this only pays off if you have really very many data items. If you have not so many, simply loop through the list and apply your condition to every key.


text:
Q: Remove Non-ASCII characters from XML file C# I am trying to write a program to remove open an XML file with Non-ASCII characters and replace those characters with spaces and save and close the file.
Thats basically it, just open the file remove all the non ascii characters and save/close the file.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;

namespace RemoveSpecial
{
    class Program
    {
        static void Main(string[] args)
        {
            string pth_input = string.Empty;
            string pth_output = string.Empty;
            for (int i = 1; i < args.Length; i++)
            {
                //input one
                string p_input = args[0];
                pth_input = p_input;
                pth_input = pth_input.Replace(@"\", @"\\");

                //output
                string p_output = args[2];
                pth_output = p_output;
                pth_output = pth_output.Replace(@"\", @"\\");
            }

            //s = Regex.Replace(s, @"[^\u0000-\u007F]+", string.Empty);

            string lx;

            using (StreamReader sr = new StreamReader(pth_input))
            {
                using (StreamWriter x = new StreamWriter(pth_output))
                {
                    while ((lx = sr.ReadLine()) != null)
                    {
                        string text = sr.ReadToEnd();

                        Regex.Replace(text, @"[^\u0000-\u007F]+", "", RegexOptions.Compiled);
                        x.Write(text);
                    } sr.Close();

                }
            }

        }

    }
}

Thanks in advance guys.

A: According to documentation, the first string is an input parameter (and not passed by reference, so it could not change anyway). The result of the replacement is in the return value, like so:
var result = Regex.Replace(text, @"[^\u0000-\u007F]+", "", RegexOptions.Compiled);
x.Write(result);

Note that RegexOptions.Compiled might decrease performance here. It makes sense only if you reuse the same regular expression instance on multiple strings. You can still do that, if you create the RegEx instance outside of the loop:
var regex = new Regex(@"[^\u0000-\u007F]+", RegexOptions.Compiled);

using (var sr = new StreamReader(pth_input))
{
    using (var x = new StreamWriter(pth_output))
    {
        while ((lx = sr.ReadLine()) != null)
        {
            var text = sr.ReadToEnd();
            var result = regex.Replace(text, String.Empty);
            x.Write(result);
        }
    }
}


text:
Q: How to filter custom Big Object fields? Here's my question on custom big object: can we filter a record under big object?. I just want to filter and show an account record based on account name, here we are storing about 300,000 records of some custom object.

A: Yes, you can perform a SOQL query against a BigObject table. However, there are very significant limitations as to how you can construct your query.
The true answer to your question is going to ride on how your BigObject is defined. That's because the specific fields, and their order, in the BigObject's index defines how you can use standard SOQL against it.
If you're working with a BigObject Order__b and it has an Order_Number__c field that is the first field in its index, you can query using WHERE Order_Number__c = :SOME_ORDER_NUMBER, for example.
If you want to do something more than that, you'd need to use Async SOQL to filter a dataset into a new custom object that you can then operate upon.

A: As I completed a small project on Big object, I can say this can be done with Index fields. Please take assess which fields you want to filter and take index on those fields, so that you will be able to filter the records in the SOQL query.


text:
Q: How to monitor whatsapp activity to show a chathead? I see that recently many apps are allowing you an option to get activated via whatsapp. Some apps are allowing you to transfer money using whatsapp in similar fashion.
As soon as I write some keyword in someone's chat window in whatsapp that wallets chat head appears and it already knows who I'm talking to and gives me an option to send money to that contact.
I was wondering how can you do that in android? and is it even legal?


text:
Q: JUnit testcase to test a Map of Map containing class object I am trying to write a JUnit testcase to test a Map: Map<String, Map<Long, Book>> map. Following is the description of the Book class: -
Class Book{ long id; String name; String description; List<Payment> payments; }
Following is the structure of the Payment class.
Class Payment{ long id; long payNum; double amount; String paidBy; }
I need to assert that the map has following entries: -
<"Shelf1", <1L, book1>> <"Shelf2", <5L, book2>>
Also, need to verify that: -
book1 has id=1L, name="my book", payments={amount=10}
book1 has id=5L, name="my book2", payments={amount=50}
I am trying following code: -
`Assertions.assertThat(map)
        .hasSize(2)
        .contains(entry("Shelf1",
            contains(entry(Long.valueOf(1),
                    extracting(Book::getId, Book::getName)
                    .containsExactlyInAnyOrder(
                              tuple(Long.valueOf(1), "my book"),
                              tuple(Long.valueOf(5), "my book2")))))));`

*

*I am always getting an error on extracting function call that the method extracting is undefined for Book::getId, Book::getName.

*In addition, I am not sure how to check the payment entry. Note that the books has only one payment entry.

I tried to solve the assert with the way that I just shared, but that is not working.your text


text:
Q: HttpHandler is not getting called I am trying to create a custom Handler but my debugger is not hitting the HandlerClass code.

Here is the class
 public class HandlerClass : IHttpHandler
{
    public bool IsReusable {
        get {
            return true;
        }
    }

    public void ProcessRequest(HttpContext context)
    {
        throw new NotImplementedException();
    }
}


text:
Q: How to Embed Google Search I have always wondered how to embed Google on a webpage. Is it possible to put it in an iframe? I know that some websites use Google CSE, but I want the real Google. If so, how can I do this?

A: You can embed this URL (aka https://www.google.com/webhp?igu=1&gws_rd=ssl) in an iframe without fail. The ?igu=1 is what makes it work. I found this answer from agoogleaday.com, which uses an iframe to house an experimental Google search website.

Your browser does not support iframes. Please consider using a modern browser.

A: If you don't want the google logo and just the search box, you can use this:

<form target="_self" id="google" method="get" action="http://www.google.com/search" target="main" onsubmit="window.top.close();">
    <input name="q" id="google" placeholder="Google Search" size="40" maxlength="2000" value="" type="text" autofocus></input>
</form>

A: You might want to check this-
https://support.google.com/customsearch/answer/2630969?hl=en


text:
Q: Using $e^{ix}$ instead of sine and cosine in contour integration A while ago I asked:
Evaluation of $\int_{0}^{\infty} \cos(x)/(x^2+1)$ using complex analysis.
Instead of using $\cos(z)$ an answerer said that is valid to use $e^{ix}$
How is this valid? I dont understand that.

A: $\cos z = \Re(e^{iz})$ and $\Re$ is a linear operator, so $\Re\int = \int\Re$.


text:
Q: Python stops working when using weight class in fitting of XGBoost I'm dealing with hight imbalanced data in a classification problem, so I use a weighted class in order to deal with this issue,
but Python stops working when I just run this Jupyter notebook cell (the fitting cell).
My code:
xg = XGBClassifier(objective ='reg:logistic', colsample_bytree = 0.3, learning_rate = 0.01,
            max_depth = 5, alpha = 10, n_estimators = 100)

class_weight = {0: 1,
            1: 9}

xg.fit(X_train,y_train,sample_weight=class_weight)


text:
Q: Text encoding driving me crazy I am writing a paper in english but will need to provide a danish abstract and use the little word "Köppen" as well. For some reason I seam not to be able to get the them to work.
This example:
\documentclass{article}
\usepackage[german, danish, english]{babel} % danish and english languages
\usepackage{float}  % provides the ploat placement parameter H
\usepackage[ansinew]{inputenc} % provides the characters Æ, Ø, Å, æ, ø, å

\begin{document}
ö ø %å
\end{document}

compiles but gives me ö and à rather than ö and ø as they should as long is the file is saved in utf-8. If I save it in ISO Latin 9 the world is hole again and I get what I was wishing for.
The problem is that all my files are saved in utf-8 and I would like to not go through the process of changing them all.
Is there a setup to write documents containing ä, ö, ü, å, ø and æ using utf-8 encoding?
I tried to play with these packages but di not get anywhere really.
\usepackage[german, danish, english]{babel} % danish and english languages
\usepackage[ansinew]{inputenc}
\usepackage[T1]{fontenc}

I know this should be easy to figure out but I have a deadline in 10 days and this just drives me up the wall. There are still bigger fish to fry and i only need a hand full of these little obnoxious ö's and co. Please help me keep my sanity (well, whats left of it anyways).

Side note:
I love LaTeX for many reasons but the text encoding is driving my crazy. Why does it have to be so unnecessarily complicated? I mean I can type all these letters right here with no problem?!

A: If the file is saved in UTF-8, then just use
\usepackage[utf8]{inputenc}

If you are saving the file in ISO Latin 9, then
\usepackage[latin9]{inputenc}

If you do not know the encoding of the file, then package selinput helps, e.g.:
\usepackage{selinput}
\SelectInputMappings{
  adieresis={ä},
  germandbls={ß},
  Euro={€},
}

The packages chooses the right encoding for inputenc depending on the given glyph mappings.


text:
Q: Connect to database from another docker container I ran two docker containers one is tomcat and one is phpmyadmin.
I ran the phpmyadmin container with this command:
docker run -d -p 49160:22 -p 49161:80 -p 49162:3306 --name db phpmyadmin:imported

And I can see the phpmyadmin on my browser on port 49161. I ran the tomcat container with this command
 docker run -it -v ~/docker/tomcat/tomcat-users.xml:/usr/local/tomcat/conf/tomcat-users.xml --name tomcat --link db:server -p 8888:8080 tomcat:deployed

Every thing looks fine. I can ping the db from the tomcat container. but when I try to connect to it using hibernate and my J2EE application I get the following error.
10-Jun-2015 19:20:12.293 WARNING [http-nio-8080-exec-15] org.hibernate.cfg.SettingsFactory.buildSettings Could not obtain connection metadata

java.sql.SQLException: Connections could not be acquired from the underlying database!
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:690)
    at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
    at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:56)

This is my hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://172.17.0.20:3306/auction</property>
        <property name="hibernate.connection.username">root</property>
       <property name="hibernate.show_sql">true</property>
        <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>

        <mapping class="ie.domain.entity.User"/>
        <mapping class="ie.domain.entity.Auction"/>
        <mapping class="ie.domain.entity.Offer"/>
    </session-factory>
</hibernate-configuration>

I tried to use the name server instead of the IP and also I tried the port 49162 instead of 3306 and I got the same error.

A: Try connecting with:
jdbc:mysql://server:3306/auction

The port mappings are on the host, so you don't use them when talking directly to the container. The docker link functionality will add the name "server" to /etc/hosts with container IP address, so you can just reference it by name.
UPDATE: Judging from the comment on https://registry.hub.docker.com/u/wnameless/mysql-phpmyadmin/, this isn't going to work as the server is only listening on 127.0.0.1, not 0.0.0.0.


text:
Q: SQL INSERT TO statement - How to see original text in the code I am trying to log into my custom admin account from my SQL login, but i forgot my password.
I have tried the ASCII table to convert the text but that isnt the issue.

CREATE TABLE `login` (
  `id` int(255) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `admin_lvl` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Data is being exported for table `login`
--

INSERT INTO `login` (`id`, `username`, `password`, `admin_lvl`) VALUES
(1, 'john@doe', '$2y$10$QpppknXqp7LA/uSPMB6W/.J78O6r0U9EBjqt14v.cSwwWWOi8zfl2', 1),
(4, 'admin', '$2y$10$ogYLLHn1s7us8WlnmCwM4.fsLSePffusfq2Juey98nvsw6COWow7m', 9);

Is there any way to decrypt the password of admin instead of deleting it and making a new admin user with a new password?

A: It is by design that you cannot recover a password from its hash.
I mean, that is literally the whole reason we store hashes. So that people stealing databases cannot [trivially] find the original password.
If you could get yours back from the table, that entire process would be broken!
You should use your admin powers to set a new password, or ask somebody who does for help.
Said admin does not have to remove the entire user; they only have to do an UPDATE on the login table to put a new value into the password field.
Ideally, the application that is built around this database would already have a "forgot password" feature that accomplishes just that, with all the necessary security precautions (e.g. email verification, two-factor authentication, whatever).


text:
Q: Translating VB.NET Method Call to C# I can't seem to figure how to properly convert the following VB.NET code into C#, where I will be declaring a web service object and then ultimately using a function to return the data I need. I have the webservice created in my project: http://mmm-acctgdev.abc.com/Central_Locating/Service/Locating.asmx
VB.NET web service declaration:
Dim oFind As New com.abc.mmm_acctgdev.Locating

//*Need to convert this into something a C# form can use

VB function call :
retXML = oFind.GetLocationByNum(txtFNum.Text)

//*need this call in c#

A: var oFind = new com.abc.mmm_acctgdev.Locating();
var retXML = oFind.GetLocationByNum(txtFNum.Text);


text:
Q: C# class constructor assigning to 'this' I have a 'naïve' question.
With the following sample code:
public class ThisClass
{
    public int ThisClassID { get; set; }
    public string ThisValue { get; set;}

    public ThisClass()
    {
    }

    public ThisClass(int thisClassID)
    {
        using (MyContext dbContext = new MyContext())
        {
            this = dbContext.CaseNotes.Find(thisClassID);
        }
    }
}

And, of course, I get the error Cannot assign to 'this' because it is read-only
The only two ways of solving this that I know of are to have a static method, or to assign to each property separately.
Is there any way of creating a simple constructor that returns database entities into this?
UPDATE
Both answers below are correct but I can only accept one. There was some interesting discussion on the use of factories and repository patterns that were sadly deleted when a potential answer was deleted. Arguments were equally balanced both for and against with some pointing out the the Entity Framework itself is a factory that uses a repository pattern. The question itself had three upvotes and two downvotes.
The answer seems to be that there is no single answer.

A: You should take a look at AutoMapper, and your code could look as follows:
// Somewhere in your application/service initialization class and in some method...
Mapper.CreateMap<ThisClass, ThisClass>();

public class ThisClass
{
    public int ThisClassID { get; set; }
    public string ThisValue { get; set;}

    public ThisClass()
    {
    }

    public ThisClass(int thisClassID)
    {
        using (MyContext dbContext = new MyContext())
        {
            Mapper.Map(dbContext.CaseNotes.Find(thisClassID), this);
        }
    }
}

BTW it sounds like a bad idea. I wouldn't populate a domain object inside its own constructor.
This is a good responsibility for the repository.

A:
Is there any way of creating a simple constructor that returns database entities into this?

In practice no. In theory you can make the type a struct. Then, the code should compile. You can assign to this in a struct.
Probably, you should not use a constructor at all. Create a factory method that simply returns the result from Find.
One unchangeable fact about constructors is that they create a fresh object every time. I don't think you want that here. You probably want to preserve the existing object instance and its identity.


text:
Q: Diskless Boot with IPv6 At our work we are using around 80 diskless machines running Ubuntu. We want to make the transition to IPv6, so now I'm trying to get our diskless system to work with IPV6. The transmission of the kernel and initramfs can be still over a IPv4 connection, but once the machine is fully booted I want all network connections to be over IPv6.
This means that the nfsroot has to be mounted via IPv6. My research of this has shown that initramfs-tools (1.18.5-1ubuntu4.1) does NOT support IPv6. That means that neither ipconfig, that's used for interface configuration at early boot time, nor the mount mounting procedure for the nfs root are IPv6 capable.
To circumvent this I added two binaries to the initramfs (/etc/initramfs-tools/hooks/ipv6):
#!/bin/bash
. /usr/share/initramfs-tools/hook-functions
copy_exec /sbin/dhclient /sbin
copy_exec /sbin/mount.nfs4 /sbin

I use these to (a) request a DHCPv6 at early boot time with
/sbin/dhclient -6 -1 -cf /tmp/dhclient.conf -pf /tmp/dhclient6.eth0.pid -lf /tmp/dhclient6.eth0.leases eth0

and (b) to configure the interface with the address I attained by executing:
ipv6=$(cat /tmp/dhclient6.eth0.leases | grep iaaddr | egrep -o "([a-f0-9]{1,4}:){3}([a-f0-9]{0,4}:){0,4}[a-f0-9]{1,4}")
ip -6 addr add $ipv6/112 dev eth0

Usually the nfs root is mounted with the following command in/usr/share/initramfs-tools/scripts/nfs:
nfsmount -o nolock ${roflag} ${NFSOPTS} ${NFSROOT} ${rootmnt}

But this doesn't seem to accept IPv6 addresses.
So I changed it to:
mount ${roflag} -t nfs4 ${NFSROOT} ${rootmnt}

$NFSROOT in this case is [2001:4ca0:2218:1::1:2]:/lb/diskless/rootfs/ubuntu_1204_ipv6.
The interface configuration seems to work as well as the root mounting, but when /sbin/init is executed (I think), the IPv6 is dropped again, and therefore the system freezes (because it cannot access the ubuntu root anymore).
The /etc/network/interfaces file looks like this:
auto lo
iface lo inet loopback

iface eth0 inet manual
iface eth0 inet6 manual

Is there a way to keep the interface configuration from the initramfs? Or am I doing something wrong when I configure the interface with ip?

A: maybe it's off topic to you but I think that your specific problem can be avoided by rethink the service :
why bother booting with NFS ?
You can try to boot with iscsi (in a read only mode to allow more than one connection to the image) and then use iscsi or nfs (ipv4) for the user shares if you need to. You can achieve this with the ipxe project.
Another way is to use squashfs+tmpfs and not to bother so much with shares during the booting process of the system and then do remounts depending on the user authentifications (however this have a higher memory consumption on the client side).
Hopes that helps you.


text:
Q: Get values from Key/Value variable in javascript Please consider this scenario:
I have a Key/Value variable like this:
var dict = {"78": "X",
            "12": "G",
            "18": "R",
            "67": "U",
            "68": "O",
            "30": "P"}

I have a string that I want to check if there is a letter of my variable exist in my string. How I can do this?

A: Collect object key values and use them to create a regular expression. Then use .test(yourString):
var myStr = "Group";
new RegExp(Object.keys(dict).map(function (c) { return dict[c]; }).join("|"))
   .test(myStr); // true

Another way is simply iterating the object:
var found = false;
for (var k in dict) {
   if (myStr.indexOf(dict[k]) !== -1) {
      found = true;
      break;
   }
}

if (found) {
   // letter found
}

A: One possible approach:
var contains = Object.keys(dict).some(function(key) {
  return someStr.indexOf(dict[key]) !== -1;
});

In other words, iterate over the collection, at each step checking whether or not the tested character present in your string (someStr). If it is, stops the iteration immediately (that's how Array.prototype.some works).
Another approach is building a character class regex, then using it against the string:
var pattern = RegExp('[' + Object.keys(dict).map(function(k) {
  return dict[k];
}).join('') + ']');
var contains = pattern.test(someStr);

The second approach is slightly better if the tested strings usually do contain the characters from dict. It's also quite easy to augment this solution into case-insensitive search - just add 'i' string as a second param of RegExp call.
The caveat is that you'll have to escape the characters that will be considered meta within a string passed into RegExp constructor (backslash, for example). If there are no such characters in the dictionary, it's not a problem, though.

A: It can be done using the following:
str = "test";
isExists = false;
for(var key in dict){
  isExists = str.indexOf(dict[key]) !== -1;
  if(isExists)
    break;
};
console.log(isExists);