text:
Q: iText 7 PDF parser returns unreadable characters in C# I am trying to extract text from PDF files using iText 7 (the latest version). When I run the code below it extracts the text from every PDF I give it except the ones from a client (of course). They have a very old accounting system and the PDF files return unreadable text (diamonds w/question marks).
I can load their PDF files into Adobe Reader and copy/paste the text into notepad perfectly. Their PDFs are created by Ghostscript and the PDF file version is 1.7.
I have used iText many times and I have never encountered this before. The commented out line below was my attempt to see if it was some sort of encoding problem. I am coding in C# w/VS2019 and I installed iText 7 via Nuget. Thank you for your time!
        string fileName = @"c:\users\default\desktop\test\invoice.pdf";

        StringBuilder text = new StringBuilder();

        if (File.Exists(fileName))
        {
            PdfDocument pdfReader = new PdfDocument(new PdfReader(fileName));
            for (int page = 1; page <= pdfReader.GetNumberOfPages(); page++)
            {
                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                String currentText = PdfTextExtractor.GetTextFromPage(pdfReader.GetPage(page), strategy);
                //currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));

                outputtextBox.AppendText(currentText);
            }
            pdfReader.Close();
        }


text:
Q: color change Javascript I am trying to

*

*Retrieve 2 columns from MySQL and display them in HTML table

*When clicked on Name which is in the table header i want to change the color of all the contacts.

what I hv done-
callin a javascript on tableRows id to change color,but it only changes the the color of 1st row.
<?php
  while($row_color_test = mysql_fetch_assoc($result_color_test))
  {
    ?>

        <?php echo $row_color_test['name'] ; ?>
        <?php echo $row_color_test['phone']; ?>

    <?php
  }
    ?>

Javascript Function
function changecolor()
    {
     document.getElementById("tableRows").style.color="red";
    }

any idea why it happening although all the rows are dynamically created by while loop so all hv the same id and therefore,CSS rule sud apply on them.
Or is there a better way to do it??I hv to use Javascript only

A:
but it only changes the the color of 1st row.

Right. The tableRows id is on the row, and id values must be unique on the page. You can't have more than one element (row, in this case) with the same id. If you do, most browsers just ignore the id on subsequent elements on the page — so you're only seeing one element updated.
You could use a class instead:
<tr class="tableRows" ...

...and do this on most browsers:
var list = document.querySelectorAll(".tableRows");
var index;
for (index = 0; index < list.length; ++index) {
    ilst[index].style.color = "red";
}

But it would be better still to just set a class on the table and use CSS rules to turn the rows red instead.
document.getElementById("id_of_the_table").className += " foo";

...with this CSS:
.foo tr {
    color: "red"
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel cover sheet that is used to populate cells across the whole workbook I am trying to create a cover sheet for an excel workbook, the user will populate these cells then a macro will paste them across all worksheets inside the workbook.
The cover sheet asks for information in cells from column D and column I which could be common across the whole workbook. I am trying to make filling out this workbook faster and easier.
I have a basic understanding of Excel VBA but require help to write this, thank you.

A: You code use something like this
Sub Main
  Dim cellsToCopy As Range
  Dim shtNames as Variant, shtName As Variant

  Set cellsToCopy = Worksheets("CoverSheet").Range("D5, D11, I3, I12") '<--| change both "CoverSheet" name and its cells address list to fit your needs

  shtNames = Array("firstSheet", "secondSheet", "thirdSheet") '<--| change sheets names to paste cellsToCopy values into

  For Each shtName in shtNames
     Worksheets(shtName).Range(cellsToCopy.Address).Value = cellsToCopy.Value
  Next shtName

End Sub


text:
Q: Swipe method not working in android automation testing I am trying to implement swipe method.May I know what is the correct way to achieve my objective?
public void swipeWithCordinateLocation(WebDriver driver,double startX,
                                       double  startY,double endX,double endY,
                                       double Duration)
{
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, Double> swipeObject = new HashMap<String, Double>();
swipeObject.put("x", startX);
swipeObject.put("y", startY);
swipeObject.put("x", endX);
swipeObject.put("y",endY );
swipeObject.put("duration", Duration);
// HashMap[] param = {swipeObject};
js.executeScript("mobile: swipe", swipeObject);

}

common.swipeWithCordinateLocation(driver, 100.00, 500.00, 500.00, 500.00, 1.00);

But appium is perform swipe but it takes different credentials
[x=360][y=592]
 to [x=360][y=592]

. what to do?
Can any one help me please.

A: The best way to analyze a swipe in automation is to enable "Show touches" and "pointer location" options in your developer option.
The correct code for the swipe parameters is this -
swipeObject.put("startX", 198.00);
swipeObject.put("startY", 685.00);
swipeObject.put("endX", 198.00);
swipeObject.put("endY", 550.00);
swipeObject.put("duration", 1.0);

Hope this helps.
Or even a better way is to use something like using fractions -
swipeObject.put("startX", 0.50);
swipeObject.put("startY", 0.50);
swipeObject.put("endX", 0.50);
swipeObject.put("endY", 0.35);
swipeObject.put("duration", 1.0);

A: The best solution is to use swipe() of AppiumDriver as shown below:
Swipe Left:
 public void swipeLeft()
  {
      AppiumDriver appiumDriver = (AppiumDriver) driver;
      appiumDriver.context("NATIVE_APP");
      Dimension size = appiumDriver.manage().window().getSize();
      int startx = (int) (size.width * 0.8);
      int endx = (int) (size.width * 0.20);
      int starty = size.height / 2;
      appiumDriver.swipe(startx, starty, endx, starty, 1000);

  }

Swipe Right:
 public void swipeRight()
  {
      AppiumDriver appiumDriver = (AppiumDriver) driver;
      appiumDriver.context("NATIVE_APP");
      Dimension size = appiumDriver.manage().window().getSize();
      int endx= (int) (size.width * 0.8);
      int startx = (int) (size.width * 0.20);
      int starty = size.height / 2;
      appiumDriver.swipe(startx, starty, endx, starty, 1000);

  }

A: You can achieve the same swiping result with TouchAction
    TouchAction action = new TouchAction(androidDriver);
    action.press(0, 500)
            .waitAction(200)
            .moveTo(0, 200)
            .release()
            .perform();

Just play with the coordinates to get the desidered swiping.

A: You can also use uiautomator for the same .
It will help you to automate test cases very effectively and faster.
you can read more about it at http://developer.android.com/tools/help/uiautomator/index.html


text:
Q: Multiple imageView refreshing in Android using asynctasks? what I have to do is to play videos on a single activity, the number of videos is undefined, could be from 1 to 8, a video in my case is an image sequence, where every image is downloaded from a cam on the internet using a fixed time interl.
Do a single video activity is not a problem, I can make it using ImageView and a AsyncTask, using many instances of this method when I try to make multiple videos activities does not work, only one of the video plays. I don't know exactly what it happens but I think it could be a cuncurrency related issue due to the UIThread.
Here the used AsyncTask code:
private class AsyncTask_LiveView extends AsyncTask<String, Integer, Void>
{
    private String sImageMessage = "";

    private final WeakReference<ImageView> imageViewReference;
    private Bitmap bmImage = null;
    private String url = "";
    private String usr = "";
    private String pwd = "";
    private utils u = new utils();

    public AsyncTask_LiveView(ImageView imageView, String Url, String Usr, String Pwd)
    {
        imageViewReference = new WeakReference<ImageView>(imageView);
        url = Url;
        usr = Usr;
        pwd = Pwd;
    }

    // automatically done on worker thread (separate from UI thread)
    @Override
    protected Void doInBackground(final String... args)
    {
        while(!isCancelled())
        {
            if(isCancelled())
                 return null;

            SystemClock.sleep(200);

            Log.v("ImageDownload","test");
            bmImage = u.DownloadBitmapFromUrl(url, usr, pwd);

            publishProgress(0);
        }

        return null;
    }

    // can use UI thread here
    @Override
    public void onProgressUpdate(Integer... i)
    {
        Log.v("Image", "Setup Image");
        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bmImage);
            }
        }
    }
 }

I start the AsyncTasks in this way:
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layoutliveviewdouble);

        this.imgV1 = (ImageView ) findViewById(R.id.imageView1);
    aTaskImgV1 = new AsyncTask_LiveView(imgV1,
                                        URL1,
                                        "",
                                        "");

    this.imgV2 = (ImageView ) findViewById(R.id.imageView2);
    aTaskImgV2 = new AsyncTask_LiveView(imgV2,
                                        URL2,
                                        "root",
                                        "jenimex123");

    aTaskImgV1.execute();
    aTaskImgV2.execute();
}

The DownloadBitmapFromUrl method is:
public Bitmap DownloadBitmapFromUrl(String imageURL, final String usr, final String pwd) {  //this is the downloader method
    try {
        URL url = new URL(imageURL);

        /* Open a connection to that URL. */
        HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
        ucon.setRequestMethod("GET");
        ucon.setDoOutput(true);
        Authenticator.setDefault (new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication (usr, pwd.toCharArray());
            }
        });
        ucon.connect();

        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is =  ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(100000);
        int current = 0;
        while ((current = bis.read()) != -1) {
                baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        Bitmap bmp = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.length());

        return bmp;
    } catch (Exception e) {
            //Log.d("ImageManager", "Error: " + e);
        return null;
    }
}

Any Ideas?
Solution : (21/01/11)
The bounch of lines:
Authenticator.setDefault (new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication (usr, pwd.toCharArray());
            }
        });

were braking the mechanism. In fact only one credentials pair a could have been set globally, and the other download processes stucked in requesting using the wrong credentials.
The solution is:
String authString = usr + ":" + pwd;
byte[] authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
String authStringEnc = new String(authEncBytes);
ucon = (HttpURLConnection) url.openConnection();

if(_usr != "")
   ucon.setRequestProperty("Authorization", "Basic " + authStringEnc);

Thanks to all.

A: I think yuo should use unique AsyncTask_LiveView for each ImageView.

A: Does this function support multiple threads?
bmImage = u.DownloadBitmapFromUrl(url, usr, pwd);

A: It looks like some of the methods you call in downloadBitmapFromUrl(..) method involve synchronization by some common object. Try adding some extra logging to each part of this method and see where each thread gets stuck. I would do it this way:
public Bitmap downloadBitmapFromUrl(String imageURL, final String usr, final String pwd) {  //this is the downloader method
    try {
    ...
    Log.i(toString() + " in " + Thread.currentThread(), "is about to open connection...");
    HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
    Log.i(toString() + " in " + Thread.currentThread(), "has opened connection");

    ...

and so on.


text:
Q: Create a matrix with random numbers when required shape is derived from other variables I want to create a matrix with random numbers  in J programming language when the required shape is derived from other variables.
I could create such a matrix with ? 3 5 $ 0 if i specify its shape using literal integers. But I am struggling to find a way to create such a matrix when the shape is # y  and # x instead of 3 and 5 shown in above example.
I have tried ? 0 $~ # y, # x and it has not worked.
I think I need some way to apply # over a list of variables and return a list of numbers which should be placed after $~, somewhat like map functionality of other languages. Is there a way to do this?

A: I think that ?@:$ is what you are looking for
   3 5 ?@:$ 0
0.031974   0.272734    0.792653   0.439747  0.136448
0.332198   0.00904103  0.7896     0.78304   0.682833
0.27289    0.855249    0.0922516  0.185466  0.257876

The  general structure for this is x u@:v y   <->  (u (x v y)) where u and v are the verbs and the arguments are x and y.
Hope this helps.
Rereading your question it looks as if you want the shape to be based on the number of items in the arguments. Here I would use # to count the items in each argument, then use , to create the left argument for $&0 and apply ? to the result.
   3 4 5  (?@:($&0 @:,))&#  5 3 3 4 5
0.179395  0.456545  0.805514  0.471521  0.0967092
0.942029  0.30713   0.228288  0.693909  0.338689
0.632752  0.618275  0.100224  0.959804  0.517927

Is this closer to what you had in mind?
And as often the case, I thought of another approach overnight
   3 4 5 ?@0:"0/ 1 2 3 4 5
 0.271366   0.291846  0.0493541  0.72488   0.47988
 0.50287    0.980205  0.58541    0.778901  0.0755205
 0.0114588  0.523955  0.535905   0.5333    0.984908


text:
Q: shutil.move(scr, dst) gets me IOError: [Errno 13] Permission denied and 3 more errors Documents = ['*pdf', '*docx', '*txt']

for i in range(len(Documents)):
    if glob.glob(Documents[i]):
        print(Documents[i], True)
        shutil.move(glob.glob(Documents[i])[0], '/home')

    else:
        print(Documents[i], False)

Well, everything goes great until:
shutil.move(glob.glob(Documents[i])[0], '/home')

Which is basically:
shutil.move(scr, dst)

And produces the error:
*pdf False
*docx True
Traceback (most recent call last):
  File "/usr/lib/python3.2/shutil.py", line 326, in move
    os.rename(src, real_dst)
OSError: [Errno 13] Permission denied

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "teste.py", line 19, in <module>
    shutil.move(glob.glob(Documents[i])[0], '/home')
  File "/usr/lib/python3.2/shutil.py", line 334, in move
    copy2(src, real_dst)
  File "/usr/lib/python3.2/shutil.py", line 146, in copy2
    copyfile(src, dst)
  File "/usr/lib/python3.2/shutil.py", line 99, in copyfile
    with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: '/home/jesus.docx'

I tried using absolute path in both scr and dst and it didn't work. I browsed the web and found out that it might have something to do with permissions but if i have to change the permissions it will defeat the purpose of the script and that's why i will try to find help here before getting into the permissions thing.
So, what do i do?
My purpose is to move files in Linux user's directories. (sort them according to the file format..)...ex->  .jpg --> Pictures, .pdf --> Documents and so on. (That's why i can't be having permission thing hardening life...)
Also i'm a newbie at programming (just so you guys don't get very geeky :D )
And, this is also my first questions here at this community so please little patience if i sound lost or retundant? Thanks

A: You're attempting to write files to the /home directory. You should not be doing that.
Linux is a multiuser operating system. /home is where all of your users home directories live. Each user should have their own directory under /home. For example yours could be /home/Joao.
Change the last parameter from this line
shutil.move(glob.glob(Documents[i])[0], '/home')

to
shutil.move(glob.glob(Documents[i])[0], '/home/your_username')

Here's a general improvement suggestion:
# Variable names are lower case
documents = ["*.pdf", "*.docx", "*.txt"]
# You iterate over a for loop like this. Python's for is like for-each. You get the actual item.
for doc in documents:
    if glob.glob(doc):
        shutil.move(glob.glob(doc)[0], '/home/your_username/Documents')

A: You want users that run your script to be able to run it with elevated privileges. There is something called the setuid bit (set user id), which, when set, will run the script with the priveleges of the owner. There is also a setgid (set group id) bit.
To set them, become root and execute:
chown root scriptname
chmod ug+s scriptname

This sets both the setuid bit and the setgid bit.
http://en.wikipedia.org/wiki/Setuid


text:
Q: Android ListView array index out of bounds after filter I think this is a question for experts.
I get calls to getView() with positon out of bounds from the ListView data list.
This happens when I use the Adapter filter. The filter publishResults() method populates the data with a filtered list which is smaller than the original list.
The error seems to occur when the new filtered list is shorter than the previous  filtered list.
I changed the code of getView() to return a dummy convertView when out of bounds, just to see how many such calls are issued.
These are the relevant code and the log messages I logged:
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // No logs here to keep ListView performance good
        Log.d(TAG, "+ getView( position=" + position + ")");
        ViewHolder holder;

        if( position >= mData.size() ) {
            // This code allows to see how many bad calls I get
            Log.w(TAG, "position out of bounds!");
            convertView = mInflater.inflate(mLayout, parent, false);
            return convertView;
        }

        . . . // Normal getView code

        return convertView;
    }

In the filter (code copied as is from ArrayAdapter source code)
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            Log.pe(TAG, "+ publishResults(constraint:" + constraint + ", results.count:" + results.count + ")");
            //noinspection unchecked
            mData = (ArrayList<String>) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
            Log.px(TAG, "- publishResults()");
        }

The log file shows that after a filter with 7 results, comes a fitler with 3 results, but getView keeps getting calls for 7 items (I marked with *** the out of bounds calls):
02-26 05:31:55.986: D/ViewerActivity(22857): + onQueryTextChange(newText:log)
02-26 05:31:55.986: D/ViewerActivity(22857): - onQueryTextChange()
02-26 05:31:56.029: D/LogScreenAdapter(22857): + performFiltering(prefix:log)
02-26 05:31:56.113: D/dalvikvm(22857): GC_CONCURRENT freed 378K, 5% free 13577K/14215K, paused 0ms+1ms
02-26 05:31:56.153: D/LogScreenAdapter(22857): - performFiltering()
02-26 05:31:56.153: D/LogScreenAdapter(22857): + publishResults(constraint:log, results.count:7)
02-26 05:31:56.167: D/LogScreenAdapter(22857): - publishResults()
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=0)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=0)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=0)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=1)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=2)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=3)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=4)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=5)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=6)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=0)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=1)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=2)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=3)
02-26 05:31:56.167: D/LogScreenAdapter(22857): + getView( position=4)
02-26 05:31:56.493: D/LogScreenAdapter(22857): + getView( position=5)
02-26 05:31:56.503: D/LogScreenAdapter(22857): + getView( position=6)
02-26 05:32:23.793: D/ViewerActivity(22857): + onQueryTextChange(newText:logs)
02-26 05:32:23.793: D/ViewerActivity(22857): - onQueryTextChange()
02-26 05:32:23.813: D/LogScreenAdapter(22857): + performFiltering(prefix:logs)
02-26 05:32:23.854: D/dalvikvm(22857): GC_CONCURRENT freed 383K, 5% free 13577K/14215K, paused 0ms+0ms
02-26 05:32:23.924: D/dalvikvm(22857): GC_CONCURRENT freed 388K, 5% free 13573K/14215K, paused 0ms+1ms
02-26 05:32:23.974: D/LogScreenAdapter(22857): - performFiltering()
02-26 05:32:23.983: D/LogScreenAdapter(22857): + publishResults(constraint:logs, results.count:3)
02-26 05:32:23.983: D/LogScreenAdapter(22857): - publishResults()
02-26 05:32:23.983: D/LogScreenAdapter(22857): + getView( position=0)
02-26 05:32:24.074: D/LogScreenAdapter(22857): + getView( position=0)
02-26 05:32:24.093: D/LogScreenAdapter(22857): + getView( position=0)
02-26 05:32:24.113: D/LogScreenAdapter(22857): + getView( position=1)
02-26 05:32:24.155: D/LogScreenAdapter(22857): + getView( position=2)
02-26 05:32:24.164: D/LogScreenAdapter(22857): + getView( position=3)
*** 02-26 05:32:24.193: W/LogScreenAdapter(22857): position out of bounds!
02-26 05:32:24.233: D/LogScreenAdapter(22857): + getView( position=4)
*** 02-26 05:32:24.263: W/LogScreenAdapter(22857): position out of bounds!
02-26 05:32:24.284: D/LogScreenAdapter(22857): + getView( position=5)
*** 02-26 05:32:24.313: W/LogScreenAdapter(22857): position out of bounds!
02-26 05:32:24.333: D/LogScreenAdapter(22857): + getView( position=6)
*** 02-26 05:32:24.343: W/LogScreenAdapter(22857): position out of bounds!
02-26 05:32:24.353: D/LogScreenAdapter(22857): + getView( position=0)
02-26 05:32:24.373: D/LogScreenAdapter(22857): + getView( position=1)
02-26 05:32:24.383: D/LogScreenAdapter(22857): + getView( position=2)
02-26 05:32:24.403: D/LogScreenAdapter(22857): + getView( position=3)
*** 02-26 05:32:24.413: W/LogScreenAdapter(22857): position out of bounds!
02-26 05:32:24.433: D/LogScreenAdapter(22857): + getView( position=4)
*** 02-26 05:32:24.443: W/LogScreenAdapter(22857): position out of bounds!
02-26 05:32:24.463: D/LogScreenAdapter(22857): + getView( position=5)
*** 02-26 05:32:24.475: W/LogScreenAdapter(22857): position out of bounds!
02-26 05:32:24.483: D/LogScreenAdapter(22857): + getView( position=6)
*** 02-26 05:32:24.503: W/LogScreenAdapter(22857): position out of bounds!
02-26 05:38:26.769: D/dalvikvm(22857): GC_CONCURRENT freed 316K, 5% free 13640K/14215K, paused 0ms+1ms

What you are seeing here, the publishResults() method did change mData from a list of 7 items to a shorter list of 3 items, see the code above, but the Adapter keeps getting getView() calls for the 7 items list, even that it is not longer there.
Note that notifyDataSetChanged() has been called with the new data assignment, so the ListView should be aware of the new list.

A: what are you returning in public int getCount() method of custom list view adapter?
You should return like mData != null? mData.size() : 0,
Position out of bond is getting due to may be you are returning size of list more than data to show in the list
getCount() method of custom list adapter specifies size of list view so it should be the size of data you are passing in the list

A: Seems like overriding of "getCount()" method will solve your problem:
@Override
public int getCount() {
    return mData.size();
}

A: I did this and it solved my problems
@Override
public int getCount() {

    if (isFiltered == true) {
        return myFilteredArray.size();
    }

    return myUnfilteredArray.size();
}


text:
Q: Delegate with Image and Text wading ColumnLayout I have following QML Item:
import QtQuick 2.0
import QtQuick.Layouts 1.2

import si.mikroelektronika 1.0

Item
{
    id: ueCategorySelector

    width: 768
    height: 128
    clip: true

    Rectangle
    {
        radius: 16
        gradient: Gradient
        {
            GradientStop
            {
                position: 0
                color: "#ffffff"
            }   // GradientStop

            GradientStop
            {
                position: 1
                color: "#000000"
            }   // GradientStop
        }   // Gradient

        border.color: "#4682b4"
        border.width: 1

        antialiasing: true

        anchors.centerIn: parent
        anchors.fill: parent

        ColumnLayout
        {
            anchors.margins: parent.radius/2

            spacing: 0
            antialiasing: true

            anchors.fill: parent
            anchors.centerIn: parent

            ListView
            {
                id: ueCategoryListView
                antialiasing: true

                orientation: ListView.Horizontal
                clip: true

                Layout.fillWidth: true
                Layout.fillHeight: true

                spacing: 64

                model: ueCategoriesModel

                delegate: Rectangle
                {
                    radius: 16

                    width: 160
                    height: ueCategoryListView.height-2*Layout.margins

                    clip: true

                    border.color: "#4682b4"

                    antialiasing: true

                    gradient: Gradient
                    {
                        GradientStop
                        {
                            position: 0
                            color: "#000000"
                        }   // GradientStop

                        GradientStop
                        {
                            position: 1
                            color: "#ffffff"
                        }   // GradientStop
                    }   // Gradient

                    ColumnLayout
                    {
                        anchors.centerIn: parent
                        anchors.fill: parent

                        antialiasing: true

                        spacing: 8

                        Image
                        {
                            Layout.fillWidth: true
                            Layout.fillHeight: false
                            Layout.alignment: Qt.AlignCenter|Qt.AlignTop

                            fillMode: Image.PreserveAspectFit

                            horizontalAlignment: Image.AlignHCenter
                            verticalAlignment: Image.AlignVCenter

                            antialiasing: true
                            source: "image://ueCategoriesModel/"+model.ueRoleImage
                        }   // Image

                        Text
                        {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            Layout.alignment: Qt.AlignCenter|Qt.AlignBottom

                            color: "#000000"

                            text: model.ueRoleName
                            wrapMode: Text.WordWrap
                            font.family: "Courier"
                            textFormat: Text.RichText

                            font.bold: true
                            font.pointSize: 10

                            verticalAlignment: Text.AlignVCenter
                            horizontalAlignment: Text.AlignHCenter
                        }   // Text
                    }   // ColumnLayout
                }   // delegate
            }   // ListView
        }   // ColumnLayot
    }   // Rectangle
}   // Item

Everything is ok, but the Image of Listview delegate is wading the ColumnLayout, as you can see in screenshot:

This should not be happening, but why is it happening?

A: According to user @BaCaRoZzo hint, here is now working code:
import QtQuick 2.0
import QtQuick.Layouts 1.2

import si.mikroelektronika 1.0

Item
{
    id: ueCategorySelector

    clip: true

    Rectangle
    {
        id: ueCategorySelectorWrapper

        radius: 16
        gradient: Gradient
        {
            GradientStop
            {
                position: 0
                color: "#ffffff"
            }   // GradientStop

            GradientStop
            {
                position: 1
                color: "#000000"
            }   // GradientStop
        }   // Gradient

        border.color: "#4682b4"
        border.width: 1

        antialiasing: true

        anchors.fill: parent

        ColumnLayout
        {
            anchors.margins: parent.radius/2

            spacing: 0
            antialiasing: true

            anchors.fill: parent

            ListView
            {
                id: ueCategoryListView
                antialiasing: true

                orientation: ListView.Horizontal
                clip: true

                Layout.fillWidth: true
                Layout.fillHeight: true
                Layout.alignment: Qt.AlignHCenter|Qt.AlignVCenter
                Layout.margins: 8

                spacing: 8

                model: ueCategoriesModel

                delegate: Rectangle
                {
                    radius: 16

                    width: 256
                    height: ueCategoryListView.height-2*Layout.margins

                    clip: true

                    border.color: "#4682b4"

                    antialiasing: true

                    gradient: Gradient
                    {
                        GradientStop
                        {
                            position: 0
                            color: "#000000"

                            ParallelAnimation on color
                            {
                                loops: 1
                                running: ueDelegateMouseArea.pressed

                                ColorAnimation
                                {
                                    from: "#4682b4"
                                    to: "#000000"
                                    duration: 100
                                }   // ColorAnimation
                            }   // ParallelAnimation
                        }   // GradientStop

                        GradientStop
                        {
                            position: 1
                            color: "#ffffff"
                        }   // GradientStop
                    }   // Gradient

                    MouseArea
                    {
                        id: ueDelegateMouseArea

                        anchors.fill: parent
                    }   // MouseAres

                    ColumnLayout
                    {
                        anchors.fill: parent

                        antialiasing: true

                        spacing: 8

                        Image
                        {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            Layout.alignment: Qt.AlignHCenter|Qt.AlignTop
                            Layout.topMargin: ueCategorySelectorWrapper.radius+4

                            fillMode: Image.PreserveAspectFit

                            horizontalAlignment: Image.AlignHCenter
                            verticalAlignment: Image.AlignVCenter

                            antialiasing: true
                            source: "image://ueCategoriesModel/"+model.ueRoleImage
                        }   // Image

                        Text
                        {
                            Layout.fillWidth: true
                            Layout.fillHeight: true
                            Layout.alignment: Qt.AlignHCenter|Qt.AlignBottom
                            Layout.bottomMargin: ueCategorySelectorWrapper.radius+4

                            color: "#000000"

                            text: model.ueRoleName
                            wrapMode: Text.WordWrap
                            font.family: "Courier"
                            textFormat: Text.RichText

                            font.bold: true
                            font.pointSize: 10

                            horizontalAlignment: Text.AlignHCenter
                            verticalAlignment: Text.AlignVCenter
                        }   // Text
                    }   // ColumnLayout
                }   // delegate
            }   // ListView
        }   // ColumnLayot
    }   // Rectangle
}   // Item


text:
Q: Проблема кодировки на Java сервере (mysql) Есть сервер на Java. БД mysql. Так создал базу данных:
CREATE DATABASE `my_db` CHARACTER SET utf8 COLLATE utf8_general_ci;

После, если ввожу в командную строку команды insert into, все окей, но вот если я пытаюсь ввести в программе русские символы, то вместо букв выходят вопросы.
Вот код простого запроса на сервер.  Может тут что нибудь нужно написать?
public static void main(String[] argv) {

      try {
          Class.forName("com.mysql.jdbc.Driver");
          System.out.println("connect");
          Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
          Statement statement = conn.createStatement();
          statement.executeUpdate("INSERT INTO `msg` (`text`)VALUES('текс какой нить');");

      } catch (ClassNotFoundException | SQLException ex) {
          Logger.getLogger(DBJava.class.getName()).log(Level.SEVERE, null, ex);
          System.out.println("cath:".concat(ex.getMessage()));
      }
    System.out.print("end");
  }
}

Пробовал перекодировать строку
String str = new String("текс какой нить".getBytes("utf8"));

A: Переустановил сервер на последний и вроде все в норме


text:
Q: Logging connections on a port of a openvz container by iptables I'm trying to log the connections that are made on the container with the IP x.x.x.x
I'm sending an email using postfix by the mail command but I don't see any logs.
Here is my configuration:

iptables -N LBFT_OUT
  iptables -A FORWARD -j LBFT_OUT
  iptables -A OUTPUT -j LBFT_OUT
  iptables -A LBFT_OUT -s x.x.x.x/32 -p tcp -m tcp --dport 25 -m state --state NEW -j LOG --log-prefix "LBFT_SMTP " --log-level 7
[root@host log]# cat /etc/rsyslog.d/lbft.conf
  :msg, contains, " LBFT_SMTP" -/var/log/lbft-smtp.log
  & ~

A: It seems iptables -I FORWARD -p tcp --dport 25 -o eth0 -m state --state NEW -j LOG --log-level info --log-prefix 'LBFT_SMTP ' works.


text:
Q: Personal modification Angluar CLI - Creating a new app Hi Stackoverflow Community,
I have the following question / problem.
Is there a way to create an own (more individually) ng new script ?
The standard command
ng new projectname

just allow me to create or not create routing, set scss or css.
When creating a new app, I want some specials (for example ask or automatic install bootstrap)
In other words, I want to make a more individual ng new command

A: Does the manual help you?
See: https://angular.io/cli/new
There you have a lot of options which you can set. For example --collection options which is very powerful.
With --collection you can pass a schematic.
A very good Schematic example you can find here:
https://developer.okta.com/blog/2019/02/13/angular-schematics


text:
Q: The density --- or otherwise --- of $\{\{2^N\,\alpha\}:N\in\mathbb{N}\}$ for ALL irrational $\alpha$. Problem
Is there an irrational $\alpha\in\mathbb{R}\backslash\mathbb{Q}$ such that the set $S= \{\,\{2^N\alpha\} :N\,\in\mathbb{N}\}$ is not dense in $[0,1]$.
Here $\{x\}=x-\lfloor x\rfloor$ is the fractional part of $x$.
Questions very similar to this have been asked in the past. For example
Multiples of an irrational number forming a dense subset
However right now I can't adjust them and put the two sticks together.

Context
I was trying to prove the following proposition --- which isn't actually true when $n>2$.
Let $n>2$ and let $O_n$ be the (proper) subset of $[0,1]$ of irrational numbers containing only $0$s and $1$s in their base-$n$ expansion. If we take $\alpha\in O_n$ we then have that
$$\{n^N\alpha\}\in O_n\text{ for all }N\in\mathbb{N}$$
and so $S$ can not be dense in $[0,1]$ when $n>2$.

Proposition
Suppose that $f:\mathbb{C}\rightarrow\mathbb{Z}$ is a power mapping
$f(z)=z^n$ for some $n\geq 2$.
Then the dynamical system $(\mathbb{C},f)$ exhibits the following four behaviours:

*

*If $z_0\in\mathbb{D}:=\{z\in\mathbb{C}:|z|<1\}$ then $z_n\rightarrow 0$.

*If $z_0\in\mathbb{C}\backslash\bar{\mathbb{D}}:=\{z\in\mathbb{Z}:|z|>1\}$ then $z_n\rightarrow\infty$.

*If $z_0\in\mathbb{T}=\{z\in\mathbb{C}:|z|=1\}$ then there are two behaviours:
a. If $z_0=e^{q\,2\pi i}$ with $q\in\mathbb{Q}$ then $z_0$ is eventually periodic.
b. If $z_0=e^{\alpha\,2\pi i}$ with $\alpha\in\mathbb{R}\backslash\mathbb{Q}$ then $z_0$ has a dense orbit.
In fact, $(\mathbb{T},f)$ is a chaotic mapping.
Proof: 1, 2 and the first part of 3 were illustrated in class for $n=4$. Here we prove for a general $n\geq 2$.
Assume that $z_0=e^{\alpha\cdot\,2\pi i}$ with $\alpha\in\mathbb{R}\backslash \mathbb{Q}$
Claim 1: $z_0$ is not eventually periodic.
Proof by Contradiction:  Suppose that $z_0=e^{\alpha\cdot2\pi i}$ is eventually periodic. That is there exists an iterate of $z_0$, say $f^N(z_0)$, that is periodic. Note that
$$f^N(z_0)=z_0^{n^N}=\left(e^{\alpha\cdot 2\pi i}\right)^{n^N}=e^{n^N\alpha\cdot2\pi i}.$$
Now if this point is periodic then there exists an $M\geq 1$ such that
$$f^M(e^{n^N\alpha\cdot2\pi i})=e^{n^N\alpha\cdot2\pi i}$$
$$\Rightarrow e^{n^Nn^M\alpha\cdot2\pi i}=e^{n^N \alpha\cdot2\pi i}$$
If these two complex numbers are equal then their argument/angle must differ only by a multiple of $360^\circ$; i.e. $k\cdot 2\pi$ for $k\in\mathbb{Z}$:
$$n^{M}n^N\alpha\cdot 2\pi-n^N\alpha\cdot 2\pi=k\cdot 2\pi$$
$$\Rightarrow n^{N+M}\alpha-n^N\alpha=k$$
$$\displaystyle\alpha=\frac{k}{n^{N+M}-n^N},$$
but this is a contradiction as $\alpha$ is not a fraction. Hence $z_0$ is not eventually periodic $\bullet$
Claim 2: Two iterates of $z_0$ can be found that are arbitrarily close together.
Proof : Note that the length of the unit circle is $2\pi$. Suppose that we divide the unit circle into $N$ arcs $A_1,A_2,\dots,A_N$ each of equal length $\displaystyle \frac{2\pi}{N}$ (to be careful suppose that they contain their 'right' endpoints but not their 'left'). Now, we know that $z_0$ is not eventually periodic so the first $n$ iterates of $z_0$ are all distinct:
$$z_0,z_1,z_2,z_3,\dots,z_N.$$
Note that there are $N$ arcs but $N+1$ iterates so by the Pigeonhole Principle there is an arc $A_i$ containing two iterates of $z_0$ --- say $z_i$ and $z_j$ --- that are on the same arc. Take $N\rightarrow \infty$ so that the arcs becoming arbitrarily small and the points become arbitrarily close together $\bullet$
Claim 3: There is a number $M$ such that $z_0$ and $f^M(z_0)$ are arbitrarily close together.
Proof: We know that for any $N$ we can find two iterates of $z_0$ that are at most (radially) apart by $\displaystyle \frac{2\pi }{N}$. Denote these by
$z_i=f^i(z_0)$ and $z_j=f^j(z_0)$... what I was hoping to do here actually doesn't work. Hmmm..

A: The sequence $\{2^n \alpha \}$ is dense if and only if its binary development contains every possible finite sequence of $0$s and $1$s.
(furthermore, it is uniformly distributed if and only if $\alpha$ is normal in base $2$. Almost all numbers are normal in base $2$)
If you have a finite sequence $d_1 \ldots d_k$ of length $d_k$, it is the binary expansion of an integer $a$, and irrational numbers whose binary development begin with $d_1 \ldots d_k$ are irrational numbers in the interval $[a/2^k ; (a+1)/2^k)$.
So if the sequence is dense, than $\alpha$ is irrational and for any finite sequence, there is a rank $n$ such that $\{2^n \alpha\} \in [a/2^k ; (a+1)/2^k)$. This means that the binary development of $\alpha$ contains the sequence $d_1 \ldots d_k$ starting at the $n$th digit.
Conversely, if the binary development contains all possible finite sequences, then the sequence $\{2^n \alpha\}$ visits every dyadic interval (intervals of the form $[a/2^k ; (a+1)/2^k)$), and because any open interval contains such a dyadic interval, it visits any open interval, so it is dense in $[0;1]$.
Then, it is not hard to see that the sequence generated by $\alpha = 0.1101001000100001\ldots$ is not dense since the binary development doesn't contain $111$, and $\alpha$ is obviously irrational.

A: Mercio's answer is correct and complete. From a dynamical point of view, what we can say is the following : every $z=e^{i \pi \theta}$, with $\theta$ rational, is eventually periodic.
But among the points that are not eventually periodic, not all have a dense orbit in all of $\mathbb{T}$. Indeed, there are invariant Cantor sets contained in $\mathbb{T}$ with orbits dense in those sets.


text:
Q: UIView flip vertically I know it's probably a dummy question, but I have to ask: How to flip a UIView vertically? I'm not asking for doing a animation, but just flip it.
I can do vertical flip a UILabel by:
label1.layer.transform = CATransform3DMakeRotation(M_PI, 1.0f, 0.0f, 0.0f);
and turn it back by:
label1.layer.transform = CATransform3DMakeRotation(M_PI, 0.0f, 0.0f, 0.0f);

But when I'm doing it to a view:
self.view.layer.transform = CATransform3DMakeRotation(M_PI, 1.0f, 0.0f, 0.0f);

I think it only rotate half way... So, any ideas?
Thanks guys.

A: I realize this is an old question, but I'll leave this here anyway. The following would flip the view vertically using just the y-scale of the layer, so it would be my preference:
self.view.layer.transform = CGAffineTransform(scaleX: 1, y: -1)


text:
Q: JPA/Hibernate: java.sql.SQLException: Invalid argument in JDBC call: parameter index out of range I'm using Hibernate 4 with a simple "join table" between two other tables. Here are the JPA 1.0 compatible entities:
@Entity
@Table(name = "Companies")
public class Company
{
    @Id
    @Column
    private Integer id;

    @Column
    private String name;

    ...
}

and
@Entity
@Table(name = "PQs")
public class PQ implements Serializable
{
    @Id
    @Column
    private Integer id;

    @Column
    private String name;

    ...
}

As you can see two similar tables, just a simple ID plus name. Now the interconnecting entity:
@Entity
@Table(name = "Partnerships")
@IdClass(value = PartnershipId.class)
public class Partnership implements Serializable
{
    @Id
    @Column(name = "pq_id", insertable = false, updatable = false)
    private Integer pqId;

    @Id
    @Column(name = "company_id", insertable = false, updatable = false)
    private Integer companyId;

    @Column(name = "ordinal_nbr")
    private Integer ordinalNbr;

    @ManyToOne
    @JoinColumn(name = "pq_id", referencedColumnName = "id")
    private PQ pq;

    @ManyToOne
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private Company company;

    ...
}

Note the ... , insertable = false, updatable = false on @Column here.
public class PartnershipId implements Serializable
{
    private Integer pqId;

    private Integer companyId;

    public PartnershipId()
    {
    }

    public PartnershipId(Integer pqId, Integer companyId)
    {
        this.pqId = pqId;
        this.companyId = companyId;
    }

    ...
}

When running the following test code
public class Main
{
    private static String PERSISTENCE_UNIT_NAME = "standalonePu";

    private static EntityManagerFactory emf;
    private static EntityManager em;
    private static EntityTransaction trans;

    public static void main(String[] args)
    {
        setUp(PERSISTENCE_UNIT_NAME);
        trans.begin();

        PQ detachedPq = new PQ(1, "Test PQ");
        Company detachedCompany = new Company(1, "Test Company");

        PQ pq = em.merge(detachedPq);
        Company company = em.merge(detachedCompany);

        Partnership detachedPartnership = new Partnership(1, 1, 1);
        detachedPartnership.setPQ(pq);
        detachedPartnership.setCompany(company);

        Partnership partnership = em.merge(detachedPartnership);

        partnership = em.find(Partnership.class, new PartnershipId(1, 1));

        System.out.println("Persistent partnership = ("
            + partnership.getPQId() + ", "
            + partnership.getCompanyId() + ", "
            + partnership.getOrdinalNbr() + ")");

        trans.commit();
        close();
    }

    private static void setUp(String puName)
    {
        emf = Persistence.createEntityManagerFactory(puName);
        em = emf.createEntityManager();
        trans = em.getTransaction();
    }

    private static void close()
    {
        em.close();
        emf.close();
    }
}

... Hibernate fails with a really strange exception on trans.commit();:
ERROR: Invalid argument in JDBC call: parameter index out of range: 4
Exception in thread "main" javax.persistence.RollbackException: Error while committing the transaction
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:90)
    at main.Main.main(Main.java:44)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Invalid argument in JDBC call: parameter index out of range: 4
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1347)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1280)
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:78)
    ... 1 more
Caused by: org.hibernate.exception.GenericJDBCException: Invalid argument in JDBC call: parameter index out of range: 4
    at org.hibernate.exception.internal.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:148)
    at org.hibernate.exception.internal.SQLStateConverter.convert(SQLStateConverter.java:136)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:124)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:131)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:80)
    at $Proxy12.setInt(Unknown Source)
    at org.hibernate.type.descriptor.sql.IntegerTypeDescriptor$1.doBind(IntegerTypeDescriptor.java:57)
    at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:82)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:305)
    at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:300)
    at org.hibernate.type.ComponentType.nullSafeSet(ComponentType.java:358)
    at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2599)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2836)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3276)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:80)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:273)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:265)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:186)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:344)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1084)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:319)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:100)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:173)
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:73)
    ... 1 more
Caused by: java.sql.SQLException: Invalid argument in JDBC call: parameter index out of range: 4
    at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
    at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
    at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
    at org.hsqldb.jdbc.Util.outOfRangeArgument(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.checkSetParameterIndex(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.setInt(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:124)
    ... 22 more
Caused by: org.hsqldb.HsqlException: Invalid argument in JDBC call: parameter index out of range: 4
    at org.hsqldb.error.Error.error(Unknown Source)
    ... 31 more

The tested configuration is Hibernate 4.0.0.CR4 and HSQLDB 2.0. I've also tested this with MySQL 5 with the very same JDBC exception, so obviously Hibernate is generating incorrect code.
The workaround to resolve this is to put ..., insertable = false, updatable = false onto the relationships' @JoinColumns, but it's not really what I want.
So, is this a Hibernate bug? The above code should be correct from the perspective of JPA...

A: It's a bug:
https://hibernate.onjira.com/browse/JPA-24
I tested this with the JPA reference implementation EclipseLink 2.3 and it works perfectly.


text:
Q: Unity Ads not working on android device, Advertisement.IsReady() comes back with false I need some help with Unity. I am developing a simple mobile game and only the ads left. I am using Unity 5.5.3. I did set up everything in the services and included the code which works fine on PC. When i call the ShowAds function it displays a window says "This screen would be your ad unit, everything seems to be working"
However, when i build the game and install on android device the Advertisement.IsReady() comes back with false.
I have been researching for 2 days now and still no success!
So far:

*

*Updated Unity to 5.5.4p4

*Disabled the service and started everything from scratch

*Created a code which checks the internet connection which comes back with true.

*Changed the Build Settings/ Player Setting / Internet Access to Require

*Waited for minutes as some says Initialization sometime takes minutes.

Nothing seems to be working. On mobile there is no ads appearing at all. On PC everything works fine. However on PC i got an error says:
gameID "IDnumber" is not enabled
System.Net.Sockets.Worker:Receive()
I did not find any solution for this error so far.
Here are the codes:
IEnumerator TestInternet(){
        WWW internet = new WWW ("http://www.google.com");
        yield return internet;
        if (internet.error != null) {
            alertText.text = internet.error;
        } else {
            alertText.text = "connected";
            if (Advertisement.IsReady ()) {
                Advertisement.Show ();
                alertText.text = Advertisement.IsReady ().ToString();
            } else {
                alertText.text = Advertisement.IsReady ().ToString();
            }
        }
    }

A: OK! Finally I found a solution. Indeed, there was an issue with the project settings, that is why it gave the "IDnumber is not enabled" error. What I did is from the newly created project i copied all the .asset files and overwrite the existed files in the old project. For me is the following path:
User\Documents\newproject\ProjectSettings\
Now everything works fine. The only downside is that I need to redo some settings such as orientations, etc. I think copying only the UnityConnectSettings.asset would have solved the issue.
Anyway, thanks for everyone for helps!


text:
Q: Value of C of a bivariate discrete distribution I have the following math problem:
$ \sum^{\infty}_{j=1} \sum^{\infty}_{i=1}  C/(i*j)^2 = 1 $
where C is the value of the constant that makes this function be equal to 1.
I am not being able to find how to prove this converge and prove how C goes to $ 36/pi^4 $

A: $\sum\limits_{i=1}^{\infty} \frac 1 {i^{2}}=\frac {\pi^{2}} 6$. The given equation is $C \sum\limits_{i=1}^{\infty} \sum\limits_{i=1}^{\infty} \frac 1 {i^{2}j^{2}}=1$. You can sum w.r.t. $i$ first and then w.r.t. $j$.  When you sum w.r.t. $i$, $\frac  1{j^{2}}$ comes out of the summation so you get $C\frac {\pi^{2}} 6 \frac {\pi^{2}} 6=1$.

A: Use the identity $\sum_{k=1}^{\infty}\frac{1}{k^2}=\frac{\pi^2}{6}$ two times. You will get the answer.


text:
Q: Retry logic for Reactive Kafka is not working im using spring reactive kafka to create a consumer but retry logic is not working when there is an  exception.
@EventListener(ApplicationReadyEvnt.class)
public void consume(){
reactiveKafkaConsumerTemplate.reciveAutoAck()
.map(ConsumerRecord::value)
.flatMap(record->consumeException(record)) //this method throws an exception
.doOnError(err->log.error("Something went wrong : {} ",err))
.retrywhen(Retry.max(3).transientErrors(true)).retry()
.subscribe();

is there a way we can do something similar to @retryable as it does retry on actual topic and does retry on retryTopic and then pushes it DLT?
does reactive kafka pull the messages from all the partitions or is it creating a single consumer to poll the messages from single partition if so can we create multiple consumer threads as we do in traditional kafka by setting the concurrency ?
i tried logging the code but still couldn't figured why it was not working


text:
Q: CSS bar graph - very simple I have some very basic code and it works except everything aligns to the top...ideally the bars would align to the bottom. I suppose I could use fixed positioning as the dimensions are squared at 50px by 50px but I'd prefer something a little less "fixed".

I don't want to use a library or JS add on. Keeping this light weight is mission critical.
Also I'd prefer the bars were vertical. Any CSS guru care to shed the bit of light I seem to be missing? I've googled and most examples are far to complicated/sophisticated,

A: I would personally avoid setting xpos explicitly on every element, makes things less maintainable. In some scenarious percentage-basedvalue dumps would be more appropriate too. With that in mind, an imo more scalable and semanticaly correct approach has been mocked up in a fiddle. HTML:

and CSS:
.graph {
    border: 1px solid #aeaeae; background-color: #eaeaea;/*"canvas" styling*/
    float:left; /*should be clearfix'd instead, but this is OK for a demo*/
}
.graph li {
    width:8px; height:50px; /*set a bar width and a full height*/
    float:left; /*to have bars "left-aligned"*/
    position:relative; /*needed for the actual bar fill element*/
    margin:2px;
 }
 .graph li+li {
    margin-left:0; /*avoid margin double-up between bars as they don't collapse*/
 }
 .graph span {
    position:absolute;right:0;bottom:0;left:0; /*"bottom-align" the bars,
                                                  widths will be set inline*/
    background-color: #aeaeae;
 }

This also gives you potential to get quite fancy - bars could have content with a negative text indent for semantic value or  elements could be abandoned altogether in favor of pseudo-elements.

A: First of all, separate your CSS from your HTML. You're repeating too much code when you could just use a bar class for your inner divs.
bottom: 0 doesn't change anything for relatively positioned div.
If you wish to use relative positioning, get rid of float and bottom and use display: inline-block and vertical-align: baseline;. Also, in this case, you need to get rid of any space in the HTML between the inner divs (newline).
Like this (you can see the demo at http://dabblet.com/gist/2779082 ):
HTML

CSS
.graph {
    width: 50px;
    height: 50px;
    border: 1px solid #aeaeae;
    background-color: #eaeaea;
}
.bar {
    width: 8px;
    margin: 1px;
    display: inline-block;
    position: relative;
    background-color: #aeaeae;
    vertical-align: baseline;
}

A: Kolink's answer is correct. Each bar div's width is 8px, plus margin-left and margin-right, 8+1+1=10px. So I suggest, set the left value to 0px, 10px, 20px ...

The css should look like this(I grouped some general css rules):
.wrapper{
  border: 1px solid #aeaeae;
  background-color: #eaeaea;
  width: 50px;
  height: 50px;
  position : relative;

}

.wrapper > div{
  bottom: 0px;
  width: 8px;
  position : absolute;
  background-color: #aeaeae;
  margin: 1px;
  display : inline-block;

 }

You can check this link: http://jsfiddle.net/zhujy_8833/AFbt4/ to see the result of the above code.

A: If you give the parent position: relative, then you can use position: absolute for child div to place them in precise coordinates by setting left, top, right, bottom, width, height you can precisely control the placement of the bars in your bar chart.

.graph {
    position: relative;
    width: 54px;
    height: 54px;
    border: 1px solid blue;
    background-color: lightgrey;
}

.bar {
    position: absolute;
    border: 1px solid blue;
    background-color: yellow;
}

A: Use position: absolute, and instead of float:left; use left: 0px;, 8px, 16px and so on.
Also add position: relative to the container.


text:
Q: How Do You Handle Server Dependencies in Ansible Roles? I'm new to Ansible.  I have the following directory structure for my Ansible playbooks:
$HOME/playbooks
├── project1
├── project2
└── roles

I collect my commonly used roles such as my "nginx" role in the role directory and then I'll reference these roles in my project directories by adding the following line to each project's ansible.cfg file:
# $HOME/playbooks/project1/ansible.cfg
[defaults]
roles_path = $HOME/playbooks/roles

How do you configure your individual Ansible playbook tasks and and common role tasks when a common role task depends on which server the task is being run on?  In my case, I have a "webservers.yml" playbook for configuring my web server and a "fileservers.yml" playbook for configuring my file server.  My website will run on my web server but my static and media files will be served from a separate file server.  I currently include the following task in my nginx role's main/task.yml file:
# $HOME/playbooks/roles/nginx/tasks/main.yml
- name: create nginx config file
  template: src=nginx.conf.j2
            dest=/etc/nginx/sites-available/{{ domain }}.conf
  notify: restart nginx
  become: True
  tags: nginx

The problem is that the nginx config files on each server will be a little different since (I think) the nginx process running on my web server will need to redirect static file requests to the nginx process running on my file server.  Should I leave the "create nginx config file" task in my common nginx role and have it copy a minimal template onto each server but then call that task again in my webserver and fileserver playbooks and have each one deploy a server-specific version of the config file (e.g. nginx.webserver.conf.j2 versus nginx.fileserver.conf.j2)?  Should I just leave the create config file out of my main role task and just execute it in each playbook? (This approach seems wrong to me)  Or is there a more robust way to do this?
Thanks!

A: If the nginx configuration is different on each machine, then you should have inventory variables to drive the generation of the configuration file on each server.  Template out your nginx.conf file appropriately to handle your webserver and fileserver configurations.  If the configuration is completely difference you should either consider having  separate roles (nginx_web and nginx_file) or at least separate jinja templates for each config.

A: Inventory or group variables as already mentioned by @Petro026 are one option. In your nginx role or in the configuration template you then simply check those variables.
But I think there are better options available in this case, since the roles are explicitly called in the context of the webservers or fileservers playbook. You can simply introduce a role parameter which affects how the role works.
- role: nginx
  mode: direct

Or for the webservers mode: redirect.
Then you can either filter on task level
- some: task
  when: mode == "redirect"

Or handle everything in the template per conditions.
{% if mode == "redirect" %}
# I am a webserver
{% else %}
# I am a fileserver
{% endif %}

Now, the outcome of this is exactly the same thing as if you had used group or host vars, but I think it is much more visible what is happening to someone looking at the playbook, that the nginx role supports different modes and where that info is defined (as a role parameter).

Should I just leave the create config file out of my main role task and just execute it in each playbook? (This approach seems wrong to me) Or is there a more robust way to do this?

This is another option. Indeed, putting the task right in the playbook seems wrong. But what about nested roles? That again gives you a clean solution.
Keep your nginx role as it is and just remove the part that differs between the fileservers and webservers.
Then you create two new roles. One named nginx_web and one nginx_file. Now in both roles you set a dependency to the common nginx role in <role>/meta/main.yml:
dependencies:
  - role: nginx
    tags: nginx

Now you only need to add the differing pieces into the tasks/main.yml of nginx_web and nginx_file, which looks like it only is that single template task. You even can keep the handler for restarting nginx in your common nginx role and call it from the other roles.
All you have to reference in your playbooks now is either nginx_web or nginx_file. The nginx role automatically is executed as a dependency before the task in nginx_web/file.

Update: Describing role parameters
Roles can be applied in different ways. As a string or as an dictionary. Example as a string
roles:
  - roleName

If you wish to add additional information, like tags, conditions or other parameters, you can provide a dictionary. In that case the role name goes into the dict key role:
roles:
  - role: roleName
    tags: someTag
    when: someVar is defined
    become: True
    foo: bar

All additional data is passed on to every task inside the role. Ansible will act as if tags, become and when were applied to every single task inside the role. Everything else, that is not known to Ansible will be treat as a variable.
Alternatively you can write the dict as JSON, because YAML supports limited JSON format.
roles:
  - {role: "roleName", tags: "someTag", when: "someVar is defined", become: True, foo: "bar"}

 But I find that butt ugly and prefer the pure YAML definition

The latter is the format that is shown in the documentation:

Also, should you wish to parameterize roles, by adding variables, you can do so, like this:
---

- hosts: webservers
  roles:
    - common
    - { role: foo_app_instance, dir: '/opt/a',  app_port: 5000 }
    - { role: foo_app_instance, dir: '/opt/b',  app_port: 5001 }


text:
Q: Python, FastAPI : Multi-Threading/Processing - Start/Stop Process with API Endpoints I have been trying to solve this one for quite a while now and cannot figure it out. Would appreciate some help with it. So I have a FastAPI server in which I have deployed a Drowsiness Detection Model/Script (dlib, opencv2, scipy). Now what I am trying to achieve is - Start and stop the DDM via API Endpoints. So the problem is - the uvicorn server is single-threaded, so when I run the DDM it will run in the same thread and when I try to stop the DDM it stops the entire server process (which is not something I want). I have tried forking the process and running the DDM on that process but it gives an error and crashes. I think using multithreading might help, I am not sure. Also if it does help me solve my issue I don't know how exactly to approach it. Relevant Code :
# Drowsiness Detection Script
def eye_aspect_ratio(eye):
    A = distance.euclidean(eye[1], eye[5])
    B = distance.euclidean(eye[2], eye[4])
    C = distance.euclidean(eye[0], eye[3])
    ear = (A + B) / (2.0 * C)
    return ear

def detect_drowsiness(monitor: bool):
    pid_file = open("intelligence/drowsiness_detection/dataset/pid.txt", "w")
    pid_str = str(os.getpid())
    pid_file.write(pid_str)
    pid_file.close()

    thresh = 0.25
    frame_check = 18
    detect = dlib.get_frontal_face_detector()
    # Dat file is the crux of the code
    predict = dlib.shape_predictor(
        "intelligence/drowsiness_detection/dataset/shape_predictor_68_face_landmarks.dat")

    (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_68_IDXS["left_eye"]
    (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_68_IDXS["right_eye"]
    cap = cv2.VideoCapture(0)
    flag = 0
    while monitor:
        ret, frame = cap.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        subjects = detect(gray, 0)
        for subject in subjects:
            shape = predict(gray, subject)
            shape = face_utils.shape_to_np(
                shape)  # converting to NumPy Array
            leftEye = shape[lStart:lEnd]
            rightEye = shape[rStart:rEnd]
            leftEAR = eye_aspect_ratio(leftEye)
            rightEAR = eye_aspect_ratio(rightEye)
            ear = (leftEAR + rightEAR) / 2.0
            if ear < thresh:
                flag += 1
                print("Detecting,{}".format(flag))
                if flag >= frame_check:
                    print("ALERT - Drowsy")

            else:
                flag = 0
    cap.release()

# Drowsiness detection for a user
@ router.get("/face/drowsy/start", response_description="Drowsiness monitoring for the user")
async def start_drowsiness_detection(background_tasks: BackgroundTasks):
    background_tasks.add_task(detect_drowsiness, True)
    return("Drowsiness monitoring ON")

@ router.get("/face/drowsy/stop", response_description="Drowsiness monitoring for the user")
async def stop_drowsiness_detection():
    pid_file_path = f"intelligence/drowsiness_detection/dataset/pid.txt"
    pid_file = open(pid_file_path, "r")
    if not os.path.exists(pid_file_path):
        return("Please start monitoring first")
    pid_str = pid_file.read()
    remove_file(pid_file_path)
    os.kill(int(pid_str), signal.SIGKILL)

    return("Drowsiness monitoring OFF")

Possible workaround :
# Drowsiness Detection Script
def eye_aspect_ratio(eye):
    A = distance.euclidean(eye[1], eye[5])
    B = distance.euclidean(eye[2], eye[4])
    C = distance.euclidean(eye[0], eye[3])
    ear = (A + B) / (2.0 * C)
    return ear

class DrowsinessDetector(Process):

    running = Event()

    def stop_monitoring(self):
        if self.running.is_set():
            self.running.clear()

    def start_monitoring(self):
        if self.running.is_set():
            return

        self.running.set()
        self.detect_drowsiness()

    def detect_drowsiness(self):
        thresh = 0.25
        frame_check = 18
        detect = dlib.get_frontal_face_detector()
        # Dat file is the crux of the code
        predict = dlib.shape_predictor("./shape_predictor_68_face_landmarks.dat")

        (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_68_IDXS["left_eye"]
        (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_68_IDXS["right_eye"]
        cap = cv2.VideoCapture(0)
        flag = 0
        while self.running.is_set():
            ret, frame = cap.read()
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            subjects = detect(gray, 0)
            for subject in subjects:
                shape = predict(gray, subject)
                shape = face_utils.shape_to_np(shape)  # converting to NumPy Array
                leftEye = shape[lStart:lEnd]
                rightEye = shape[rStart:rEnd]
                leftEAR = eye_aspect_ratio(leftEye)
                rightEAR = eye_aspect_ratio(rightEye)
                ear = (leftEAR + rightEAR) / 2.0
                if ear < thresh:
                    flag += 1
                    print("Detecting - {}".format(flag))
                    if flag >= frame_check:
                        print("ALERT - Drowsy")

                else:
                    flag = 0
        cap.release()

# Drowsiness detection for a user
drowsy = DrowsinessDetector()

@router.get("/face/drowsy/start", response_description="Drowsiness monitoring for the user")
async def start_drowsiness_detection(background_tasks: BackgroundTasks):
    background_tasks.add_task(drowsy.start_monitoring())
    return "Drowsiness monitoring ON"

@router.get("/face/drowsy/stop", response_description="Drowsiness monitoring for the user")
async def stop_drowsiness_detection(background_tasks: BackgroundTasks):
    background_tasks.add_task(drowsy.stop_monitoring())
    return "Drowsiness monitoring OFF"

I got this solution from Reddit but for some reason, it doesn't work. Any help will be much appreciated.

A: You can also just put your non async code into a standard sync route def. (This is actually the encouraged approach from FastAPI) FastAPI will then run that code in an external threadpool and manage it all for you. From there you could simply check the status of literally anything(files, redis, inMem dict, pub/sub) from within your while loop to stop the drowsiness detector.
https://fastapi.tiangolo.com/async/#path-operation-functions

A: While not explicitly mentioned in the FastAPI documentation, BackgroundTasks.background_tasks will create a new thread on the same process.
Using the first code you posted - when you store the PID (process ID) into a file in the detect_drowsiness() function, and then kill the process on stop_drowsiness_detection() route/function, you are effectively killing the very process that is running FastAPI.
In the background tasks section of FastAPI, in caveat, they mention:

If you need to perform heavy background computation and you don't necessarily need it to be run by the same process (for example, you don't need to share memory, variables, etc), you might benefit from using other bigger tools like Celery.

Relating to the second code you posted, the use of multiprocessing there seems to be towards the right direction. Without more details on why that specific implementation is not working, it's hard to help you further.


text:
Q: Calculate the four corners of a bounded plane given strike, dip, width, height, and center point? I am trying to plot a geological fault plane in MATLAB as a bounded rectangle. I want to be able to plot the corners of the bounded fault plane given the following inputs: strike, dip, center point of the plane, and the width and length of the rectangle. A schematic of the problem is shown below:

In the above diagram, $\alpha$ is the strike (relative to North), $\delta$ is the dip (relative to horizontal), $P(x_c,y_c,z_c)$ is the center point of the plane, $\mathbf{O}$ is the origin, and $\mathbf{A}$, $\mathbf{B}$, $\mathbf{C}$ and $\mathbf{D}$ are the unknown points I want to solve for.
First of all, given the inputs, is it possible to calculate the four corners? If so, what would be the simplest way to do this?
I feel like I could work it out doing a significant amount of trigonometry, but perhaps there is an easier way using vectors that someone already knows which would allow me to avoid re-inventing the wheel.
EDIT: I managed to work it out using trigonometry and came up with the following solution but I still think there is probably a much easier and more elegant way to do it:
alpha = 45; %strike
delta = 30; %dip
w = 4; %width (dipping side)
L = 9; %Length (side parallel to the surface)

A = [0,0,0]; % Pivot point at the surface

H = w*sind(alpha+90);
V = w*cosd(alpha+90);
Z = -w*sind(delta);

B = [L*sind(alpha) L*cosd(alpha) 0]+A;
C = [L*cosd(90-alpha)+H L*sind(90-alpha)+V Z]+A;
D = [w*sind(alpha+90) w*cosd(alpha+90) -w*sind(delta)]+A;

P = [A; B; C; D];

figure(1); p = patch(P(:,1),P(:,2),P(:,3),'red');
xlabel('EW Distance (km)');ylabel('NS Distance (km)');zlabel('Elevation (km b.s.l.)');
axis equal

Thanks.

A: As a first step suppose $O$ coincident with $A$, so you can find the unit vectors oriented as the sides $AB$ and $AD$. That is the vectors:
$$
\vec u=(\sin \alpha,\cos \alpha, 0)^T \qquad \vec v=(\cos \delta,0,-\sin \delta)
$$
so the vector orthogonal to the plane $ABD$ is:  $$\vec n=\vec u \times \vec v$$
anni, since the plane have to contain the point (correspondent to)  $\vec P$, its equation is:
$$
\vec n \cdot (\vec x-\vec P)=0
$$
Now, intersect this plane with the coordinate planes $z=0$ and $y=0$ and you can find the points $A$ and $D$ and from these the other points.


text:
Q: Join multiple values in select dropdown I have an ajax call in codeigniter that will always return only two values: team_id1 and team_id2. I'm trying to join the two results as one value value="1:2" instead of value="1", value="2". I tried el.join(":"); but that doesn't do anything.  I'm assuming the appendChild() is prohibiting the join. Is there a work around? I need the values this way for a dependable dropdown. Thank you for looking!
function alertContents() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            var data = JSON.parse(httpRequest.response);
            var select = document.getElementById('match');
            if(emptySelect(select)){
                for (var i = 0; i < data.matchup.length; i++){
                    var el = document.createElement("option");
                        el.textContent = data.matchup[i].team_id;
                        el.value = data.matchup[i].team_id;
                        select.appendChild(el);
                }
            }
        } else {
            alert('There was a problem with the request.');
        }
    }
 }

A: I think what you are looking for is:
el.value = data.matchup[i].team_id1 + ":" + data.matchup[i].team_id2

or
el.value = data.matchup[0].team_id + ":" + data.matchup[1].team_id

The key is that you can use simple string concatenation to get your desired value
var team_1 = 'a';
var team_2 = 'b';

var value = team_1 + ':' + team_2; // = 'a:b'


text:
Q: Tar extract size Is it possible to find out, what will be size of a directory after extract ?
If I do have a tar file in gz,bz2 or xz format of 1GB then is there any way to know beforehand that this tar file will need so much size for extracting the content ?

A: An uncompressed tarball is approximately the same size as its extracted contents, so you can get a very good idea of the extracted size by determining the size of the original tarball (pre-compression):
xz -l tarball.tar.xz
gzip -tl tarball.tar.gz

respectively for xz and gzip (although gzipped files larger than 4GB won't report the correct size).
bzip2 doesn't appear to have an option to show the size of the file before compression, so the easiest option is to decompress and count:
bunzip2 -c tarball.tar.bz2 | wc -c

which also works for large gzip files:
gunzip -c tarball.tar.gz | wc -c

A: check here...
https://stackoverflow.com/questions/2712173/check-the-total-content-size-of-a-tar-gz-file
$ tar tzvf archive.tar.gz | sed 's/ \+/ /g' | cut -f3 -d' ' | sed '2,$s/^/+ /' | paste -sd' ' | bc

gzsize <your file>


text:
Q: Compare a logical data frame and a numeric data frame I have 2 data frames:
> df1
  a   b  c
1 1a 11 21
2 2a 12 22
3 3b 13 23
4 4b 14 24
5 5b 15 25
> df2
  a      b     c
1 1a  TRUE  TRUE
2 2a FALSE FALSE
3 3b  TRUE FALSE
4 4b  TRUE  TRUE
5 5b FALSE FALSE

I need to keep only the TRUE values of df1 and replace the FALSE values with NA like this:
> df3
  a     b     c
1 1a   11    21
2 2a   NA    NA
3 3b   13    NA
4 4b   14    24
5 5b   NA    NA

I've been thinking to use a for loop to check each positions of the data frames (only b and c columns) but I wonder if there's a base function or package that I could use.
PS. I need column a to be present all the time in the process in order to not get lost.
Thank you all.

A: If you know that both data.frames have the same values of a in the same order, you can do
if(all(df1$a==df2$a)) {
    is.na(df1[,-1]) <-!df2[,-1]
    # alternatively
    # df1[,-1][!as.matrix(df2[,-1])] <- NA
}

The is.na function allows reassignment and will place NA values wherever the right hand side is TRUE


text:
Q: Swift Compiler Error Class Variable not yet supported in Xcode 6.2? How to I fix this This is the code in my commonutils.swift folder.   I am getting an error stating class variable not yet supported.  Can someone help me to understand what to do so that I can fix this?  Please
class CommonUtils: NSObject {
  class let cache = NSCache()

  class func clearCache() {
    cache.removeAllObjects()
  }

  class func cacheObject(object: AnyObject, key: String) {
    cache.setObject(object, forKey: key)
  }

  class func cachedObject(key: String) -> AnyObject? {
    return cache.objectForKey(key)
  }

  class func showAlert(title : String, message : String, delegate : NSObject) {
    let alert = UIAlertView(title: title, message: message, delegate: delegate, cancelButtonTitle: "OK")
    alert.show()
  }

  class func showAlert(title : String, message : String, delegate : NSObject, button : String) {
    let alert = UIAlertView(title: title, message: message, delegate: delegate, cancelButtonTitle: button)
    alert.show()
  }

  class func getTextHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat {
    let nsString = NSString(string: text)
    let attributeDict : NSDictionary = NSDictionary(object: font, forKey: NSFontAttributeName)
  }

  class func getWidthOfString(text: String, font: UIFont) -> CGFloat {
    let attributeDict : NSDictionary = NSDictionary(object: font, forKey: NSFontAttributeName)
    let attributedString : NSAttributedString = NSAttributedString(string: text, attributes: attributeDict as [NSObject : AnyObject])
    return attributedString.size().width
  }
}


text:
Q: Separate tables for the user? I'm constructing a database for my forum. One of my tables holds all the user information(username, age, gender, etc). It contains 26 columns, including several LONGTEXT like the "About Me".
My question, for performance and speed when using MySQL queries, would it be better to create two separate tables for the user: One with important information(username, password) and a second with less-important information(about me, age, gender, etc)?
Thank you!

A: If you're bringing back the data one user at a time it's probably just best to keep the data all in the same table. I would only break it out if you were going to pull back multiple users (and a lot of them) including the LONGTEXT, or if you end up with many of the same thing belonging to the user such as addresses, etc.


text:
Q: Let $X$ be compact and $f:X\to\mathbb{R}$ s.t. each $x\in X$ has a nbh where $f$ attains its minimum. Show $f$ attains minimum on $X$.
Consider a compact topological space $X$ and a map $f:X\to\mathbb{R}$
  such that each $x\in X$ has a neighborhood where $f$ attains its
  minimum. Show that $f$ attains its minimum on $X$.

My attempt:
I was thinking of covering $X$ with all the neighborhoods where $f$ attains a minimum, so something like $X\subseteq \bigcup_{x\in X} U_x$. Then, by compactness, there would be a finite subcover. I don't see how I can conclude that a minimum is attained from this information: I could possibly go over all sets of the subcover and take the overall minimum that $f$ attains (which exists, as the subcover is finite), but am I guaranteed that this minimum is the minimum of $f$ on $X$?

A: For each $x\in X$ we have open neighborhood $U_x$ of $x$ such that there is $t_x\in U_x$ such that $f(t_x)\leq f(t) \ \forall t\in U_x$.
By compactness of $X$, we have finite subcover $\{U_{x_1},...,U_{x_n}\}$ of $X$.
Hence ,$f(t_{x_i})\leq f(t) \ \forall t\in U_{x_i}$  for $i=1,2,...,n.$
$\min\{f(t_{x_i})\}_{i=1}^n =f(t_0)$ is required minimum.

A: Yes, your approach is correct. Say the minimum over all the sets of the subcover is f(t). This guy is your candidate to be the minimum of f.
Suppose by way of contradiction, that there exists b ∈ X such that f(b) is strictly less than f(t). Then b is not an element of any set of the finite subcover. This would be a contradiction with the fact that every open covering of the space admits a finite subcover.


text:
Q: save the key of an item selected from spinner of retrieved data by onDatachage I can retrieve data from my database firebase the spinner is full but I can't save an item selected I put the line
uaselected = uaSpinner.getSelectedItem().toString().trim();
after OnData change to save an item selected but it return null as it is executed first before the function OnData change any help please

A: use this method.
  spncountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    country_data=spncountry.getSelectedItem().toString();
                                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

A:   databasereference = database.getReference();
    mAuth = FirebaseAuth.getInstance();
    areaSpinner = (Spinner) findViewById(R.id.spinneretab);

      databasereference.child("UA_unity").addValueEventListener(new com.google.firebase.database.ValueEventListener() {
                @Override
                public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
                    final List<String> etab = new ArrayList<String>();
                    final List<String> keyunity = new ArrayList<String>();
                   // uaselected = areaSpinner.getSelectedItem().toString().trim();

                    for (DataSnapshot child: dataSnapshot.getChildren()) {
                        nameua = (String) child.child("nom_UA").getValue();
                        keyua = child.getKey();
                      //  keyunity.add(keyua);
                      //  databasereference.child("Users").child("UA_ID").setValue(keyua);
                        etab.add(nameua);
                    }
                    ArrayAdapter<String> areasAdapter = new ArrayAdapter<String>(add_info_user.this, android.R.layout.simple_spinner_item, etab);
                    areasAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    areaSpinner.setAdapter(areasAdapter);
                    uaselected = areaSpinner.getSelectedItem().toString().trim();

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }


text:
Q: EF Core duplicate keys: The instance of entity type '' cannot be tracked because another instance with the key value '' is already being tracked I'm working on a form using EF Core in Blazor Server. I had a number of issues with entity tracking so I set all of my queries to AsNoTracking and designed my service to create a new instance of dbcontext for each query. I think this is appropriate as none of the returned values will be edited - only the form data that users enter and the id references to the queried fields, such as employee numbers, will be stored. For inserting data, I use this:
using var context = Factory.CreateDbContext();
context.SetupForm.Attach(model);
context.Entry(model).State = EntityState.Added;
await context.SaveChangesAsync();

I am attaching the data rather than adding it and then setting the form object state to added. This ensures EF Core doesn't attempt to insert the existing employee objects when it inserts the form data.
The trouble starts in a section of the form that can have as many items as the user wants. The select a couple of employees and type in relevant data. When they submit the form, they may have selected the same employee in multiple items. As these employees were selected from separate contexts, they are two separate instances with the same ID. Of course, EF Core doesn't like this and throws errors like this one:
The instance of entity type 'Principal' cannot be tracked because another instance with the key value '{EmployeeID: 1234}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

I understand why this error is occurring but I need to be able to attach multiple entities in this way. How can I work around this issue?
One thing I could do is assign the foreign keys manually but that would be rigid and require updates whenever the model changes.

A: just try this
using var context = Factory.CreateDbContext();

context.Set<Principal>().Add(model);
//or maybe context.Principals.Add(model);

await context.SaveChangesAsync();

A: This seems to do the trick! What it does is mark any entity that lacks a key as added. Otherwise, the entity is ignored entirely.
using var context = Factory.CreateDbContext();
context.ChangeTracker.TrackGraph(model, node =>
{
     if (!node.Entry.IsKeySet)
     {
          node.Entry.State = EntityState.Added;
     }
});
await context.SaveChangesAsync();

None of the items that have a key will need to be inserted. Treating them as untracked then solves any issues with duplicates and only inserts the rows that need it.
More information: https://learn.microsoft.com/en-us/ef/core/change-tracking/identity-resolution#resolve-duplicates


text:
Q: Using SEDE to track progress on the Electorate badge Almost identical to this SEDE query, I was trying to query for all my votes and determine how many were on questions, answers, and comments. Starting simply, I wanted to grab all my votes and their type - expecting results such as:
╔════════════════════════════════╦══════════╗
║ Post Link                      ║ Name     ║
╠════════════════════════════════╬══════════╣
║  Some awesome question's title ║ UpVote   ║
║  Not an answer                 ║ DownVote ║
║  etc...                        ║ ...      ║
╚════════════════════════════════╩══════════╝

But instead I got:
╔════════════════════════════════╦══════════╗
║ Post Link                      ║ Name     ║
╠════════════════════════════════╬══════════╣
║  A favorite question           ║ Favorite ║
║  Another favorite question     ║ Favorite ║
║  etc...                        ║ ...      ║
╚════════════════════════════════╩══════════╝

Therefore, for SO, I queried:
SELECT COUNT(*)
FROM Votes
WHERE UserId = ##UserId:Int##

The results were 22 - the number of my favorite posts. Is this as intended? I was working under the assumption that the Votes table would contain data on users' votes, not favorites. I realize I can count my votes another way:
SELECT UpVotes + DownVotes
FROM Users
WHERE Id = ##UserId:Int##

But that won't help me with my overall goal: to count the number of my votes on questions, answers, and comments separately. I don't necessarily want someone to create this query for me - I want to experiment with SEDE. But is this possible, or would this violate voting anonymity and is therefore impossible altogether? If possible, can someone point me in the correct direction?
Note: The idea for this query came about as I was curious about my progress towards the Civic Duty badge versus the Electorate badge. This SEDE query for Worst Case Scenario isn't quite what I want. And I don't really want to manually go through all my cast votes and count the number cast on questions.

A:
The results were 22 - the number of my favorite posts. Is this as intended? I was working under the assumption that the Votes table would contain data on users' votes, not favorites.

Exact upvoting and downvoting data is kept private in SEDE to preserve voting anonymity. Most other vote types which are in the Votes table are public, however (such as Favorites and Bounties) -- they are also visible on your profile page.

But is this possible, or would this violate voting anonymity and is therefore impossible altogether?

No, it's not possible to fetch your votes per post type from SEDE. Exposing upvotes and downvotes with their post IDs would violate voting anonymity, and there are also no columns like "QuestionVoteCount" and "AnswerVoteCount" in the Users table.


text:
Q: Can we call EF DbContext to UnitOfWork, and its Set to Repository? If yes, then we are done... no need to design and implement repos and unit of work when using EF (with DbContext)
Maybe I missed something, but for me DbContext implements a perfect UnitOfWork (well the interface is missing... :-( ) and its .Set are the generic repos for entity T.
Why then people keep implementing repos what are using/have a context, and implement unit of works what are using/have one of more repos? They implementing a design patter using an implementation of the same design pattern.
(I know: EF DbContext is not implementing a usable interface which fits to UnitOfWork/Repo pattern, but beside this, missed I something?)
Thx in advance

A: Yes they are the implementation of unit of work and the repository pattern.
I think the only case where you need to use your own repositories or unit of work is when you are planing to separate your data access logic from the repository level . That means if you are going to use some another way of accessing database (like Nhibernate) later ,then it is easy to have your own repository layer.
And also if you need to have another type of datasources not only the entity framework, then it is better to have an abstraction layer for your data access like this.

A: You are right.
But people are implementing their custom versions on top of already existing if they miss some features (for example DbSet is too generic repository with lack possibilities for query reuse (for example with specification pattern)).


text:
Q: Using not common unicode character in Sphinx I need to write Lévy in sphinx documentation. The documentation is created from docstring in Python script.
In Python docstring I can write L\xc3\xa9vy and it throw now error when I run the script.
But the spinx render it as Lévy.
How can I achieve that text Lévy will not cause the crash of Python script (both P2.7 and P3.x) and also will be rendered by sphinx correctly?
(I will not need this often because the documentation is in English, so any workaround is acceptable.)


text:
Q: Expandable listview without children I am new to android development and also using expandable listview for the first time. I am creating an app where in I get all the contents of d expandable listview from webservice. I get all contents from the wevservice as well but then when there is no child of a parent in expandable listview the custom adapter merhod of expandable listview getchildcount () returns null and gives a null pointer exception how can I show only parent in the list with no child and both when  both are available??
Thank you
public View getChildView(int p_id, int c_id, boolean bln1, View view,ViewGroup viewgroup) {
    // TODO Auto-generated method stub

     if (view == null) {
            view = inflater.inflate(com.example.eventlive.R.layout.homescreen_list_item_child, viewgroup,false);
        }

        TextView textView = (TextView) view.findViewById(R.id.list_item_text_child);
        //"i" is the position of the parent/group in the list and
        //"i1" is the position of the child
        textView.setText(mParent.get(p_id).getArrayChildren().get(c_id));
        view.setBackgroundResource(R.drawable.child_bg);
        //return the entire view
        return view;
}

//counts the number of children items so the list knows how many times calls getChildView() method
@Override
public int getChildrenCount(int p_id) {
    // TODO Auto-generated method stub
    return mParent.get(p_id).getArrayChildren().size();
}

A: Just initialize an empty children array like this:
private HashMap<String, ArrayList<String>> mGroupsItems =
        new HashMap<String, ArrayList<String>>();
. . .
mGroupsItems.put(name_of_empty_group, new ArrayList<String>());


text:
Q: question about mixed spectrum of a linear operator $\mathcal{L}$ Suppose $\mathcal{L}$ is a bounded linear operator and I have the solution to Eigenvalue problem
$\mathcal{L} \phi + \lambda \phi = 0$
wish to solve the following PDE
$\left(-\partial_t + \mathcal{L}\right)u = 0$.
If the spectrum of $\mathcal{L}$ is continuous or discrete, then a general solution to the PDE is
$\int C_q e^{- \lambda_q t} \phi_q dq$
or
$\sum_q C_q e^{- \lambda_q t} \phi_q$,
where the $C$'s are constants.
But, what if the spectrum of $\mathcal{L}$ is mixed and has a continuous part, a discrete part, and a singular part?  Is there a general way to write the solution to the above PDE if I do not know the spectrum of $\mathcal{L}$?
This has come up in my research because I need to work with the $e^{- \lambda_q t}$ but I do not know what the spectrum of $\mathcal{L}$?

A: Well, I have to confess that I am not sure about your goals. In which space are you working? But there is always a way to represent the solution as a generazied exponential function, called operator semigroup. If your operator $\mathcal L$ is indeed bounded, then you can represent the solution via Dunford-Riesz calculus. A good reference for this and much more general cases is Engel-Nagel: A short course on operator semigroups, Springer.


text:
Q: Cannot call API within local network I guarantee this is a duplicate but I cannot find a solution. I simply wanted to test calling the API from another device using postman.
I configured CORS:
builder.Services.AddCors(options => {
    options.AddPolicy(
        name: "AllowAll",
        builder => {
            builder.AllowAnyOrigin();
        }
    );
});

Obviously I used the policy:
app.UseCors("AllowAll");

I even opened the port used by the API (7134) in my windows firewall.
So what am I missing?
P.S. Obviously I did not send the request to localhost but to the correct IP (192.168.178.29)

A: Remove  app.UseCors("AllowAll");
And also
from service dependency.
builder.Services.AddCors(options => {
options.AddPolicy(
    name: "AllowAll",
    builder => {
        builder.AllowAnyOrigin();
    }
);});

This works for me....
app.UseCors(options =>
        {
            options.AllowAnyOrigin();
            options.AllowAnyMethod();
            options.AllowAnyHeader();
            options.AllowCredentials();

        });


text:
Q: Setup https proxy for pip install command within tox environment I need to setup https proxy for the pip install command within tox environment.
Currenly, I have something like this:
...
[toxenv:test]
install_command = pip install {opts} {packages}
commands =
    <command1>
    <command2>
...

If I use just pip command, like:
pip install <package>

I will get into error, because I am behind the proxy.
So I do something like this and it work like a sharm:
https_proxy=<proxy_url> pip install <package>

But, the problem is that I need proxy to be setup only for pip install command, and for other commands (command1, command2, ...) https_proxy should be unset.
So the question is how to setup https_proxy for pip install command only in tox and make it not set for all other commands.
P.s. Doing something like this doesn't work:
install_command = https_proxy=<proxy_url> pip install {opts} {packages}

P.s.s. The pip --proxy option doesn't help too, since it sets the http_proxy only.
Beforehand thanks!

A: you can set env variable in tox sessions,  and wraps your pip command in a script
proxy_pip.sh
#!/bin/bash
https_proxy=$my_https_proxy http_proxy=$http_proxy pip $@

tos.ini
[testenv]
setenv =
   my_http_proxy = <proxy_url>
   my_https_proxy = <proxy_url>
install_command = proxy_pip.sh install {opts} {packages}
commands =
    <command1>
    <command2>


text:
Q: how to set up aws cognito for the following rules? I have this req
Admin: manages the user access to website and gives them the rights as a content manager.
Content manager: These users can use the website to search, create content and change the setting for the content in the website.
I set up user pool in Cognito gave the callback url so when I successfully login it redirects to the page That I provided.
I can't understand what it means to set up roles
I know groups with AWS roles like for access to s3 ,dynamo etc...
is this wrong requirement or it's possible to do?