text:
Q: DJI Bridge App Tutorial No Video Stream in Swift - Phantom 4 Pro I am currently going trough DJI Bridge App Tutorial. I am using Swift with bridge header that imports VideoPreviewer. App compiles just fine. I can connect to the product. I can register. Bridging app is working fine. But I get stuck with video stream. Do you have got any ideas?
Method
"func videoFeed(_ videoFeed: DJIVideoFeed, didUpdateVideoData videoData: Data)
is called correctly. When reading bytes from Data object. I am receiving some values. Than sending these values to the VidePreviewer as
func videoFeed(_ videoFeed: DJIVideoFeed, didUpdateVideoData videoData: Data) {
   var result = videoData.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) -> UInt8 in
        return pointer.pointee
    }

    print (result)

    print("Stream info:\(VideoPreviewer.instance().currentStreamInfo.frameRate)")
    VideoPreviewer.instance().push(&result, length: Int32(videoData.count))

        print(VideoPreviewer.instance().isDefaultPreviewer)

}"

However is this correct? DJIVideoStreamBasicInfo(frameSize: (0.0, 0.0), frameRate: 15, encoderType: 1). print (result) returns values
-----But the frameSize is 0.0, 0.0 could this be the problem?-----
Result is that View set for VideoPreviewer is always black. Below is code for whole Swift file for whole DJICameraViewController.swift, that compiles and run.
import UIKit
import DJISDK
class DJICameraViewController: UIViewController, DJISDKManagerDelegate,DJICameraDelegate,DJIBaseProductDelegate, DJIVideoFeedListener {
var camera: DJICamera!
@IBOutlet weak var fpvPreviewView: UIView!

@IBOutlet weak var recordBtn: UIButton!

@IBOutlet weak var changeWorkModeSegmentControl: UISegmentedControl!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.registerApp()
    VideoPreviewer.instance().setView(self.fpvPreviewView)

}

override func viewWillDisappear(_ animated: Bool){
    super.viewWillDisappear(animated)
    VideoPreviewer.instance().setView(nil)
    DJISDKManager.videoFeeder()?.primaryVideoFeed.remove(self)
}

func registerApp(){

     DJISDKManager.registerApp(with: self)

}

func appRegisteredWithError(_ error:Error?)
{
    var message: String = "Application is registered."

    if (error != nil) {
        message = "Register App Failed!"
    } else {
        message = "Application is registered."
        DJISDKManager.enableBridgeMode(withBridgeAppIP: "192.168.2.2")
        DJISDKManager.startConnectionToProduct()
        VideoPreviewer.instance().start()

    }

    DispatchQueue.main.async {

        let alert = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)

    }

}

/* after product is recognized. FetchCamera method is called by method productConnected */

func fetchCamera() -> DJICamera? {

    if ((DJISDKManager.product()) == nil){

        return nil
    }

    if (DJISDKManager.product()!.isKind(of: DJIAircraft.self)){

        print("Have UAV")
        return ((DJISDKManager.product() as? DJIAircraft)?.camera)!
    }

    return nil
}

/* DJIBaseProductDelegate method called when product is recognized */

func productConnected(_ product: DJIBaseProduct?) {
    print("Product recognized")
    if ((product) != nil) {
        product?.delegate = self

        camera = self.fetchCamera()
        if (camera != nil) {
            camera.delegate = self
            DJISDKManager.videoFeeder()?.primaryVideoFeed.add(self, with: nil)
        }
    }
}

func videoFeed(_ videoFeed: DJIVideoFeed, didUpdateVideoData videoData: Data) {

    var result = videoData.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) -> UInt8 in
        return pointer.pointee
    }

    print (result)

    print("Stream info:\(VideoPreviewer.instance().currentStreamInfo.frameRate)")
    VideoPreviewer.instance().push(&result, length: Int32(videoData.count))

        print(VideoPreviewer.instance().isDefaultPreviewer)

}

}
From the Xcode console following code prints outputs below
`print("Stream info:\(videoPreview.currentStreamInfo.frameRate)")
    VideoPreviewer.instance().push(&result, length: Int32(videoData.count))
       print(videoPreview.currentStreamInfo)
        print(videoPreview.isDefaultPreviewer)`

Output printed by the print code above:
Start:
Stream info:0
DJIVideoStreamBasicInfo(frameSize: (0.0, 0.0), frameRate: 0, encoderType: 0)
true
136

2nd:
Stream info:0
[h264 @ 0x102024210] sps_id 32 out of range
VUI timing infomation not present, set to default:29.97fps
[h264 @ 0x102024210] sps_id 32 out of range
VUI timing infomation not present, set to default:29.97fps
[h264 @ 0x102024210] missing picture in access unit with size 958351
DJIVideoStreamBasicInfo(frameSize: (0.0, 0.0), frameRate: 0, encoderType: 0)
true
65

3rd:
Stream info:15
DJIVideoStreamBasicInfo(frameSize: (0.0, 0.0), frameRate: 15, encoderType: 1)
true
119

And sometimes pops up:
Stream info:15
[h264 @ 0x102024210] SEI type 103 size 1712 truncated at 288
[h264 @ 0x102024210] sps_id 32 out of range
VUI timing infomation not present, set to default:29.97fps
[h264 @ 0x102024210] missing picture in access unit with size 111113
DJIVideoStreamBasicInfo(frameSize: (0.0, 0.0), frameRate: 15, encoderType:
[h264 @ 0x102024810] SEI type 103 size 1712 truncated at 279

And other times pops-up:
 Stream info:15
DJIVideoStreamBasicInfo(frameSize: (0.0, 0.0), frameRate: 15, encoderType: 1)
[h264 @ 0x102024810] sps_id 32 out of range
true
[h264 @ 0x102024810] sps_id 32 out of range
[h264 @ 0x102024810] sps_id 32 out of range
[h264 @ 0x102024810] sps_id 32 out of range
[h264 @ 0x102024810] sps_id 32 out of range
0[h264 @ 0x102024810]
 sps_id 32 out of range

A: You should try to set the VideoPreview.instance() as a let somewhere convenient and use it.
Also, make sure to provide a valid queue when adding the listener to the video feed.
Try these and let me know if it helped.


text:
Q: Remove last x elements from the list Lets say I have a List<Car> Cars that have n items and I want to delete the last two. The best way that I found is:
Cars.RemoveRange(Cars.Count-2, 2);
Is there better way? I searching something like this:
Cars.RemoveFrom(Cars.Count-2); //pseudocode

A: Now we have the option
void List<T>.RemoveRange(int index, int count);

See Microsoft Docs List.RemoveRange(Int32, Int32) Method for Core
Microsoft Docs List.RemoveRange(Int32, Int32) Method for Framework 4.8
Applies To
.NET Core
3.1 3.0 2.2 2.1 2.0 1.1 1.0
.NET Framework
4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5 3.0 2.0
.NET Standard
2.1 2.0 1.6 1.4 1.3 1.2 1.1 1.0

A: No, there isn't... But if you want you can put it in an extension method.
static class ListEx
{
    public static void RemoveFrom<T>(this List<T> lst, int from)
    {
        lst.RemoveRange(from, lst.Count - from);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any difference between "2 instances of JVM" and "2 different JVMs"? I have been told to make an EJB and plain Java program (client), and try to run both these in two different JVMs, and get them executed. What is meant by "two different JVMs"?

A: Your requirement :

*

*EJB

*Plain Java client for (1)

Run in different JVMs - it is as simple as it can get.
Normally EJBs are hosted in an Application server ( Such as Weblogic,Websphere, Jboss,Glassfish, etc etc) - when you deploy your EJB to one such server and start that server - server process is a "JVM"- meaning your server process that hosts your EJB is running in a JVM.
Now, you have written and compiled your Client application. For laughs, let us call it
MyBigClient.java
when you run java MyBigClient on command line or run it through the "Run" button of your favorite IDE, it is executed by a JVM - that is your second JVM instance
Voila - you have EJB and Client running in two different JVMs
Now if you use a different "java.exe"(Say, C:\JDK1.6\bin\java.exe) to run the client than the java.exe (Say, C:\JDK1.5\bin\java.exe) used by your application server, you are using "two different JVMs"
It is all how you want to define "two different" - I do not think there is any hard and fast rule around this.

A: In this context, I can't discern a difference between the two.  For the record, two different JVMs would be, in my mind, two JVMs with different versions (JRE 6 and JRE 7), and two instances implies that it's one JVM version being used twice (i.e. two separate Java applications).

A: Set your class path to one JVM for the EJB; Set the class path to another JVM for the client.


text:
Q: Single method which can return the value of a column in a datarow and automatically handle the possibility of the column value to be null Can anyone suggest a single method which can return the value of a column in a datarow and automatically handle the possibility of the column value to be null. Essentially I was trying to come up with a generic solution taking advantage of the DataRow extension methods to handle DBNull values. My solution till now has been:
public static Nullable<T> SafeRead<T>(DataRow row, string fieldName) where T : struct
{
    if (row.HasColumn(fieldName))
    {
        return row.Field<Nullable<T>>(fieldName) ?? default(Nullable<T>);
    }
    else
        return default(Nullable<T>);
}

public static T SafeRead<T>(DataRow row, string fieldName) where T : class
{
    if (row.HasColumn(fieldName))
    {
        return row.Field<T>(fieldName) ?? default(T);
    }
    else
        return default(T);
}

But this obviously complains about method ambiguity since C# does not allow method overloading based on parameter contraints

A: The following will give you the value back from the datarow, or the default for the type if the value is DBNull.Value. If the field is not defined it will throw an ArgumentException.
using System;
using System.Data;

public static class DataAccess
{
    public static T GetValueOrDefault<T>(DataRow row, string fieldName)
    {
        if (!row.Table.Columns.Contains(fieldName))
        {
            throw new ArgumentException(
                string.Format("The given DataRow does not contain a field with the name \"{0}\".", fieldName));
        }
        else if (row[fieldName].Equals(DBNull.Value))
        {
            return default(T);
        }

        return row.Field<T>(fieldName);
    }
}

And here are a few simple tests:
[TestMethod]
public void GetValueOrDefault_ValueType_Test()
{
    const string FieldName = "Column";
    const int Expected = 5;

    DataTable dataTable = new DataTable();
    dataTable.Columns.Add(FieldName, typeof(int));

    DataRow row = dataTable.Rows.Add(Expected);

    int actual = DataAccess.GetValueOrDefault<int>(row, FieldName);
    Assert.AreEqual(Expected, actual);
}

[TestMethod]
public void GetValueOrDefault_ValueType_DBNull_Test()
{
    const string FieldName = "Column";

    DataTable dataTable = new DataTable();
    dataTable.Columns.Add(FieldName, typeof(int));

    DataRow row = dataTable.Rows.Add(DBNull.Value);

    int actual = DataAccess.GetValueOrDefault<int>(row, FieldName);
    Assert.AreEqual(default(int), actual);
}

[TestMethod]
public void GetValueOrDefault_ReferenceType_Test()
{
    const string FieldName = "Column";
    object expected = new object();

    DataTable dataTable = new DataTable();
    dataTable.Columns.Add(FieldName, typeof(object));

    DataRow row = dataTable.Rows.Add(expected);

    object actual = DataAccess.GetValueOrDefault<object>(row, FieldName);
    Assert.AreEqual(expected, actual);
}

[TestMethod]
public void GetValueOrDefault_ReferenceType_DBNull_Test()
{
    const string FieldName = "Column";

    DataTable dataTable = new DataTable();
    dataTable.Columns.Add(FieldName, typeof(object));

    DataRow row = dataTable.Rows.Add(DBNull.Value);

    object actual = DataAccess.GetValueOrDefault<object>(row, FieldName);
    Assert.AreEqual(default(object), actual);
}

A: You could always make your own bastardised implementation of Nullable - and return that from your function.
public class SafeValue<T>
{
    public T Value {get; set;}
    public bool HasValue
    {
        get
        {
            if(typeof(T).IsClass)
                return Value != null;
            else return true;
        }
    }
}

So, replace both with something like:
public static SafeValue<T> SafeRead<T>(DataRow row, string fieldName)
{
    if (row.HasColumn(fieldName))
    {
        return new SafeValue<T>{ Value = row.Field<T>(fieldName)};
    }
    else
        return new SafeValue<T>();
}

And usage:
var val = SafeRead(row, "wah");

if(val.HasValue)
    //DoStuff();


text:
Q: Phonegap VS Steroids. Did I choose well? I want to develop an App for Android ann iOS. It is a very simple App where there are almost no server connections and it is pretty simple. The only things is that it will have many animations.
I thought that would be a good idea to choose Phonegap instead of a native application because it is multiplatform and it is very much easy to develop for a web developer like me.
But, when you read in the web you see a lot of people who say that it is really slow, that buttons doesn't react inmediatly and more things.
So first I would like to ask, Will the phonegap performance be enough for this kind of App.
And secondly, I have found Steroids. It looks great because it takes Phonegap and make it native. But it sounds too well, I mean, you have all of Phonegap with more performance, I guess it should have some problems.
So, could I use Stereoids instead of Phonegap to increase the performance? What it worse of Steroids?
Greetings and thanks.

A: Full disclosure, I'm an AppGyver employee and am of course inherently biased towards the Steroids platform, but here's a quick rundown of why you should choose us over PhoneGap:

*

*Theoretically, anything that can be done in PhoneGap can be done in Steroids as well. In reality, there are a few lingering problems with some custom plugins that might require some tweaking to work through our Build Service, but core Cordova plugins are supported.

*Steroids provides Native UI features to make your app virtually indistinguishable from an actual native app. We've gone to great lengths to ensure that the end user would not be able to tell a Steroids app from a fully native one. This includes eliminating the delay between button taps and the app reacting, as well as providing ready-made implementations for drawers, modals, tab bars and all the goodies that you would find in a native app, but have to build by hand in a PhoneGap app. Admittedly, this feature set is currently only available for iOS, but our Android support is catching up fast with the first UI features being in internal QA at the moment and more coming soon!

*Our qr code system makes demoing (and developing) apps insanely fast compared to having to constantly rebuild and install demo versions of your app. Just download the AppGyver Scanner, generate a share code and scan, and your app is now running on your phone.

*We provide support for a Chromium-based Android client, which blows the old Android WebViews out of the water in terms of performance and cross-platform compatibility. Once again, this is still a very young property, so full support for all Steroids features is not there yet, but Android is currently our top priority, meaning things will improve fast.
I am glossing over the details quite a bit here, but this should give you a general idea of what we feel makes our product great!


text:
Q: Is " in two to five days" a correct experession? I am wondering if "in two to five days" is correct or not. If it is correct, what are the differences among the following expressions? How do you differentiate them? I am Japanese, and the Japanese counterpart of the expression is "2日から5日のうちに."

*

*within two to five days

*between two to five days

Thank you for your assistance!

A: "In two to five days" is correct English usage in a sentence such as this:

"Your item will ship in two to five days."

Likewise,

"Your items will ship within two to five days after receiving your order."

In the above examples, "between two to five days" would be a bit awkward and not as idiomatic, as the preposition "between" is usually used to describe a relationship between two things or persons; e. g., "That comment was meant to stay between you and me."
However, "between" can be used correctly in the right context; e. g.,

"Due to changes in the agenda, the meeting could last anywhere between two and five days."


text:
Q: Removing merge with ancestor I have a mercurial repo of the followng form:
... 27-28----------------------38-39 ... tip
         \__ 29 __ ... __ 37__/

as you can see, I have accidently merged 37 into 28, creating 38. How can I fix this, so that I get a simple linear history like the follwing:
... 27-28-29-...-37-39-...tip

A: There's no easy way to do this.  You could probably use the convert extension to rebuild the repository with that history using the --branch-map argument and manually stitching it together as you'd like, but it'll invalidate all existing clones, change the hashes, and be a pain to do.  Don't fetishize a linear history -- anonymous branches and merges are part of a normal DVCS workflow.  Embrace it.

A: If it is not pushed yet, the easiest is to rebase 39 (and descendants) on top of 37, and simply strip changeset 38.
You'll get your linear history, but as @Ry4an said, "embrace" the fact that your history will not be linear, otherwise it will just make you unhappy...


text:
Q: I'm in the process of gathering quotes for multifunction copier leases...what questions should I be asking the sales people? What sort of key questions should I be asking to determine which product/company to go with? Aside form researching the different copiers presented by the different companies (Xerox, Ricoh, Savin, and Konica Minolta) what sort of key determining factors should I be researching?
Right now I know that I need to consider things like maintenance costs, SLAs, monthly lease costs, cost of delivery/setup...but I'm not sure what else I should be considering?
I'm currently looking to get a color multifunction copier setup in two of our offices in the midatllantic region.
Thanks in advance.

A: Never thought I'd have to deal with copiers in a sysadmin role, but some how they fell into our IT department's purview during the last round of upgrades.  We had little warning and almost no influence on vendor/model selection.  The devices were purchased and we were told "make these work".  Had I involvement in the process I would have been asking about the following:

*

*Directory integration for user/groups/address books. (AD, LDAP, etc.)

*Scan-to-file output file system support. (NFS, CIFS...)

*LDAP/AD integration for user authentication (Secure printing, scan-to-profile...)

*Remote console (web-based is a plus for me) to centrally manage multiple devices.

A: Do have a very close look at the costs/volume/quotas - and see if you can get accurate measures of your current usage - often the standard leases will have a quota of pages - but as soon as you go over this, you start getting charged ridiculous amounts for each page.


text:
Q: Why is $\lim_{n\rightarrow \infty } \binom{n}{s}(\frac{\lambda}{n})^{s}=\frac{\lambda^{s}}{s!}$? For some $s\in \mathbb{N}$ and  $\lambda\in \mathbb{R^{+}}$
Why is
$$\lim_{n\rightarrow \infty } \frac{\displaystyle \binom{n}{s}}{n^{s}}=\frac{1}{s!}?$$

A: You have to prove that
$$
a_n := \frac{n!}{n^s (n-s)!} \to 1
\qquad
n\to +\infty.
$$
You see in a moment that
$$
a_n = \frac{n (n-1) \cdots (n-s+1)}{n^s}
= \prod_{k=0}^{s-1} \frac{n-k}{n}
= \prod_{k=0}^{s-1} \left(1 - \frac{k}{n}\right)
$$
and so $a_n \to 1$ as $n\to +\infty$ since each of the $s$ factors goes to $1$.


text:
Q: Fastest way to read and write data in Python? Suppose I have a very large file and I want simply to divide into smaller chunks and process successively. However, in that implementation reading and writing those chunks is the bottleneck. Therefore I am looking for the best possible way. I am using cPickle presently, dumping and loading the chunks. Do you have any other alternative suggestion?

A: mmap will map part of the file cache into process memory, allowing pointer-based (or in Python's case, index-/slice-based) access to the bytes in the file. From there you can slice the mmap object to get strings, and pass them to cPickle.loads() in order to restore the original objects.

A: You probably won't get any faster than file.read(chunksize) to read chunksize bytes from a file.  You can just do that until you read less than chunksize bytes (then you know you've hit the end).  e.g.:
with open('datafile') as fin:
    data = fin.read(chunksize)
    process(data)
    while len(data) == chunksize
        data = fin.read(chunksize)
        process(data)

However, since you say that you're using cPickle -- I'm not really sure what the data looks like, or if you're looking for something more sophisticated...
And a word of warning -- Generally speaking, fileIO is one of the slowest things you can do with your computer.  If you're doing a lot of it, you can expect it to be a bottleneck no matter what you do (unless you have a really fancy file system -- Then you might be able to do something about it).


text:
Q: Implement InfluxDB in Delphi 11 Is there someone which already tried to install an InfluxDB database and use it from Delphi ?
I tried from this Github :

https://github.com/larsenbjorn/InfluxDB-Delphi

But the Demo application makes nothing.


text:
Q: Convert existing project to library project in Android Studio How can I convert an existing Android project into an Android library project in Android Studio? In Eclipse, that is possible.
Actually, I want to convert an old Android project into an Android library project so that I can use existing code of that Android project to build a new Android project with minor changes in Android Studio.

A: Looking at this document
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Multi-project-setup
I think all you have to do is add this to your build.gradle file,
Creating a Library Project
apply plugin: 'android-library'

From the link
Creating a Library Project
A Library project is very similar to a regular Android project with a few differences.
Since building libraries is different than building applications, a different plugin is used. Internally both plugins share most of the same code and they are both provided by the same com.android.tools.build.gradle jar.
buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.6'
    }
}

apply plugin: 'android-library'

android {
    compileSdkVersion 15
}

A: Changing to Library

*

*Goto android project, where you need to change as Library module.

*In build.gradle(:app) file,

*

*change this line to
plugins {
  id 'com.android.application'
  }

to
plugins {
  id 'com.android.library'
  }

*Delete the line for the applicationId in same build.gradle(:app) file
defaultConfig {
     applicationId "com.project.example" //remove this line
     minSdk 21
     targetSdk 31
     versionCode 1
     versionName "1.0"

     testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
 }

*Now Sync Project with Gradle Files.

A: In your module's build.gradle file (not the root project, if you use modules!), simply replace:
apply plugin: 'com.android.application'
// or, if you're on an old version
apply plugin: 'android' // note: this one is deprecated

...with:
apply plugin: 'com.android.library'
// or, if you're on an old version
apply plugin: 'android-library' // note: this one is deprecated

Note that recently, 'android' has changed to 'com.android.application', while 'android-library' has been changed to 'com.android.library'. Avoid using the old names in new projects.
After updating your build.gradle file, you should Sync Project with Gradle files (which is in the toolbar), as not doing it might result in errors and things not working correctly.
Android Studio will then update some files to indicate that the module is now a library; as this will be added into your .iml file:
<option name="LIBRARY_PROJECT" value="true" />

As you might already know, you will not be able to run your (now) library project -- you will need to include it into an app project.
If you're using Android Studio 1.0 and you are getting "Library projects cannot set applicationId", make sure you do not have applicationId in your Gradle build file.

A: open project in file explorer,open project.properties and try changing android.library=true in project.properties

A: If you make it with command line, like chanakya propose, you have to update it with:
android update lib-project \
--target <target_ID> \
--path path/to/your/project

see: http://developer.android.com/tools/projects/projects-cmdline.html#ReferencingLibraryProject
That work for eclipse, but not for android-studio since that update the build.xml.

A: This is a late response, but I've been trying to do the same thing. None of the above seem to have done the job for me, but I found this that I think works:
Right click on the project name -> Mark Directory As (at bottom) -> Sources Root
I don't know the difference between Resources Root and Sources Root, and a bit of googleing to turn up the answer, but hopefully that's right. I just know a Library isn't supposed to build an apk, and after setting this option, it's not able to so I'm assuming it works.
If anybody else knows more than me, please say so!


text:
Q: Actionscript error cannot import library In the Below action script file i get an error saying cannot import mx.controls.Label,how is this to be resolved
  package {
    import flash.display.Sprite;
    import mx.controls.Label;

    public class cld extends Sprite
    {
        public function cld()
        {
            var myLabel:Label = new Label();
            myLabel.text = "hello";
            addChild(myLabel);
        }

    }

}

A: Make sure it is Flex project and that in project properties->Flex Build Path->Library Path you import the framework.


text:
Q: Use pojo as gwt RequestFactory proxy instead of interface Is there any easy way to use a pojo as a request factory proxy and not an interface? The case is that I would like to reuse the actual value object as is without creating an interface describing it.
I do not that this can not be done out of the box. GWT fails to compile with an error regarding non getter/setter methods insite the "proxy" class.

A: This not possible, by design.  See this previous StackOverflow answer.


text:
Q: iTextSharp 5 generated PDF-Document AdobeReader-compatibility I am generating some reports with iTextSharp 5.
Opening the generated .PDF-file, everything looks and actually is fine with most PDF-readers.
When I open the PDF using AdobeReader(DC) however, it asks me if i want to save the changes on close. Although I didn't change anything.
Hitting 'Cancel' sure makes the message window go away, but hitting save causes the file to actually shrinks in size.

Now what is happening there? And why? How can I disable it?
The users of the application are most likely gonna use AdobeReader as well.
I don't want them to see the save dialog anytime they open a report.
Here is my BaseReport class
public abstract class BaseReport : PdfPageEventHelper
{
    protected const string SPACE = " ";
    protected const string COLON = ":";
    protected static string NEWLINE = Environment.NewLine;
    protected Document document;
    protected PdfTemplate footerTemplate;
    protected PdfContentByte contentByte;
    protected PdfWriter writer;

    private PdfTemplate totalPageNoTemplate;
    private int lastPageNumber;

    // properties for header
    private bool done;
    // needs to be overriden in subclass order to use header feature
    protected string kundeHeader { get; set; }

    // font definitions
    protected BaseFont baseFont;
    protected Font fontFooter;
    protected Font fontGeneralText;
    protected Font fontLabelText;
    protected Font fontBoldLabelText;
    protected Font fontBoldText;
    protected Font fontSpace;
    protected Font fontLargeBoldText;

    protected int language;
    protected bool useLogo = false;
    protected bool usePageNumbers = false;
    protected bool usePrintDate = false;
    protected const string PRINT_FULLDATE_FORMAT = "dd.MM.yyyy HH:mm";
    protected const string PRINT_DATE_ONLY_FORMAT = "dd.MM.yyyy";

    protected Rectangle pagesize = PageSize.A4;
    protected float marginLeft = 80;
    protected float marginRight = 35;
    protected float marginTop = 40;
    protected float marginBottom = 40;

    private MemoryStream PDFStream { get; set; } = new MemoryStream();
    private DateTime printDate;

    public BaseReport(int language = Languages.DE, bool landscape = false)
    {
        this.language = language;
        if (landscape)
        {
            pagesize = pagesize.Rotate();
        }
    }

    public byte[] GenerateReport()
    {
        CultureInfo cultureBefore = Resources.Culture;
        try
        {
            Resources.Culture = SelectCultureForLangauge();
            PrepareReport();
            document = new Document(pagesize, marginLeft, marginRight, marginTop, marginBottom);
            BuildFonts();
            OpenDocument();
            PrepareDocument();
            GenerateContent();
            document.Close();
            return PDFStream.GetBuffer();
        } finally
        {
            Resources.Culture = cultureBefore;
        }
    }

    public void GenerateReport(string filename)
    {
        byte[] report = GenerateReport();
        using (FileStream f = new FileStream(filename, FileMode.Create))
        {
            f.Write(report, 0, report.Length);
        }
    }

    protected CultureInfo SelectCultureForLangauge()
    {
        string languageCode = GetLanguageCode();
        return CultureInfo.GetCultureInfo(languageCode);
    }

    protected string GetLanguageCode()
    {
        string languageCode = string.Empty;
        switch (language)
        {
            case Languages.FR: languageCode = "FR"; break;
            case Languages.IT: languageCode = "IT"; break;
            case Languages.EN: languageCode = "EN"; break;
            default: languageCode = "DE"; break;
        }

        return languageCode;
    }

    protected virtual void PrepareReport() { }

    protected virtual void PrepareDocument() { }

    protected abstract void GenerateContent();

    private void BuildFonts()
    {
        baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
        fontFooter = FontFactory.GetFont(FontFactory.HELVETICA, 11, Font.ITALIC, BaseColor.DARK_GRAY);
        fontGeneralText = FontFactory.GetFont(FontFactory.HELVETICA, 11, Font.NORMAL, BaseColor.BLACK);
        fontLabelText = FontFactory.GetFont(FontFactory.HELVETICA, 8.5f, Font.NORMAL, BaseColor.BLACK);
        fontBoldLabelText = FontFactory.GetFont(FontFactory.HELVETICA, 8.5f, Font.BOLD, BaseColor.BLACK);
        fontBoldText = FontFactory.GetFont(FontFactory.HELVETICA, 11, Font.BOLD, BaseColor.BLACK);
        fontSpace = FontFactory.GetFont(FontFactory.HELVETICA, 3.5f, Font.NORMAL, BaseColor.BLACK);
        fontLargeBoldText = FontFactory.GetFont(FontFactory.HELVETICA, 17, Font.BOLD, BaseColor.BLACK);
        GetFontIfAvailable();
    }

    private void GetFontIfAvailable()
    {
        string fileName = "IF_Rg";
        try
        {
            baseFont = LoadFontFromFile(fileName, true);
            fontFooter = new Font(baseFont, 11, Font.ITALIC, BaseColor.DARK_GRAY);
            fontGeneralText = new Font(baseFont, 11, Font.NORMAL, BaseColor.BLACK);
            fontLabelText = new Font(baseFont, 8.5f, Font.NORMAL, BaseColor.BLACK);
            fontBoldLabelText = new Font(baseFont, 8.5f, Font.BOLD, BaseColor.BLACK);
            fontBoldText = new Font(baseFont, 11, Font.BOLD, BaseColor.BLACK);
            fontSpace = new Font(baseFont, 3.5f, Font.NORMAL, BaseColor.BLACK);
            fontLargeBoldText = new Font(baseFont, 17, Font.BOLD, BaseColor.BLACK);
        } catch (FileNotFoundException)
        {
            LogWrapper.Warn("Font not found - using default.");
        }

    }

    protected BaseFont LoadFontFromFile(string fileName, bool embedded)
    {
        string fontPath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\" + fileName + ".ttf";
        if (File.Exists(fontPath))
        {
            return BaseFont.CreateFont(fontPath, BaseFont.WINANSI, embedded);
        }
        else
        {
            throw new FileNotFoundException($"Fontfile {fileName} was not found!");
        }
    }

    protected Image HeaderLogo()
    {
        Image logo = Image.GetInstance(Resources.logo, BaseColor.BLACK);
        // TODO msc pick logo from debitor
        logo.ScaleToFit(100f, 100f);
        return logo;
    }

    protected void OpenDocument()
    {
        writer = PdfWriter.GetInstance(document, PDFStream);
        writer.PageEvent = this;
        writer.SetFullCompression();
        document.Open();
        contentByte = writer.DirectContent;
    }

    protected void AddLabelAt(string label, float posX, float posY)
    {
        PdfContentByte cb = writer.DirectContent;
        ColumnText column = new ColumnText(cb);
        column.SetText(new Paragraph(label + NEWLINE, fontLabelText));
        column.SetSimpleColumn(posX, 20, posX + 200, posY);
        column.Go();
    }

    protected void AddLabelOnMargin(string label)
    {
        AddLabelAt(label, document.LeftMargin - 40, writer.GetVerticalPosition(false));
    }

    protected Phrase ParaLine(string Text, Font textfont)
    {
        return new Phrase(Text, textfont);
    }

    public override void OnOpenDocument(PdfWriter writer, Document document)
    {
        if (usePageNumbers)
        {
            totalPageNoTemplate = writer.DirectContentUnder.CreateTemplate(50, 50);
        }
        if (usePrintDate)
        {
            printDate = DateTime.Now;
        }
    }

    public override void OnStartPage(PdfWriter writer, Document document)
    {
        if (useLogo || (document.PageNumber > 1 && !string.IsNullOrEmpty(kundeHeader)))
        {
            PdfContentByte canvas = writer.DirectContentUnder;
            canvas.SaveState();
            if (document.PageNumber > 1 && !string.IsNullOrEmpty(kundeHeader))
            {
                //showtextaligned only shows a single line
                //therefor the header needs to be split and its parts need to be added seperately
                string[] headerParts = kundeHeader.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                Phrase header = new Phrase(kundeHeader, fontLabelText);
                ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT,
                        ParaLine(headerParts[0], fontLabelText),
                        document.LeftMargin,
                        document.Top + 30, 0);
                ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT,
                        ParaLine(headerParts[1], fontLabelText),
                        document.LeftMargin,
                        document.Top + 20, 0);
            }
            if (useLogo)
            {
                Image logo = HeaderLogo();
                logo.SetAbsolutePosition(marginLeft - 17.5f, document.Top + document.TopMargin - 50);
                document.Add(logo);
            }
            canvas.RestoreState();
        }
    }

    public override void OnEndPage(PdfWriter writer, Document document)
    {
        if (usePageNumbers || usePrintDate)
        {
            PdfContentByte canvas = writer.DirectContentUnder;
            canvas.SaveState();
            if (usePageNumbers)
            {
                // adds current page number to the footer section of the document
                int pageN = writer.PageNumber;
                string text = Resources.LabelSeite + SPACE + pageN + "/";
                float len = fontLabelText.BaseFont.GetWidthPoint(text, fontLabelText.Size);
                ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT,
                        ParaLine(text, fontLabelText),
                        document.LeftMargin,
                        document.Bottom - 10, 0);
                // adds template to fill in total page number (see OnCloseDocument method)
                canvas.AddTemplate(totalPageNoTemplate, document.LeftMargin + len, document.Bottom - 10);
                lastPageNumber = pageN;
            }
            if (usePrintDate)
            {
                // adds the printdate to the footer secdtion of the document
                string dateFormatted = printDate.ToString(PRINT_FULLDATE_FORMAT);
                ColumnText.ShowTextAligned(canvas, Element.ALIGN_RIGHT,
                        ParaLine(dateFormatted, fontLabelText),
                        document.Right,
                        document.Bottom - 10, 0);
            }
            canvas.RestoreState();
        }
    }

    public override void OnCloseDocument(PdfWriter writer, Document document)
    {
        if (usePageNumbers)
        {
            // fills in the total page number to the prepared template in the footer section of the document
            string text = lastPageNumber + "";
            float widthPoint = fontLabelText.BaseFont.GetWidthPoint(text, fontLabelText.Size);
            totalPageNoTemplate.Width = widthPoint;
            ColumnText.ShowTextAligned(totalPageNoTemplate, Element.ALIGN_LEFT, ParaLine(text, fontLabelText), 0, 0, 0);
        }
    }

A: iTextSharp-generated PDFs now cause Save dialog in Adobe Reader X
I had to switch PDFStream.GetBuffer() with PDFStream.ToArray(); problem solved.


text:
Q: What parts of speech is "Like" in this Sentence This is a line from Ruskin Bond's short story, "Eyes Have It."
—"What is it like outside?"I asked.
I am more inclined to call 'like' an adverb in this sentence but cannot figure out what should be its literal meaning. But at the very next moment discard the idea of branding it as adverb as it is used with a linking verb which always presupposes a complement in the form of adjective or noun. Any help?


text:
Q: DC voltmeter and full wave bridge rectifier in Proteus I am trying to measure the average voltage on a resistor but I see always zero like below:

I connected ground but the result was the same.
When I add a parallel capacitor in R1, there is no problem but otherwise I can't get a good reading. My friend tried this circuit on Multisim and there was no extreme situation like I have.


text:
Q: Inserting data into database using html forms Okay, guys. I am new at php and other server side codes.
I am able to connect successfully to my server and database. I am able to use the Insert data code to insert data with values. However, when I enter the values into the code, those are the values that get sent to the table. How do I use HTML forms to use custom data entered into text areas to show up in my database table?
For example,
when I use VALUE ('jon', 'doe') it sends those values into the database instead of the text I enter into the text areas. How do I fix this to say, enter my actual name when I fill out a web form?
Basically, I am asking how I would use web forms to manipulate data into the database. I'm so confused

A: You are encouraged to use PDO (or at least mysqli) prepared statements from the first day. This way you can relatively safely insert data into your SQL statements. Please read the official manual. Be aware that PDO will emulate prepared statements by default. That can result in a security hole. Therefore you should request to switch of emulated prepared statements.
$options       = [PDO::ATTR_EMULATE_PREPARES => false];
$pdoConnection = new PDO($dsn, $user, $password, $options);

You can then create prepared SQL statements like:
SELECT `id`, `value` FROM `myTable` WHERE `value` = ?;

As long as the driver supports real prepared statements, the "?" will not be substituted directly, data will be separately sent after the statement. This avoids SQL injection via encoding attacks.
Please read documentation, try things out and come back if you have concrete questions.

A: You can build a form on one page that sends input to another page. For example:
index.php:
<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <form method="POST" action="action.php">
      <input type="text" name="message">
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

Your php/MySQL code would then exist in a page called action.php which would be located in the same directory as index.php.
action.php:
<?php
$message = $_POST['message'];
/*now you can use the $message variable in your MySQL code to insert
it into the database*/
?>

Please remember to used prepared statements and to bind your parameters in your MySQL code to prevent hacker attacks (like sql injection).
Let me know if that worked for you!

A: When creating a form in html you may define the following input:
<input type="text" name="my_input">

To access the content of this particular input, after submission of the form. Use depending on what method your form is using $_GET['my_input'] or $_POST['my_input'] to retrieve the value entered in the form input.
Try to play arround with this example:
<form action="" method="get">
    <input type="text" name="field" value="<?php print $_GET['field']; ?>">
    <input type="submit" name="s" value="Go!">
</form>
<?php

if (isset($_GET['s'])) {
    print "value of the text field: ".$_GET['field'];
}


text:
Q: Addition on well ordered sets not-commutative by showing $[0,1) +_o \mathbb{N} =_o \mathbb{N} \neq_o \mathbb{N} +_o [0,1)$ My goal is to show that addition on well ordered sets are non-commutative by showing that,
$[0,1) +_o \mathbb{N}  =_o \mathbb{N} \neq_o \mathbb{N} +_o [0,1)$
Some definitions (let A and B be posets)

*

*$[n,m) =_{df} \{k\in \mathbb{N}: n \leq k \land k < m\}$

*$A =_o B \Leftrightarrow_{df} \exists \ \phi : A \to B $ such that
$\phi$ is bijective and preserves order

*$A+_o B =_{df} \{0\}\times A \cup \{1\}\times B$ with $(i,x),(j,y)
   \in A+_o B$, $(i,x) \leq_{A+_o B} (j,y) \Leftrightarrow_{df} i < j
   \lor [i=j=0 \land x \leq_A y] \lor [i=j=1 \land x \leq_B y] $
I also take for granted (ie proved earlier) that sum of two wosets is a woset
I think I've found a order preserving bijection:
$\phi:[0,1)  +_o \mathbb{N} \to\mathbb{N} $ by $\phi((0,0)) = 0,\ \phi((1,n)) = n+1$
$\phi(x) =\phi(y) \implies \phi(x) = 0 =\phi(y) = 0 \implies x = (0,0) = y$
or
$\phi(x) =\phi(y) \implies \phi(x) = \phi((0,n)) = \phi((0,m)) \implies n + 1 = m+1 \implies x = y $ and in my mind it's clearly onto $\mathbb{N}$ since every natural number $n$ gets hit by either $(0,0)$ or $(1,n-1)$.
Order preserving.
Let $(i,n), (j,m) \in [0,1)  +_o \mathbb{N} $ such that $(i,n) \leq_{[0,1)  +_o \mathbb{N}} (j,m)$

*

*Case 1.) $i< j$,
$(i,n) \leq_{[0,1)  +_o \mathbb{N}} (j,m) \implies (i,n) = (0,0)
   \land (j,m) = (1,m) \implies \phi((i,n)) = \phi((0,0)) = 0
   \leq_{\mathbb{N}} \phi((j,m)) = \phi((1,m)) = m+1
   \geq_\mathbb{N} 1  $

*Case 2.) $i = j = 0$
If $i = j = 0$ then $(i,n) \leq_{[0,1)  +_o \mathbb{N}} (j,m)
   \implies (i,n) = (j,m) = (0,0) \implies \phi((i,n)) = \phi((j,m)) = 0
   \implies \phi((i,n))  \leq_{\mathbb{N}}\phi((j,m)) $   Since $[0,1) =
   \{0\}$

*Case 3.) $i = j = 1$
If $i = j = 0$ then $(i,n) =(1,n) \leq_{[0,1)  +_o \mathbb{N}}
   (j,m)=(1,m)$ then we have that $n \leq_{\mathbb{N}} m  \implies
   \phi((i,n)) = \phi((1,n)) = n+1 \leq_{\mathbb{N}} \phi((i,m)) =
   \phi((1,m)) = m+1  $
Here I draw the conclusion that $[0,1) +_o \mathbb{N}  =_o \mathbb{N} $
But now to the part which I find very challenging. I have to show that $\mathbb{N} \neq_o \mathbb{N} +_o [0,1)$
I think I can find a bijection $\pi: \mathbb{N} \to \mathbb{N} +_o [0,1)$ by $\pi(0) = (1,0), \pi(n) = (0,n+1)$ but I can't get it to "break" with the order preserving.
I've also tried to play around with just some general bijection but without any luck.
My idea is to find a bijection $\pi: \mathbb{N} \to \mathbb{N} +_o [0,1)$ (maybe a general one if that might work) assume or explicitly show that is has order. take two elements $a,b$ from $\mathbb{N} +_o [0,1)$ such that $a \leq_{\mathbb{N} +_o [0,1)} b$ and then map them to $\mathbb{N}$ thus we have $\pi(a),\pi(b) \in \mathbb{N} $ Since every element in  $\mathbb{N}$ is mapped from some element in $[0,1) +_o \mathbb{N}$ we can rewrite $\pi(a) =\phi((i,n)),\pi(b) =\phi((j,m))$ and then deriving a contradiction so that $\pi$ can't preserve order.
This at best a very very dirty sketch and I have several problems.
By intuition I refuse to believe that there is no bijective mapping from $\leq_{\mathbb{N} +_o [0,1)}$  to $\mathbb{N}$.
If I find a bijection and derive the contradiction, I have to show that this bijection is unique, right? I find this to be quite impossible to be honest.
Or am I going about this the wrong way, is it specifically the mapping of strict ordering that fails in some way I'm missing? Any help would be highly appreciated.

A: To show that $\mathbb{N} \neq_o \mathbb{N} +_o [0,1)$. We'll show by contradiction. Suppose that it exists an order preserving bijection $$\rho: \mathbb{N} \longrightarrow \mathbb{N} +_o [0,1).$$ Then, it must exist an element $m\in \mathbb{N} $ such that $\rho(m)=(1,0)$. But as $\mathbb{N}$ doesn't have a maximum element, we can affirm  that $m+1$ exists. The image of $m+1$ would have the form $$\rho(m+1)=(0,x), x\in \mathbb{N}$$ and so $\rho(m+1)\leq_{\mathbb{N} +_o [0,1)}\rho(m)$, which is a contradiction because $\rho$ is order preserving.


text:
Q: CSS Translate causes typo to break I'm trying to add an effect to a menu I use on a website.
The effect is the first one of the list with a color change added: http://tympanus.net/Development/CreativeLinkEffects/
But when I try to apply it to my case I have a weird problem that happens on the not hovered element. You can see that the elements that are not hovered change opacity and font-size during the hover on an element.
I added the demo here :

a{
    text-decoration:none;
}

/* Effect 15: scale down, reveal */
 .cl-effect-15 a {
    color: #FFF;
    text-shadow: none;
}
.cl-effect-15 a::before {
    margin-right: 10px;
    content:'[';
    -webkit-transform: translateX(20px);
    -moz-transform: translateX(20px);
    transform: translateX(20px);
}
.cl-effect-15 a::after, .cl-effect-15 a::before {
    display: inline-block;
    opacity: 0;
    -webkit-transition: -webkit-transform 0.3s, opacity 0.2s;
    -moz-transition: -moz-transform 0.3s, opacity 0.2s;
    transition: transform 0.3s, opacity 0.2s;
    font-size: 12px;
}
.cl-effect-15 a::after {
    margin-left: 10px;
    content:']';
    -webkit-transform: translateX(-20px);
    -moz-transform: translateX(-20px);
    transform: translateX(-20px);
}
.cl-effect-15 a:hover::before, .cl-effect-15 a:hover::after, .cl-effect-15 a:focus::before, .cl-effect-15 a:focus::after {
    opacity: 1;
    -webkit-transform: translateX(1px);
    -moz-transform: translateX(0px);
    transform: translateX(1px);
    font-size: 14px;
}
.totblockhtml.html_2 {
    padding-bottom:10px;
    margin-bottom:0px;
}
.totblockhtml.html_2 {
    margin-bottom: 0px;
    padding-bottom: 9px;
    padding-top: 4px;
    width: 100%;
    float: left;
    background: none repeat scroll 0 0 #282F47;
    margin-top: -20px;
    background-image: url(../img/BlueJean.svg);
}
.totblockhtml.html_2 .block_content {
    text-align:center;
    color:#ababab;
    padding-top: 5px;
}
.totblockhtml.html_2 ul li {
    display: inline-block;
    margin-left: 70px;
    font-size: 14px;
    font-family:"trajanpro_regular";
    text-transform: uppercase;
    letter-spacing: 1px;
    position: relative;
}
.totblockhtml.html_2 ul li:first-child {
    margin-left:0px;
}
.totblockhtml.html_2 ul li a {
    color: #9099AF;
    font-size: 11px;
    font-family:"Cinzel";
    text-transform: uppercase;
    letter-spacing: 2px;
    -webkit-transition: color 0.5s ease;
    -moz-transition: color 0.5s ease;
    -ms-transition: color 0.5s ease;
    -o-transition: color 0.5s ease;
    transition: color 0.5s ease;
}
.totblockhtml.html_2 ul li a:hover {
    text-decoration:none;
    color: #fff;
}

Rechercher

Vendre

Conseils

A: Here's the code changing the opacity:
.cl-effect-15 a::after, .cl-effect-15 a::before {
    -webkit-transition: -webkit-transform 0.3s, opacity 0.2s;
    -moz-transition: -moz-transform 0.3s, opacity 0.2s;
    transition: transform 0.3s, opacity 0.2s;
}

and here's the one changing the font-size:
.cl-effect-15 a:hover::before, .cl-effect-15 a:hover::after, .cl-effect-15 a:focus::before, .cl-effect-15 a:focus::after {
    font-size: 14px;
}

I set font-size to 12px and opacity to 1, check it out here: jsFiddle


text:
Q: How should i design a server application in java I'm developing a java application which reads a continuously written a file of recordsets (800.000.000 records per month), bulk reading data from files and calls a web service to read also data. These data should be stored in a database (a huge database). The next feature I'm going to add is a web service, which can be called from other applications to add or receive (predefined queries [maybe the running time of the method/query is about 1 or 2 minutes]) records. Additionally to web service I want other application written in c#, c++, etc. to be able to connect (I thought about protocol buffers or apache thrift).
And at least it should offer a way to administrate the application (i though about a web site)
In my opinion it should be a server application. But should I develop a server on my own (opening sockets, etc.), a Java EE or are there any other "server frameworks" (may be a combination of jetty, sockets, etc.)?

A: just divide and conquer:
One solution can be using tomcat:
function 1) create a thread which reads the file. then you can define a context listener within the web.xml
function 2) Look at java.util.Timer or, for more robust functionality, look at a third party product like Quartz.
function 3a) There are a lot of WS frameworks availabe. Use google to find tutorials
function 3b) Google for Asynchronous Web Service or Asynchronous Support in Servlet
function 4) AFAIK Thrift has a build-in TServlet. I think Tomcat and Google Protokoll Buffers is also possible
function 5) Offering web sites is one of tomcats main functions

A: If it's going to be something that users can deploy -- a product that clients will buy, or an open-source tool for people to download -- then I would suggest that the best approach is to develop it in a container-agnostic manner, as far as possible.
By which I mean, focus on what the application does, and abstract things like launching and connecting to services out.  If you do that right, you can then write container-specific elements, to allow your users to deploy the application in, for example, their choice of app server, or as a standalone application.
On the other hand, if it's for an in-house project, where you fully control all aspects of how the application will be used, you can avoid some or all of the above; though you probably would be better to use that kind of abstraction in any case.
Certainly Eric Leschinski is right in that you don't want to develop something like Tomcat or IIS.


text:
Q: iOS set text color in a view's drawrect I have code that does custom rendering inside of a drawRect method in a UIView subclass. I am trying to render text out using [NSString drawInRect] which works great, however it always shows up in white. After much googling and browsing SO I have no been able to find out how to change the color of a text. Any advice would be great.
Edit
Below is the snippet of code inside my drawRect implementation
if(self.state != UIControlStateHighlighted)
{
    CGContextSaveGState(context);
    CGContextSetFillColorWithColor(context, color);
    CGContextSetShadowWithColor(context, CGSizeMake(0, 2), 3.0, shadowColor);
    CGContextAddPath(context, path);
    CGContextFillPath(context);
    [title drawInRect:rect withFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
    CGContextRestoreGState(context);
}

A: Before drawing text, you have to set the color. Try this,
[[UIColor blackColor] set];
[title drawInRect:rect withFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];

A: Have you tried changing the current fill color?
[[UIColor redColor] setFill];
[string drawInRect:rect withFont:font];


text:
Q: Nullpointerexception attempt to read from null array I made a chart on my android app with MPAndroidChart.
I'm extracting data from my RoomDB.
private void reportAnnuale() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            ArrayList<BarEntry> barEntries = new ArrayList<>();
            ArrayList<String> labelsNames = new ArrayList<>();
            int[] colors = new int[12];

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -11);
            int month = calendar.get(Calendar.MONTH);
            int year = calendar.get(Calendar.YEAR);
            calendar.set(year, month, 1, 0, 0, 0);
            Locale.setDefault(Locale.ITALIAN);

            int somma = 0;
            int num = 0;
            for (int i = 0; i < 12; i++) {
                colors[i] = R.color.white;
                Long inizio = (calendar.getTimeInMillis() / 1000) * 1000;
                calendar.add(Calendar.MONTH, +1);
                Long fine = (calendar.getTimeInMillis() / 1000) * 1000;
                int media = DB.getInstance(getContext()).getValutazioneDao().mediaIntervallo(inizio, fine);
                if (media == 0) num--;
                if (media <= 40 && media > 0) colors[i] = R.color.red;
                if (media > 40 && media <= 70) colors[i] = R.color.yellow;
                if (media > 70) colors[i] = R.color.green;
                barEntries.add(new BarEntry(i, media));
                labelsNames.add("");
                somma += media;
                num++;
            }
            int finalNum = num;
            int finalSomma = somma;

            if(finalNum ==0) return;
            BarDataSet barDataSet = new BarDataSet(barEntries, "Media degli utltimi 12 mesi: " + (finalSomma / finalNum) + " %");
            barDataSet.setColors(colors, context);
            Description description = new Description();
            description.setText("");
            barAnnuale.setDescription(description);
            BarData barData = new BarData(barDataSet);
            barAnnuale.setData(barData);
            XAxis xAxis = barAnnuale.getXAxis();
            xAxis.setValueFormatter(new IndexAxisValueFormatter(labelsNames));
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM_INSIDE);
            xAxis.setDrawGridLines(false);
            xAxis.setDrawAxisLine(false);
            xAxis.setGranularity(1f);
            xAxis.setLabelCount(labelsNames.size());
            xAxis.setLabelRotationAngle(270);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    barAnnuale.invalidate();
                }
            });
        }
    }).start();
}

Everything works perfectly but the app rarely crashes due to this exception, the exception refers to external code, no line of my code is reported, log:
java.lang.NullPointerException: Attempt to read from null array
    at com.github.mikephil.charting.renderer.BarChartRenderer.drawDataSet(BarChartRenderer.java:138)
    at com.github.mikephil.charting.renderer.BarChartRenderer.drawData(BarChartRenderer.java:82)
    at com.github.mikephil.charting.charts.BarLineChartBase.onDraw(BarLineChartBase.java:237)
    at android.view.View.draw(View.java:22513)
    at android.view.View.updateDisplayListIfDirty(View.java:21376)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at android.view.View.updateDisplayListIfDirty(View.java:21367)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at android.view.View.draw(View.java:22517)
    at android.view.View.updateDisplayListIfDirty(View.java:21376)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at android.view.View.updateDisplayListIfDirty(View.java:21367)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at android.view.View.draw(View.java:22517)
    at android.widget.ScrollView.draw(ScrollView.java:1833)
    at android.view.View.updateDisplayListIfDirty(View.java:21376)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at android.view.View.updateDisplayListIfDirty(View.java:21367)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at androidx.constraintlayout.widget.ConstraintLayout.dispatchDraw(ConstraintLayout.java:1975)
    at android.view.View.updateDisplayListIfDirty(View.java:21367)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at android.view.View.updateDisplayListIfDirty(View.java:21367)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at android.view.View.updateDisplayListIfDirty(View.java:21367)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at android.view.View.updateDisplayListIfDirty(View.java:21367)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at android.view.View.updateDisplayListIfDirty(View.java:21367)
    at android.view.View.draw(View.java:22238)
    at android.view.ViewGroup.drawChild(ViewGroup.java:4551)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:4310)
    at android.view.View.draw(View.java:22517)
    at com.android.internal.policy.DecorView.draw(DecorView.java:819)
    at android.view.View.updateDisplayListIfDirty(View.java:21376)
    at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:559)
    at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:567)
    at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:651)
    at android.view.ViewRootImpl.draw(ViewRootImpl.java:4274)
    at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3979)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3240)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:2066)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8496)
E/AndroidRuntime:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1076)
    at android.view.Choreographer.doCallbacks(Choreographer.java:897)
    at android.view.Choreographer.doFrame(Choreographer.java:826)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1061)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:236)
    at android.app.ActivityThread.main(ActivityThread.java:8057)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)

The strangest thing is that the exception rarely occurs...
Why???? Thank you all!!!!


text:
Q: Why cant we call nonstatic method from static method? I have a class Program. Here it has main method.It is static method. I created a simple
getAllSum method to return sum of three values.But, if i remove static keyword then i get error as:
**Cannot make a static reference to the non-static method getALlsum(int, int, int) from the type Program
**

If I am calling a function from static method to non static method then,why it is necessary to become non static method to be static?
Static method I have learned about them is that:

*

*Can be called from class name instead of using object.

*Each object shares the same variable.

But,I am getting confuse why cant we call a nonstatic function from static function?What is the reason behind this?
public class Program {

    public static void main(String[] args) {
        int l=getALlsum(1,2,3);
        System.out.println(l);
    }

    public static int getAllSum(int a,int b,int c) {
        return (a+b+c);
    }

    }

A: You cannot call non-static methods or access non-static fields from main or any other static method, because non-static members belong to a class instance, not to the entire class.
You need to make an instance of your class, and call your method


text:
Q: RDLC reports are not respecting my page height option I am passing in this DeviceInfo to the report:
<DeviceInfo>
  <OutputFormat>Word</OutputFormat>
  <PageWidth>11in</PageWidth>
  <PageHeight>8.5in</PageHeight>
  <MarginTop>1in</MarginTop>
  <MarginLeft>0.5in</MarginLeft>
  <MarginRight>0.5in</MarginRight>
  <MarginBottom>1in</MarginBottom>
</DeviceInfo>

However when the report renders (as Word or PDF), the page size is 11 by 11 inches, rather than 11 by 8.5 (landscape). Why is this? How can I get the report to render with the proper size?
Here is where I render the report:
byte[] bytes = Report.Render( // Report is an instance of the Microsoft.Reporting.WebForms.LocalReport class
    reportType,
    deviceInfo, // this contains the XML above
    out mimeType,
    out encoding,
    out fileNameExtension,
    out streams,
    out warnings);

A: In the Report builder or Visual Studio you have also to set the Layout of the Report to Landscape so it will know how to render

A: It looks like the report page size was not being initialized properly, so I did so:
var page = report.Page;

page.LeftMargin = LeftMargin;
page.RightMargin = RightMargin;

page.TopMargin = TopMargin;
page.BottomMargin = BottomMargin;

// I added these next two lines
page.PageWidth = PageWidth;
page.PageHeight = PageHeight;


text:
Q: How to add a prefix to a WordPress post preview url? I need to remove any query parameters from the WordPress post preview URL.
I need to access https://www.domain.com/prefix/12345 and see the same post preview I would see on https://www.domain.com/?p=12345&preview=true
It can not redirect, the URL in the browser must still be https://www.domain.com/prefix/12345
As an alternative, adding a prefix to the original WordPress post preview url would also be enough:
https://www.domain.com/previx/?p=12345&preview=true
How can I achieve one of these without changing the URLs of the published posts?
The motivations is that I need a URL with a prefix to create a bypass route on CloudFlare Workers.
ps.: Cloudflare Page rules are different than Cloudflare Workers Routes. The Worker Routes does not support query parameters on it.


text:
Q: crypto/bcrypt: hashedPassword is not the hash of the given password I encrypt user's password and save to db. Then to user login, compare hashed password and plain password, I'm getting crypto/bcrypt: hashedPassword is not the hash of the given password error. Whats wrong ?
func encryptPassword(password string) (string, error) {
    bytePass := []byte(password)
    hashedPassword, err := bcrypt.GenerateFromPassword(bytePass, bcrypt.DefaultCost)
    if err != nil {
        log.Printf("ERROR:EncryptPassword: %s", err.Error())
    }
    return string(hashedPassword), err
}

func (i *Impl) Register(user User) bool {
    hashedPass, err := encryptPassword(user.Password)
    if err != nil {
        return false
    }

    user.Password = hashedPass

    if err := i.DB.Create(&user).Error; err != nil {
        log.Printf("ERROR:Register: %s", err.Error())
        return false
    }
    return true
}

func (i *Impl) Login(email string, password string) (User, error) {
    var user User
    i.DB.Where("email = ?", email).First(&user)

    err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
    if err != nil {
        log.Printf("ERROR:Login: %s", err.Error())
        return User{}, err
    }

    return user, err
}

A: My bet is that user.Password is empty in your Register function before you pass it to encryptPassword thus leading to hashes on empty passwords like the one you provided ($2a$10$rqHJJTHsxMbtX/5ZjG1mFuWyYbUDW1PLbfwQRN0uChwes38c/0m3e).

A: I cannot tell which is which, but in your compare function, ensure that you have the variables in the right place.
bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
           Must be the already hashed PW ^              ^ Plain Text Password to compare

Also ensure you're actually getting something to hash, you could be getting a blank password but not realizing it because the hash will still look full.

A: My mistake was thinking that it compared two bcrypt hashedpasswords, rather than a hashedpassword and your unencrypted password converted to binary -- hope that helps someone out there!


text:
Q: Is there a way to save password to the browser with Flash sites? Is there a way to prompt the browser to save a password on a Flex or Flash app? And on returning to a webpage retrieving that login (the same behavior as HTML sites have)? I'm open to creative solutions...
~~~ UPDATE ~~~~~~~~~~~~
I should have mentioned I'm trying to avoid the SharedObject route. This is because of features like FireFox' and Chromes' sync feature which makes logins and cookies portable across devices. I'm thinking about copying username and password to HTML text inputs and checking for their existence on HTML page load. What do you think?

A: No "creative" solutions required. Just use a local SharedObject.
Write userData to disk:
var so:SharedObject = SharedObject.getLocal("my_user_data", "/", false);
so.data.user = userData;
so.flush(90000);
so.close();

Read userData from disk:
var so:SharedObject = SharedObject.getLocal("my_user_data", "/", false);
var userData:UserData;

if (so.data.hasOwnProperty('user'))
    userData = so.data.user as UserData;

Now fill the TextInputs with the contents of userData


text:
Q: Criando array multidimensional a partir de query a BD MySQL Tenho o seguinte problema:
Tenho uma tabela num banco de dados MySQL e em um trecho do código eu preciso fazer com que o conteúdo recuperado por uma query feita a este banco seja armazenada em um array multidimensional/matriz em php. Os valores das duas colunas consultadas estão relacionadas e eu não consigo imaginar em outra maneira de manter a relação entre os itens de maneira prática sem que estejam armazenados em uma variável de estrutura semelhante à tabela do banco de dados (no caso, o array multidimensional).
TL;DR; Quero armazenar o conteúdo de duas colunas de uma tabela SQL em um array multidimensional, de modo que eu consiga acessar o array com
'array["valor1_da_tabela"]= "valor1,valor2,valor3,..."
 array["valor2_da_tabela"]= "valor1,valor2,valor3,..."
 array["valor3_da_tabela"]= "valor1,valor2,valor3,..."
'

Detalhe: sugestões de solução devem ser feitas usando PDO. Tudo isto é para poder fazer um esquema de combobox/dropdown em javascript em cascata em uma página do portal. E os itens destes combobox/dropdown são todos valores armazenados nesta tabela SQL. O primeiro funciona tranquilo. Já o segundo que depende do que foi selecionado no primeiro não está saindo por causa  da ordem de execução dos códigos client e server side. Preciso armazenar estas duas colunas inteiras com valores string para facilitar a tarefa de implementação dos combobox/dropdown em cascata dinâmicos. Se tiverem sugestões quanto a isso, também agradeço.
Agradeço a atenção dos senhores.
EDIT: Este é um trecho de uma parte do projeto que faz algo parecido só que apenas para uma coluna. O que eu tentei fazer foi adaptar este trecho para atender a minha necessidade de criar um array multidimensional ao invés de um array comum.
<?php
    ini_set('default_charset','UTF-8');
    require("../dbconnect.inc.php");
    $vet = array();
    $assunto = array();
    $jsArray = "";
    $sql = "SELECT distinct assunto
                FROM arquivos";

    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $vet = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach($vet as $vet_assunto){
    array_push($assunto, $vet_assunto['assunto']);
}
    for($i=0;$i<sizeof($assunto);$i++){
    $jsArray = $jsArray . $assunto[$i] . ",";
    }
    $jsArray = chop($jsArray, ",");
    require("../dbdisconnect.inc.php");
?>

Este trecho é uma das tentativas:
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $vet = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach($vet as $vet_assunto){
        array_push($assunto['assunto'], $vet_assunto['assunto']);
        array_push($assunto['assunto']['aula'], $vet_assunto['aula']);
    }

        require("../dbdisconnect.inc.php");
    ?>

Exemplo das duas colunas em questão na tabela do banco de dados:
Assunto|aula

teste1 | 1
teste1 | 2
teste2 | 1
teste2 | 2
teste2 | 3

E eu gostaria que no array ficasse organizado da seguinte maneira:
                  Output
   array[teste1]= {1,2}
   array[teste2]= {1,2,3}

array[teste1][1]= {2}
array[teste2][2]= {3}


text:
Q: Sequential promise loop with delay I'm attempting to load an array of "requests" sequentially each one separated by a delay.
I'm using promises but for some reasons I'm having issues with the requests being executed in parallel instead of in sequence.
I wrote some test code as per below. It works! It makes the request, processes it, timesOut for 3 second and goes to the second request.

var batches = [of_objects];
var sequence = Promise.resolve();
var self = this;

sequence
    //Create request for first batch
    .then( function(){
        return self._createRequestPromise(batches[0]);
    })
    //callback so we can update, returns nothing
    .then(callback)
    //add 3 sec timeout before next request
    .then(function(){
        return new Promise(function (resolve, reject){
            setTimeout(resolve, 3000);
        });
    })
    //Create request for second batch
    .then( function(){
        return self._createRequestPromise(batches[1]);
    })
    //callback so we can update, returns nothing
    .then(callback)
    //add 3 sec timeout before next request
    .then(function(){
        return new Promise(function (resolve, reject){
            setTimeout(resolve, 3000);
        });
    });

return sequence;

BUT, as soon as I try to put it any sort of loop, my requests are firing all at the same time. And the timeout calls happen after.
I'm not sure what I'm doing wrong, or misunderstanding.

//object I need to use to construct requests
var batches = [of_objects];
var sequence = Promise.resolve();
var self = this;

batches.forEach(function(batch){
    sequence
    //Function returns promise
    .then( function(){
        return self._createRequestPromise(batch); //this runs first 5x
    })
    //callback so we can update, returns nothing
    .then(callback)
    //add 3 sec timeout before next request
    .then(function(){
        return new Promise(function (resolve, reject){
            setTimeout(resolve, 3000); //this runs after 5x
        });
    });
});
return sequence;

A: The issue is that you're not updating sequence to include any of the successive operations, so all of them are chaining off of that original resolved promise. There's nothing there to delay any of them, so they execute right away.
You should be able to remedy this simply by updating the sequence variable on every loop, so you're chaining off the end of the chain:
//object I need to use to construct requests
var batches = [of_objects];
var sequence = Promise.resolve();
var self = this;

batches.forEach(function (batch){
    sequence = sequence            // <-- here
        //Function returns promise
        .then( function(){
            return self._createRequestPromise(batch); //this runs first 5x
        })
        //callback so we can update, returns nothing
        .then(callback)
        //add 3 sec timeout before next request
        .then(function(){
            return new Promise(function (resolve, reject){
                setTimeout(resolve, 3000); //this runs after 5x
            });
        });
});

return sequence;

Personally, I try to avoid overwriting variables, so an alternate way to do this without variable reassignment is to use .reduce():
//object I need to use to construct requests
var batches = [of_objects];
var self = this;

return batches.reduce(function (last, batch){
    return last
        //Function returns promise
        .then( function(){
            return self._createRequestPromise(batch); //this runs first 5x
        })
        //callback so we can update, returns nothing
        .then(callback)
        //add 3 sec timeout before next request
        .then(function(){
            return new Promise(function (resolve, reject){
                setTimeout(resolve, 3000); //this runs after 5x
            });
        });
}, Promise.resolve());


text:
Q: Cannot run Ubuntu after installation. Black Screen I installed Ubuntu LTS 20.04 beside Windows.
When I'm running Live version by USB, it's working. But when I'm trying to run from grub, i see only black screen and my keyboard is not working also. So i cannot use Ctrl+Alt+F2 command, nomodeset also is not helping. And I cannot run Windows 10 as I have the same problem with black screen and keyboard.
I have a laptop with AMD A8-4500M CPU and GPU: AMD Radeon HD 7640G + HD 8570M Dual Graphics.
Please help!

A: I had faced the same problem before. I reinstall ubuntu again. Before installation, you need to learn the installation process from the different tutorials.


text:
Q: PHP & MySQL empty records In my database I've been getting individual records that are displayed by its own ID. In the URL is like this: site.com/index.php?id=1.  But if I write the address with an ID that does not exist (like site.com/index.php?id=3553255) it sends me to the page i use as "template", but with no data (an empty page).
How could I send a header status 404, if the record is empty or does not exist?
This is my code:
<?php

if(isset($_GET['id'])) {

$id = mysql_escape_string($_GET['d']);

include 'mysql_conexion.php';

$sql=" SELECT * FROM portfolio WHERE id='$id'";
$data=mysql_query($sql,$conexion);

while ($row=mysql_fetch_array($data)) {
      $id=$row['id'];
      $heading=$row['heading'];
 }

echo "

$heading

";

}

mysql_free_result($data);
mysql_close($conexion);

?>

Note: I tried with else and header function
"else {header ('HTTP/1.0 404 Not Found', true, 404);} exit;"  and header: location,
but did not work.
Thanks for your attention.

A: Try inputting a simple if statement that basically looks something like this :
$numberofRows = count($cars);

if ($numberofRows == 0){

echo '<meta http-equiv="refresh" content="0; url=http://example.com/" />';

}

else{
while ($row=mysql_fetch_array($data)) {
      $id=$row['id'];
      $heading=$row['heading'];
 }

echo "

$heading

";

}

mysql_free_result($data);
mysql_close($conexion);
}
?>

This will use your query to see how many rows match it. If the number is 0 it will redirect the user to what ever url is you 404 page.
Hope this helps.


text:
Q: Spring Rest Dropping Data When Returning I have a simple Spring Rest service setup to handle some JSON objects I have in a DB.  I have two applications; one looking to hold that data, and the other is looking to request/store that data locally to its DB.  The object used is in a shared Jar that both applications have access to, so they know the structure, expectations, etc.
When I run a request for the data I can see it coming in, but some of the data has been nulled out in the JSON.  I have setup breakpoints at the last return point for the source system, and when the data is there (pulled from DB) and ready to return it is intact.  Once it gets across the wire in any form via Postman or my 2nd App, some of the fields have been blanked out.
EDIT: Some code posted with specific names simplified for ease of reading
//------------------The Data "Source"------------------------------
//The source service that serves the content
@ResponseBody
@RequestMapping(value = { "/json/listObjectA" }, method = RequestMethod.GET)
public List<ObjectA> listAllObjectA() {
    List<ObjectA> allObjectA = ObjectA
            .getAll(thisApplicationContext);
    return allObjectA; //a breakpoint here shows the data as expected
    //the data in the DB is correct in source, confirmed.
}

//------------------The Requesting "Target"-----------------------------
//trying to get that data, setting up a baseURL for the service works
//when using this block of code with debuggers on, it reaches the source above.
RestTemplate rest = new RestTemplate();
ResponseEntity<ObjectA[]> sfResponse = rest.getForEntity(
coreBaseLocation+"json/listObjectA",
                ObjectA[].class);
ObjectA[] sfList = sfResponse.getBody();
// right here debugging, the list has the correct number, but some of the data is missing
for (ObjectA sf: sfList) {
    sf.setId(null); //clear the local id, a uuid is persisting
    sf.save(thisApplicationContext);
}

//------------------The data class------------------------------
@Entity
public class ObjectA{
...
protected String ObjectBUuid;
protected String ObjectCUuid;
...
// basic POJO getters/setters/constructor etc. nothing fancy

Also for reference, ObjectA is a simple "Join" object between an ObjectB and ObjectC.  A simple join table doesn't work since I am storing a lot more meta data about the association that isn't super relevant to this but needed for business reasons.
//Here is a copy of the "response" from Postman hitting that json url.
//again, in debug before this is sent back the data looks correct with the Uuids populated (like in the DB)
[
{
  "id": 1, //local id of the ObjectA
  "uuid": "1464d8dc-0281-4850-a51d-a375f7a2fd04",  //ObjectA's uuid
  ... metadata stuff ...
  // end of obj., no reference to the ObjectB/C uuids at all in the returned obj.
}, // more data here matching the number I expect from the DB and the source debug breakpoint, just with the reference uuid missing.


text:
Q: UDP socket server, 3 listening sockets at time [Python] I would like to write a UDP server in Python, which would have 3 different sockets listening on different ports at time. The main job of the server is to send clients a constant text, different for different socket.
I wrote the below code:
import socket
import thread

def create_socket_server(host, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((host, port))
    return s

def run_socket(s, secret):
    while True:
        (data, addr) = s.recvfrom(1024)
        s.sendto(secret, addr)

def run_server():
    s1 = create_socket_server('127.0.0.1', 2000)
    s2 = create_socket_server('127.0.0.1', 3000)
    s3 = create_socket_server('127.0.0.1', 4000)

    while 1:
        thread.start_new_thread(run_socket, (s1, "A"))
        thread.start_new_thread(run_socket, (s2, "B"))
        thread.start_new_thread(run_socket, (s3, "C"))

if __name__ == "__main__":
    run_server()

But after I ran it it showed that:
/usr/bin/python2.7 /home/brian/Temp/udp.py
Traceback (most recent call last):
  File "/home/brian/Temp/udp.py", line 29, in <module>
    run_server()
  File "/home/brian/Temp/udp.py", line 24, in run_server
    thread.start_new_thread(run_socket, (s2, "SI"))
thread.error: can't start new thread

Process finished with exit code 1

What is the problem?

A: You are continually trying to re-start the sockets, as they fall under the never ending "while" loop. Remove the "while 1" and instead make your loop at the bottom of the script. could even be
if __name__ == "__main__":
    run_server()
    while 1:
        time.sleep(1)

This way it will start your threads and then move on, in this case into a never ending sleep. Just as an example. Hope it helps.


text:
Q: How is the length of actual and predicted value different in table? Getting error- all arguments must have the same length This is my code for a Logistic regression:
data_raw = data.frame(
    Var1= c(11, 5, 1, 0, 5, 1, 0, 0, 1, 0),
  Var2= c(11, 5, 0, 0, 2, 1, 0, 2, 0, 2),
  Var3= c(10, 7, 15, 9, 16, 9, 13, 15, 11, 17),
  Var4= c(6, 10, 36, 10, 9, 12, 17, 5, 12, 14),
  Var5= c(7, 26, 24, 16, 23, 25, 15, 10, 15, 22),
  Var6= c(0, 0, 1, 0, 0, 2, 1, 0, 0, 0),
  Var7= c(17, 21, 23, 16, 26, 22, 11, 9, 9, 9),
  Var8= c(1, 0, 1, 0, 3, 5, 2, 0, 0, 0),
  Var9= c(3, 0, 3, 3, 2, 0, 1, 3, 3, 2),
  Var10= c(3, 0, 3, 3, 2, 0, 1, 3, 3, 2),
  Var11= c(7, 2, 6, 7, 7, 5, 3, 5, 5, 4),
  Var12= c(4, 3, 3, 4, 2, 3, 4, 8, 7, 5),
  Var13= c("Summer", "Summer", "Summer", "Summer", "Autumn", "Autumn", "Summer", "Summer", "Summer", "Summer"),
  Var14= c("Both host", "Both host", "Both host", "Host Visitor", "Both host", "Both host", "Both host", "Both host", "Both host", "Both host"),
  Var15= c("Home", "Similar", "Similar", "Similar", "Similar", "Similar", "Home", "Home", "Home", "Similar"),
  Winner = c("Win", "Loss", "Win", "Loss", "Win", "Win", "Loss", "Loss", "Win", "Loss"),
  stringsAsFactors = TRUE
)
set.seed(123) # <-- edit
data_shuffled = sample(1:nrow(data_raw))

data_new = data_raw[data_shuffled, ]

create_train_test <- function(data_new, size = 0.8, train = TRUE) {
  n_row = nrow(data_new)
  total_row = size * n_row
  train_sample = 1: total_row
  if (train == TRUE) {
    return (data_new[train_sample, ])
  } else {
    return (data_new[-train_sample, ])
  }
}

data_train <- create_train_test(data_new, size= 0.8, train = TRUE)
data_test <- create_train_test(data_new, size= 0.8, train = FALSE)

mymodel = glm(Winner~., data= data_train, family= binomial)

res2 = predict(mymodel, data= data_test, type="response")
pred2= ifelse(res2>0.5, 1, 0)
tab2= table(data_test$Winner, pred2)

In the final code, I am getting an error that all arguments should have the same length. On inspection, I found that indeed they have different lengths. Why is it happening BTW? I used a different data set and it is working fine.
Edit. I have included an example data set.

A: When you use predict you have to use newdata and not data for using a new data set.
res2 <- predict(mymodel, newdata=data_test, type="response")


text:
Q: Does $\lim_{x\to\infty} f(x+1)/f(x) = 1$ imply $\lim_{x\to\infty} f(f(x+1))/f(f(x)) = 1$? As mentioned above, does
\begin{align}
\lim_{x\to\infty} \frac{f(x+1)}{f(x)} = 1
\end{align}
imply
\begin{align}
\lim_{x\to\infty} \frac{f(f(x+1))}{f(f(x))} = 1?
\end{align}
Here, $f:\mathbb{R}\to \mathbb{R}$ is a function such that
(1) $f(x)\neq 0$ for all $x\in\mathbb{R}$ (or for all $x\ge x_0$ for some $x_0$);
(2) $\lim_{x\to\infty} f(x) =\infty$;
(3) $f$ is increasing.
This is not a homework question, but I just wonder if this statement is true (Indeed, I observe that this holds for $f(x)=\log(x)$ so I have this question). I would appreciate any counterexample/proof/hints. Many thanks!

A: No.
Take $f(x)=e^{\sqrt{x}}$.
Then $$f(x+1)=e^{\sqrt{x+1}}=e^{\sqrt{x}\left(1+\frac 1 {2x}+o\left(\frac 1 {x}\right)\right)}=f(x)\left(1+\frac 1 {2\sqrt x}+o\left(\frac 1 {\sqrt x}\right)\right)$$
thus $$\lim_{x\rightarrow+\infty} \frac{f(x+1)}{f(x)}=1$$
But
$$f(f(x+1))=e^{\sqrt{e^{\sqrt{x+1}}}} = e^{e^\frac{\sqrt{x+1}}2}=e^{e^{\frac{\sqrt{x}}2 \left(1+\frac 1 {2x}+o\left(\frac 1 {x}\right)\right)}}\simeq f(f(x))\exp \left [ \frac{e^{\frac {\sqrt{x}}2}}{4\sqrt x}\right]$$
Thus $$\lim_{x\rightarrow+\infty} \frac{f(f(x+1))}{f(f(x))}=+\infty$$


text:
Q: How to show that $p_{K}(x)<1$ iff $x$ is an interior point of convex set $K.$ I would like to prove theorem $3$, chapter $3$ from the book Functional Analysis, Peter Lax.

Definition 1 : Let $X$ be a linear space of reals and $S\subset X.$ A point $x_0$ is called an interior point of $S$ if $\forall y\in X,\exists \epsilon $ such that for all $t\in \mathbb{R}$ with $|t|<\epsilon$ we have $x_0+ty\in S.$
Definition 2 : Let $K$ be a convex set that has an interior point. Define $$p_K(x)=\inf a, \text{ where }a>0 \text{ and }\frac{x}{a}\in K.$$
Theorem 3 : For any convex set $K$, $$p_K(x)<1 \iff x\text{ is an interior point of K}.$$

My attempt:
For the forward direction, assume that there exists $x\in X$ such that $r = p_{K}(x)<1.$ Then we want to show that $x$ is an interior point of $K.$ Choose $y\in X,$ then I am not sure what $\epsilon$ to choose that will make $x+ty\in K$ for all $|t|<\epsilon.$
For the reverse direction, if $x$ is an interior point of $K$ then this means that
$$p_K(x)\leq p_K(x-ty) + tp_K(y)\leq 1 + \epsilon p_K(y)$$
for some $y\in X$ and for all $|t|<\epsilon.$ Can I use this to show that $p_K(x)\leq 1?$

A: I don't think the other implication works. Let $X = \mathbb{R}^2$ and $S \subset X$ be the closed square with vertices $(1,0)$, $(2,0)$, $(2,1)$ and $(1,1)$. Then $S$ has an interior point $(\frac{3}{2}, \frac{1}{2})$.
Further for $x = (\frac{3}{2},0)$ we have $$p_S(x) \leq \frac{3}{4} < 1$$ as $(\frac{3}{4})^{-1}x = (2,0) \in S$. However, $x$ is not an interior point of $S$.
I think that the problem is that the condition of $p_S(x)$ takes into consideration only the line $\overline{0x}$ while being interior point considers all directions from $x$.

A: Let $y=x$, so that there's an $\epsilon>0$ such that for all $|t|<\epsilon$ , $x+tx=(1+t)x\in S$.
Pick any such $t$ that satisfies $0<t<\epsilon$. Let $a_t:=1/(1+t)$. Then $p_K(x)\leq a_t<1.$


text:
Q: How do I modify DataExplorer::create_report function to create a plot bar with percentage? I have this data set (it's an example). With my real data set, I have 100 categorical variables:
library(DataExplorer)

df <- data.frame(Sex = c("Male","Female","Male","Female","Male"))

create_report(df)

And I am making a report through DataExport, but it generates a bar plot in this way:
But my desired plot is:

How could I customize this plot?


text:
Q: Explanation for coverage_error metric in scikit learn I am not understanding how the coverage_error is calculated in scikit learn, available in sklearn.metrics module. Explanation in the docs is as below:

The coverage_error function computes the average number of labels that have to be included in the final prediction such that all true labels are predicted.

For eg:
import numpy as np
from sklearn.metrics import coverage_error
y_true = np.array([[1, 0, 0], [0, 1, 1]])
y_score = np.array([[1, 0, 0], [0, 1, 1]])
print coverage_error(y_true, y_score)
1.5

As per my understanding, here we need to include 3 labels from the prediction to get all labels in y_true. So coverage error = 3/2, ie, 1.5. But I am not able to understand what happens in the below cases:
>>> y_score = np.array([[1, 0, 0], [0, 0, 1]])
>>> print coverage_error(y_true, y_score)
2.0
>>> y_score = np.array([[1, 0, 1], [0, 1, 1]])
>>> print coverage_error(y_true, y_score)
2.0

How come the error is same in both the cases?

A: You can have a look at User Guide 3.3.3. Multilabel ranking metrics

with

One thing you need to take care is how to compute ranks and break ties in ranking y_score.
To be specific, the first case:
In [4]: y_true
Out[4]:
array([[1, 0, 0],
       [0, 1, 1]])

In [5]: y_score
Out[5]:
array([[1, 0, 0],
       [0, 0, 1]])

*

*For the 1st sample, the 1st true label is true, and the rank of 1st score is 1.

*For the 2ed sample, the 2ed and 3rd true label are true, and the ranks of score are 3 and 1 respectively, so the max rank is 3.

*The average is (3+1)/2=2.

the second case:
In [7]: y_score
Out[7]:
array([[1, 0, 1],
       [0, 1, 1]])

*

*For the 1st sample, the 1st true label is true, and the rank of 1st score is 2.

*For the 2ed sample, the 2ed and 3rd true label are true, and the ranks of score are 2 and 2 respectively, so the max rank is 2.

*The average is (2+2)/2=2.

Edit:
The rank is within one sample of y_score. The formula says the rank of a label is the number of labels (including itself) whose score is greater than or equal to its score.
It is just like sort the labels by y_score, and the label with largest score is ranked 1, the second largest is ranked 2, the third largest is ranked 3, etc. But if the second and third largest labels have the same score, they are both ranked 3.
Notice that y_score is

Target scores, can either be probability estimates of the positive class, confidence values, or binary decisions.

The goal is to have all true labels predicted, so we need to include all the labels with higher or equal scores than the true label.


text:
Q: How to upload HDF5 file directly to S3 bucket in Python I want to upload a HDF5 file created with h5py to S3 bucket without saving locally using boto3.
This solution uses pickle.dumps and pickle.loads and other solutions I have found, store the file locally which I like to avoid.

A: You can use io.BytesIO() to and put_object as illustrated here 6. Hope this helps. Even in this case, you'd have to 'store' the data locally(though 'in memory'). You could also create a tempfile.TemporaryFile and then upload your file with put_object. I don't think you can stream to an S3 Buckets in the sense that the local data would be discarded as it is uploaded to the Bucket.


text:
Q: Server 2003 DC & Server 2003 Terminal Server I've setup a Server 2003 R2 as AD & DC. I created some test users on the dc. I also setup a Server 2003 R2 as a Terminal Server.
I got licensing etc. working.
What i cant get to work is that users can login to the terminal server.
What i dont understand is how the terminal server should know to check for users at the DC? How do these two talk to each other?
When i trie to login to the terminal server i get an error stating that says
"allow login thru terminal services right" I've set this to enable in the policy,ran a gupdate /force on both servers but still i get this error. I also read somehwere that you can add the user to the rdp-tcp policies,but why would i wanna do that? The terminal server should check at the dc or am i wrong? To test things i did add the user at the rdp-tcp policies but it still doesnt work.
The terminal server is a member of the dc, i added the terminal server like  a normal pc to the domain.
Any help is appreciated as i'm out of options :)
Thanks,
Oscar

A: Have you joined the terminal server to the AD domain?  Without joining it to a domain you will only be able to use local logins on the terminal server.  The terminal server will check the DC by being joined to the AD domain that your DC is authoritative for.  If the terminal server is part of the domain then it will automatically contact a DC in the background during the login process (or at least attempt to).  You also need to make sure you're specifying domain credentials by either entering your username in domain\username format, user@domain.com format, or just username and selecting the domain from the dropdown.

A: You stated that you set the "allow login thru terminal services right" in your GPO, but this only tells the TS to allow logins but it doesn't tell it who to allow to login. the easiest way is to add the domain users that you want to login (Domain Users group, or another group, or individuals) to the local Remote Desktop Users group on the TS.
So, to summarize:

*

*You have to tell the TS to allow logins (which you did)

*You have to tell the TS who to allow to login (which you have not done)


text:
Q: dimension of fiber product of k-schemes of finite type I'm reading Görtz and Wedhorn Algebraic Geometry I, I have a question about the proof of

I don't understand why the final map is still injective.
I would be grateful for any help.

A: Since you are working over a field, every $k$-module is flat. Since $k[T_1,\ldots,T_n]\to \Gamma(X,\mathscr{O}_X)$ is injective, so is $$k[T_1,\ldots,T_n]\otimes k[T_{m+1},\ldots,T_{m+n}]\to \Gamma(X,\mathscr{O}_X) \otimes k[T_{m+1},\ldots,T_{m+n}].$$ Similarly, since $k[T_{m+1},\ldots,T_{m+n}]\to \Gamma(Y,\mathscr{O}_Y)$ is injective, so is $$\Gamma(X,\mathscr{O}_X)\otimes k[T_{m+1},\ldots,T_{m+n}]\to \Gamma(X,\mathscr{O}_X)\otimes \Gamma(Y,\mathscr{O}_Y).$$ Now the map $k[T_1,\ldots,T_{n+m}]\to \Gamma(X,\mathscr{O}_X)\otimes \Gamma(Y,\mathscr{O}_Y)$ is just the composition of these two injective morphisms.


text:
Q: How to make UIElement's location transform persistent? While looking for ways to drag around a UIElement in WPF I came across some code and have been experimenting with it. When the Element is clicked, it nicely follows the mouse, but on a subsequent drag-event, the Element reset itself to its original position.
The xaml setup: Very simple, just a named Canvas with the most original name ever and the Element, in this case a grid, called Tile1.
<Grid>
         <Canvas x:Name="Canvas" Width="200" Height="300" Background="LightGray">
            <Grid x:Name="Tile1">
                <Border BorderBrush="Black" BorderThickness="1" Background="White">
                    <Control Width="25" Height="25"/>
                </Border>
            </Grid>
        </Canvas>
</Grid>

some code-behind:
public TranslateTransform transPoint;
public Point originPoint;

public MainWindow()
        {
            InitializeComponent();
            Tile1.MouseLeftButtonDown += Tile1_MouseLeftButtonDown;
            Tile1.MouseLeftButtonUp += Tile1_MouseLeftButtonUp;
            Tile1.MouseMove += Tile1_MouseMove;
        }

        private void Tile1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var myLocation = e.GetPosition(Canvas);
            originPoint = new Point(myLocation.X, myLocation.Y);
            transPoint = new TranslateTransform(originPoint.X, originPoint.Y);
        }

        private void Tile1_MouseMove(object sender, MouseEventArgs e)
        {
            var mouseLocation = e.GetPosition(Canvas);

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                transPoint.X = (mouseLocation.X - originPoint.X);
                transPoint.Y = (mouseLocation.Y - originPoint.Y);
                Tile1.RenderTransform = transPoint;
            }
        }

        private void Tile1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var mouseLocationOnCanvas = e.GetPosition(Canvas);
            var mouseLocationOnTile = e.GetPosition(Tile1);

            //attempting to account for offset of mouse on the Tile:
            var newX = mouseLocationOnCanvas.X - mouseLocationOnTile.X;
            var newY = mouseLocationOnCanvas.Y - mouseLocationOnTile.Y;

            Tile1.Margin = new Thickness(newX, newY, 0, 0);
        }

In the original example (reference added here) A MouseUpEvent wasn't even used. Without it, my element just resets to its original position at 0,0 at every MouseDragEvent. And with it, it'll jump all over the place.
My train of thought was to somehow set the Element's current position to where the MouseUpEvent occurred.
I've been fiddling around with different things, as this particular stuff is rather new to me. Examples are: Tile1.TransformToAncestor(Canvas).Transform(mouseLocation);
I also found that VisualOffset has the information I need, so somehow it's already stored on the object, before being reset, but I haven't found a way to access it in any form.
Tile1.SetValue(VisualOffset.X = ...); or Tile1Grid.GetValue(VisualOffset);
So basically, is there a way to not have the element reset its position after RenderTransform?

A: I didn't find MouseLeftButtonDown event useful so I removed it:
I noticed some lags when moving the mouse that ould be annoying maybe the event needs to run asynchronously MouseMove performance slow using GetPosition.
 public TranslateTransform transPoint = new TranslateTransform(0, 0);
 public Point originPoint = new Point(0, 0);

public MainWindow()
        {
            InitializeComponent();
            Tile1.MouseLeftButtonUp += Tile1_MouseLeftButtonUp;
            Tile1.MouseMove += Tile1_MouseMove;
        }

private void Tile1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var mouseLocation = e.GetPosition(Canvas);

                transPoint.X = (mouseLocation.X - originPoint.X);
                transPoint.Y = (mouseLocation.Y - originPoint.Y);
                Tile1.RenderTransform = transPoint;

            }
        }

private void Tile1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
   var mouseLocation = e.GetPosition(Tile1);
   originPoint.X = mouseLocation.X;
   originPoint.Y = mouseLocation.Y;
        }

A: The RenderTransform seems to erratic, but I got the UIElement to stay put after moving it using the following:
private void MovableTile_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        tile.CaptureMouse();
    }

with
private void MovableTile_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            var tile = sender as UIElement;
            var mousePosition = e.GetPosition(canvas);
            Canvas.SetLeft(tile, mousePosition.X);
            Canvas.SetTop(tile, mousePosition.Y);
        }
    }

and then
private void MovableTile_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        tile.ReleaseMouseCapture();
    }

The MouseCapture was the key here. :)


text:
Q: Android adb shell ,ps-ef does not show any process? i have many application running on my emulator but ps -ef does not show any process y?

A: It seems like Android's ps does not accept the argument -ef. Try issuing ps only?

A: adb shell ps | grep com.android.mms | awk '{print $2}'
This gives the process id of the attached process