text:
Q: MongoDB multi update consistency I have a collection similar to the below, of say 5,000,000 records.
{ "_id" : ObjectId("56d18f95d2961d1ddcb7244f"),
  "rec_id" : 0,
  "status" : "open",
  "updated by" : "A"
}

User B is trying to mark all status to "closed", with below command:
db.prod.update({},{'$set': {'status':'closed', 'updated by':'B'}}, false, true)

Let's say user B is able to update closed status to 100,000 records and the connection is lost, or some problem occurs, and the remaining docs are not updated. So the data is inconsistent, is there any way in which we can fix this kind of problem?
I need to mark all status to closed or nothing to closed.

A: The documentation states

When a single write operation modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic

Multi-row rollback is one of those things which are foregone in the NoSQL world, sadly.
That same link mentions the $isolated operator. This may be of some help, depending on the use case and topology.
Also documented is the so-called "two phase commit" pattern. This may require application changes, however, so may not be practical.
Five million rows isn't a silly-big number. Would it be possible to arrange an application outage until the writes succeed, with continuous retries? Maybe run the write application on the same hardware as Mongo so the network is no longer an issue.

A: My two cents.
based on documentation, I believe if you have single operation which leads changes to multiple documents is atomic. It will succeed regardless of if client is still connected or not.
BUT...
if while performing updates, your primary fails then you'll have inconsistent documents. Some will get changes while other will not (depending on configuration. i.e replication, write concerns etc)
In your case, I don't see any problem. once user fireup a update query, it doesn't mater if still connected or not. User may not have updated status, but operation will succeed as long as server is running and without any issue.
db.prod.update({},{'$set': {'status':'closed', 'updated by':'B'}}, false, true)

Remember mongodb queries run on server, not on client unless you are updating individual documents on client side inside a loop. In that case whatever queries client manage to push to client before disconnection, will succeed.

A: Frankly that two-phase commit is just a gimmick, and a very bad one because it's not even consistent after it starts ;)
Solution would be to build a log-based reader/writer on top of this collection. So you'd send all reads and writes through additional layer. If you had your IDs sorted ascending you could add something like
Update WHERE id < LAST : Status = closed
Then on read you need to get the item + all pending operations in log, and calculate the state of item based on that. On write you'd put the operation on top of log, and then some backend would modify the data in collection based on what you have in the log, removing log entry when operation is finished.
This way you'd have it non-blocking and atomic / consistent. But that would probably take some time to code ... don't know if that's worth it, for just one collection it shouldn't take a long time.
Maybe better would be to switch to normal SQL if you need transactions and consistency across the app. It's much easier to implement document-like behaviour in SQL that SQL-like behaviour in K/V stores.


text:
Q: How to present set of optional security questions I need to present the list of possible questions while clicking the button and after clicking the button it must be placed inside the text field. What is the best way to present the questions.

In the above image while clicking the arrow button I need to present the list of possibles questions
I have implemented the following is there some better ways then that
#pragma mark - pickerview

-(void)pickerview:(id)sender
{
    pickerView=[[UIPickerView alloc] initWithFrame:CGRectMake(0,[Util window_height]-260,[Util window_width],300)];
    // pickerView.transform = CGAffineTransformMakeScale(0.75f, 0.75f);
  //  pickerView.transform = CGAffineTransformMakeScale(0.85f, 0.85f);
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.showsSelectionIndicator = YES;
    pickerView.backgroundColor = [UIColor lightGrayColor];
    [pickerView selectRow:1 inComponent:0 animated:YES];
    [self.view addSubview:pickerView];
   // [contentView addSubview:pickerView];

}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;

}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{

    return [_items count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
        return[_items objectAtIndex:row];

}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{

    [pickerView removeFromSuperview];
    [Txt_SecurityQue setText:[_items objectAtIndex:row]];
     NSLog(@"Did select");
}

#pragma mark - securityQuestionsArray

-(void)securityQuestionsArray {

    _items =[[NSArray alloc]initWithObjects:
             @"Where do you want to retire?",
             @"Where did you vacation last year?",
             @"What is your personal address",
             @"What is your employer name",
             @"Who is your nearest relative",
             @"What is your best friend phone number",
             @"In what city were you born?",
             @"What was your childhood nickname?",
             @"Type your own question.",
             @"What was the make and model of your first car?",
             @"What time of the day was your first child born?",
             @"What is your oldest sibling's birthday month and year?",
             @"What was your childhood nickname?",
             @"What is the name of your favorite childhood friend?",
             @"In what city or town did your mother and father meet?",
             @"What is the middle name of your oldest child?",
             @"What is your favorite team?",
             @"What is your favorite movie?",
             @"What was your favorite sport in high school?",
             @"What was your favorite food as a child?",
             @"What is the first name of the boy or girl that you first kissed?",
             @"What was the make and model of your first car?",
             @"What was the name of the hospital where you were born?",
             @"Who is your childhood sports hero?",
             @"What school did you attend for sixth grade?",
             @"What was the last name of your third grade teacher?",
             @"what town was your first job?",
             @"What was the name of the company where you had your first job?",
                          nil];

}

A: This requires a custom control on iOS, there is not a built in "Combo box" like in OS X. You can either try building one yourself with custom UIView's, or use something like this link (codeproject.com). They have sample code for what I think you are asking for.

A: This isn't a trivial thing to implement, as iOS does not provide a native dropdown list. If you would like to use a dropdown button, you will have to place a UIButton where the arrow is, and upon tapping it, you would have to populate a UITableView below the UITextField. This would require a decent amount of work on your part, but is entirely possible.
Also, you could use the built in UIPickerView.

A: Use a picker view and button. On the click of button just show the picker view and after selection, just dismiss the picker.
array_from=[[NSMutableArray alloc]initWithObjects:
                @"In what city were you born?",
                @"What was your childhood nickname?",
                @"Type your own question.",
                nil];

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    NSUInteger numRows = [array_from count];
    return numRows;
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    [label setText:[array_from objectAtIndex:row]];
    [label setTextAlignment:NSTextAlignmentCenter];
    label.adjustsFontSizeToFitWidth = YES;
    return label;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: phaser on vscode launch I've created a simple game using Phaser on vscode.
I read that i need to run it locally in order to run it on chrome and i can't manage to do so using vscode's F5.
when im on "index.html" and pressing F5 it pops out an alert box that says "cannot find progrem to debug".
pressing F5 while im on any other file causes a error in the debugger "window is not defined"(when im on phanser.js)/"Phaser is not defined"(when im on any other file)
how can i start this program correctlly ? sorry for the basic question .

A: Had to install http-server from npm and run it in terminal.
tried it before, but accidently installed it not globaly.
now it works. thanks!

A: http-server works just fine. But if you want to debug the game easily. You might want to follow the steps in this post: https://divillysausages.com/2015/06/09/using-phaser-with-visual-studio-code/
It is an instruction for setting up Typescript phaser development in vscode, but the steps that teach you how to set up node server also applies to a javascript usage case. If you want to make it easy to debug(pause code executing while game running, etc.) Try to set it up in that way.


text:
Q: C++ - Cannot pass the object pointed by an iterator by reference I have the following piece of code, a function that tries to pass a reference to an object in a set (foo) to another function (goo).
/**************** working ***************/
{
    std::set<MyStruct> foo;

    MyStruct abc = *foo.begin();
    goo(abc);
}

int goo(MyStruct & st)
{
    //some code here
}

/**************** not working ***************/
{
    std::set<MyStruct> foo;

    goo( *(foo.begin()) );
}

int goo(MyStruct & st)
{
    //some code here
}

And the error list:
>file.cpp:190:45: error: no matching function for call to 'goo(const MyStruct&)'
>file.cpp:190:45: note: candidate is:
>file.h:33:9: note: int goo(MyStruct&)
>file.h:33:9: note: no known conversion for argument 1 from 'const MyStruct' to 'MyStruct&'

The first version compiles fine, while the second gives the error reported. I've seen the const keyword, but I'm not declaryng it const anywhere, and the set is not const. Can you explain me what I'm doing wrong?

A: A set contains immutable objects with unique values, but goo requires a non-const reference. Either change goo to take a const reference, use something other than a set, or make a copy of the object. So long as the object is in the set, it cannot be modified, so it cannot be passed to a function that modifies (or can modify) the value of the object.

A: The first version work because you are assigning const MyStruct& to a variable of type MyStruct, in this case the copy constructor take in. When calling goo the variable abc is modifiable.
The second version you are passing the dereference of begin, the key of the associative container is const (this is because would be really bad if the key could be changed when there is inserted in the container, the order could be mess up, Visual Studio has that problem some versions ago) in this case begin return as the error say const MyStruct& (non modifiable).
If goo would not change the value of the parameter, add const, if it modify his value, use the first case. In case you need to update the set with the modify value, erase and reinsert.

A: In the first case, you assign *foo.begin() to a variable (which is not const).
In the second case, you send *foo.begin() (which is internally represented as a const reference) to your method straight away.


text:
Q: Keeping and checking Process alive in Java 1.7
*

*How to make sure process (java.lang.Process) is alive in Java 1.7. In Java 1.8, there is isAlive() method. How can it be done in Java 1.7.

Thank you!

A: Probably wait too late, but since I faced the same problem, here is my solution:
Just copy the implementation of the Process.isAlive() method from Java 8:
public boolean isAlive() {
    try {
        exitValue();
        return false;
    } catch(IllegalThreadStateException e) {
        return true;
    }
}

A: with out knowing  about the context of need of the Process. But in general, we could use Threads with  Executors framework..
Executors.newCachedThreadPool()
Then submit Tasks to it...

A: I used the following for monitoring multiple processes launched through a Swing application. It follows the same logic mentioned by @mastah. See whether it helps.
package snippet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ProcessMonitor extends Thread {

    private Process process;
    private int exitCode;

    public ProcessMonitor(Process process) {
        this.process = process;
        start();
    }

    @Override public void run() {
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void setOutputStream(final OutputStream s) {
        new Thread(new Runnable() {
            @Override public void run() {
                InputStream is = process.getInputStream();
                int c ;
                try {
                    while((c = is.read()) >= 0) {
                        s.write(c);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void setErrorStream(final OutputStream s) {
        new Thread(new Runnable() {
            @Override public void run() {
                InputStream is = process.getErrorStream();
                int c ;
                try {
                    while((c = is.read()) >= 0) {
                        s.write(c);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public int getExitCode() {
        return exitCode;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        if(args.length == 1) {
            System.err.println("In child process.. going to sleep for 1 second");
            Thread.sleep(1000);
            System.err.println("In child process.. done sleep exiting...");
            System.exit(-1);
        }
        String[] pbArgs = new String[] {
          "java", "-cp", System.getProperty("java.class.path"), ProcessMonitor.class.getName(), "arg"
        };
        ProcessBuilder pb = new ProcessBuilder(pbArgs);
        pb.redirectErrorStream(true);
        System.out.println("Starting process: " + pb.command());
        final Process process = pb.start();
        ProcessMonitor pm = new ProcessMonitor(process);
        pm.setOutputStream(System.err);
        while (pm.isAlive()) {
            System.out.println("Process is still alive");
            Thread.sleep(1000);
        }
        System.out.println("Process exited with: " + pm.getExitCode());
    }

}


text:
Q: Apache error_log: File does not exist - undefinedadapters Browsing through the error_log, it seems to be flooded with the following error:
[Mon Feb 15] [error] [client {ip}] File does not exist: /var/www/vhosts/{site}/httpdocs/undefinedadapters, referer: {page-1.php}

[Mon Feb 15] [error] [client {ip}] File does not exist: /var/www/vhosts/{site}/httpdocs/undefinedadapters, referer: {page-2.php}

Done a few google searches, but I can't seem to find anything relevant.
Any ideas for what/where to look at ?
Server version: Apache/2.2.15 (Unix)
Server built:   Oct 16 2014 14:48:21
Server's Module Magic Number: 20051115:25
Server loaded:  APR 1.3.9, APR-Util 1.3.9
Compiled using: APR 1.3.9, APR-Util 1.3.9
Architecture:   64-bit
PHP 5.3.3 (cli) (built: Oct 30 2014 20:12:53)
Zend Engine v2.3.0,
    with the ionCube PHP Loader v4.6.0
Should I post the httpd.conf as well ? Having trouble formatting it here.
Thank you.


text:
Q: How to simplify to use ISNULL with LEFT OUTER JOIN to merge tables I need to merge below Table 1 & Table 2 as indicated in "Merge".

The query I wrote below works; but it is TOO SLOW! Is there any simpler way which returns it faster?
SELECT T1.Loc, T2.SO, T2.PO, T1.Item
FROM Table1 T1

LEFT OUTER JOIN Table2 T2
ON ISNULL(T1.[SO2],T1.[SO1]) = T2.[SO]

A: Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax:
SELECT *
FROM Table1 T1 LEFT OUTER JOIN
     Table2 T2
     ON COALESCE(T1.[SO2], T1.[SO1]) = T2.[SO];

There is no need to join to Table2 twice (much less getting a Cartesian product).  I prefer COALESCE() to ISNULL() simply because the former is the ANSI standard function for replacing NULL values.
I should add that for performance, two joins might be preferable:
SELECT T1.Loc, COALESCE(T2_2.SO, T2_1.SO) as SO,
       COALESCE(T2_2.PO, T2_1.PO) as PO, T1.Item
FROM Table1 T1 LEFT OUTER JOIN
     Table2 T2_2
     ON T1.[SO2] = T2_2.[SO] LEFT OUTER JOIN
     Table2 T2_1
     ON T1.[SO1] = T2_1.[SO] AND T1.[SO2] IS NULL;

It is easier for the SQL engine to optimize joins that use only equality and AND conditions, on the clean column references (that is, the columns are not the arguments to any function calls).

A: Hope this SQL full fill your requirement.
Select T2.Loc, T2.SO, T2.PO, T1.item from table 2 T2 join table1 T1
on T1.SO1 = T2.SO;


text:
Q: Format date as 'DD Month YYYY' Just have a mssql query that has a date in the format:
'2016-03-22 00:00:00.000'

I need to format it as:
'22 March 2016'

I'm using SQL Server 2012. I've tried googling and the usual 106, 112 codes don't seem to work.
Is there a specific code format I can use?

A: Use Format Function in SQL Server 2012
SELECT FORMAT(GETDATE(),'dd-MMMM-yyyy')

See Image for your datatype ref

A: Try the FORMAT function:
SELECT FORMAT(GETDATE(), 'D', 'en-gb')

If your version does not support the FORMAT function, you can do it by concatenating the date parts:
SELECT
    RIGHT('00' + CAST(DATEPART(DAY, GETDATE()) AS VARCHAR(2)), 2) + ' ' +
    DATENAME(MONTH, GETDATE()) + ' ' +
    CAST(DATEPART(YEAR, GETDATE())  AS VARCHAR(4))

A: Try this query:
SELECT CONVERT(VARCHAR, CONVERT(DATETIME, '2016-03-22 00:00:00.000'), 106)

You need to convert into DATETIME then you will get your desired output
More Datetime Sql formate
SQLFiddle
This may help you

A: Try Convert function for SQL server:
select convert(varchar(11),cast('2016-03-22 00:00:00.000' as datetime), 106)

A: How to change day, month, year in PHP:
echo $purchase_date=date('F-Y',strtotime('2022-03-22 00:00:00.000'));

Answer:
March-2022


text:
Q: Null Pointer Exception in mapreduce and GlobStatus I recently came across an issue when using Hadoop FileSystem API and GlobStatus while writing Mapreduce application.
Here's snippet of the driver program.
FileSystem fs = FileSystem.get(URI.create(args[0]), conf);
Path path = new Path(args[0] + args[1]);

FileStatus[] status = fs.globStatus(path);
Path[] paths = FileUtil.stat2Paths(status);

and here is how I invoke the program

yarn jar MyMapReduceTest01.jar com.abc.test.MyMapRedTestDriver /user/root/raw_data/ abc*

This results in the following exception
    Exception in thread "main" java.lang.NullPointerException
    at com.abc.test.MyMapRedTestDriver.run(MyMapRedTestDriver.java:42)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
    at com.abc.test.MyMapRedTestDriver.main(MyMapRedTestDriver.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:136)

The files in the /user/root/raw_data/ directory are named as
abc_01.txt
abc_02.txt
...

A: there seems to be a problem in the way the globstatus is handled in the Hadoop filesystem API.
To make the above program work without any code change I just needed to change the command to

yarn jar MyMapReduceTest01.jar com.abc.test.MyMapRedTestDriver /user/root/raw_data/ abc_*


text:
Q: (Perl's) GD Graph - Limit of plotted data? Haven't had many good experiences with GD::Graph when trying to plot larger data arrays.
What i have is two arrays, one is 2mln float/integer values, the other - various length but less than 2 million. Trying to plot them on the same line graph. (i do create a 0..2000000 index array for the x axis). Everything has worked when tested for 1 million of the values.
Larger array sizes throw up:

Not a GD::Image object at
  /usr/local/lib/perl5/site_perl/5.8.9/GD/Graph.pm
  line 182

not even sure where in my script it fails - no other errors
Did not find anything in the official documentation about memory/data limits of GD::Graph.
Additional info that might help you people help me:

*

*my script attempts to save graphs into a file (.gif)

*pretty sure this is not due to my web server memory limit (it would show a message about killed perl process)

Thanks

A: Could you maybe post the code in question so we can give it an inspection and see what's up? at first guess, it does sound like a memory issue related to inability to allocate that much storage space, the allocation is returning a null pointer in the underlying system and thus Perl can't actually create the GD object, since you're trying to allocate somewhere in the range of 125MB off the heap with 2000000 64bit (assuming you're on a 64bit host) ints/floats.  But, it could just be something syntactical.


text:
Q: Script to Copy cells to another sheet, for example, based on the Background Color of the Cell First of all I'm completly new to Google Sheets and Scripts so I'm trying to learn all by myself, so sorry if I'm asking something 'stupid'
So my problem is: I've created a Script to basically add a Background color to a cell, based in a certain condition. What I wanted to do now was identify all cells with that added Background color, select the entire row in which they are contained and copy all the information to another sheet.
I was trying to do it with an if condition, but I have no idea how to select the entire row or if the condition I'm using to get the Background color is right. Can anybody help me? Thank you so much!
var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getSheetByName('Sheet1');
  var r = s.getRange('F:F');
  var v = r.getBackgrounds();
  for(var i=v.length-1;i>=0;i--)
    if(v =='B7E1CD')
      s.getCurrentCell.copyTo(spreadsheet.getRange(20,1)); //don't mind this instruction, I know it isn't right

A: Explanation:
Your goal is to filter only the rows for which the background color in column F is '#b7e1cd' and copy these values to a different sheet.

*

*You don't need a loop to achieve this goal, you can directly filter the rows for which the background color in F is '#b7e1cd'.
const new_values = values.filter((_,i)=>colors[i]=='#b7e1cd');

where values is defined as the full datarange of Sheet1:
const values = sh.getDataRange().getValues();

You can use copyTo in case you want to move data within the same spreadsheet file. This is why I prefer getRange/setValues because it does not have this limitation.
Solution:
The following script will paste the values starting from the cell A1 of Sheet2. If you want a different starting cell, modify 1,1 in target_sh.getRange(1,1,..) to a different cell reference.
function myFunction() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1'); // put the name of the source sheet
  const target_sh = ss.getSheetByName('Sheet2'); // put the name of the target sheet
  const colors = sh.getRange('F1:F').getBackgrounds().flat();
  const values = sh.getDataRange().getValues();
  const new_values = values.filter((_,i)=>colors[i]=='#b7e1cd');
  target_sh.getRange(1,1,new_values.length,new_values[0].length).setValues(new_values);
}

Updated code based on your sheet:
function iftest() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('HH 2 - Main Database'); // put the name of the source sheet
  const target_sh = ss.getSheetByName('HH 1 - New Database'); // put the name of the target sheet
  const colors = sh.getRange('F1:F').getBackgrounds().flat();
  console.log(colors);
  const values = sh.getDataRange().getValues();
  let LastRow = target_sh.getLastRow();
  const new_values = values.filter((_, i) => colors[i]=='#ff6d01');
  target_sh.getRange(LastRow+1,1,new_values.length,new_values[0].length).setValues(new_values);
}


text:
Q: Configure laravel using mssql and mysql I am using laravel for an application which is using MySQL for all the data from/to web user interface.
My situation is: actually I have another application running exclusively with MSsql server.

How could I run a SELECT query MSsql, get the data and then update a
  MySQL table using a built in constructor?

Outside Laravel a try this and work perfectly:
<?php
$serverName = "MYPC/sqlexpress";
$dataBase = "b2";
$UID = "root";
$PWD = "1234567890";

Try {
$conn = new PDO("sqlsrv:Server= $serverName;DataBase=$dataBase", $UID, $PWD);

$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

Catch(Exception $e)
{
die( print_r($e->getMessage() ) );
}

$Select = "SELECT * FROM AtdRecord";

$t = sqlsrv_query(conn, $select);

While($row=sqlsrv_fetch_array($t, SQLSRV_FETCH_ASSOC)) {
echo $row['RecDate'];
}

Inside laravel, configured over .env file, For MySQL query's I used the build in constructor
DB::

Just that easy
I am rookie in this. Hope I express my self correctly.


text:
Q: Linear maps on irreducible representation of G Let G be finite group. Let V be irreducible representation of G over $\mathbb{C}$. For $f\in \mathbb{C}[G]$, consider $\phi_f$ on V, defined by $\phi_f(v) = f.v$ (scaling by f).
I know, $\phi_f$ is $\mathbb{C}$-linear. Does the converse true?
If $\phi$ is $\mathbb{C}$- linear on V, does there exist $f\in \mathbb{C}[G]$ such that $\phi=\phi_f$
Please help me with this.

A: We want to show for any irrep $V_i$ that the map $\rho:\mathbb{C}[G]\rightarrow End_{\mathbb{C}}(V_i)$ is surjective. We will prove this using some character theory, solets look at the (algebra) product of these maps, over a chosen set of irreducibles $V_i$.
\begin{equation} \mathbb{C}[G]\rightarrow \prod_{V_i} End_{\mathbb{C}}(V_i)\end{equation}
Comparing dimensions, we see that both sides have dimension $|G|$, by the sum of squares of dimensions formula. (This is secretly equivalent to the statement we want to prove, but it definitely seems friendlier).
So to show surjectivity, we just need to show injectivity, since these spaces have the same dimension. So if we had an element $x\in \mathbb{C}[G]$ that acted as zero in every irreducible representation, by linearity, it would act as zero on every representation.
But this cannot occur, as it would contradict the fact that $x$ acts as a nonzero linear transformation on $\mathbb{C}[G]$, viewed as a representation via left multiplication. Thus, the map is injective, hence surjective, giving your result.


text:
Q: How to encode hyphen for POST I want to send a POST request to an API.
API parameters
api = {
 'url': 'test.com',
 'path': 'myapi.cgi',
 'port': 443,
 'method': 'POST',
 'params': {
   'o': 'my-org',
   'i': '322e9c5eefd1953f788bdefdd7e627d1_bb604d924aefdd7c25b14a382dea3585'
 }
}

I send HTTPS request like this:
conn = httplib.HTTPSConnection(self.api['url'], self.api['port'], timeout=5, context=httplib.ssl._create_unverified_context())
conn.request(self.api['method'], self.api['path'], urllib.urlencode(self.api['params']), headers)

Here I encode the parameters with urlencode.
I get a response from the API: Invalid chars in organization.
The call worked when I used an organization name without a hyphen. So, I guess the problem is with - char.
How to encode the my-org word correctly? Is - a legitimate character for the POST request, maybe I don't need to encode it?
I don't have access to the API source code.

A: No need to encode, basically you need to change all the ' for " then add at the start of the payload ''' and at the end.
Example:
api = '''{
 "url": "test.com",
 "path": "myapi.cgi",
 "port": 443,
 "method": "POST",
 "params": {
   "o": "my-org",
   "i": "322e9c5eefd1953f788bdefdd7e627d1_bb604d924aefdd7c25b14a382dea3585"
 }
}'''

This works with spaces, or special characters.
Regards.


text:
Q: Retrieve the camera sensor dimensions I'm looking for a way to calculate the camera sensor size using the iOS API.
Exif files contain the focal length and the focal plane X and Y resolutions, but I'm not sure how to retrieve the physical size of the sensor using this data.


text:
Q: Advice on how to show that the following inequalities hold I am trying to show that the following inequalties hold
$$\exp[\frac{k^2}{b^2 t}]  \log ^{\alpha_2 -1}(t) \left(\frac{1}{2} \log (t) -\alpha_2\right) \leq  \frac{k}{\sqrt{2 \pi b^2}} \leq  \exp[\frac{k^2}{b^2 t}] \log ^{-\alpha_1 -1}(t) \left(\alpha_1 + \frac{1}{2} \log (t)\right),$$
where $k$, $b$ are positive constants and $\alpha_1 > 1$ and $\alpha_2 > -4$ and $t$ is the time variable.
I am concerned if the inequalities will hold for all values of $t$, but it seems difficult to isolate $t$.
Obviously the standard approach will be to find the inflection points for both the lower and the upper bound and isolate the maximum and the minimum values, but that again requires isolating $t$ which seems really hard.
How can one prove such a problem.
Your help is greatly appreciated.


text:
Q: access denied while renaming .exe file We have a application developed with VB.NET and kept in windows server 2003. Users run the apllication through network. We were using this method for updating our application

*

*Create new .exe with updated code

*Rename old .exe file while users are running the application

*Copy new .exe in old exe path

*Delete old .exe following day

It was working fine.But from a week it is behaving strange. Its giving error Access denied  while renaming sometimes. After closing application on user side it will allow to rename. And sometimes after closing application on user side .exe will be automatically deleted. What is causing this? pl help

A: Maybe the application is in use somewhere..try killing the process from Task Manger and then try to rename it
Hope this helps

A: Just start cmd.exe and type rename "\Server\share\Dir\my.exe" Old.exe.
 You can do this over network


text:
Q: Pyvmomi Deploy OVF template gets 'Host did not have any virtual network defined' Error When I'm trying to use the deploy_ovf sample (pyvmomi) in order to deploy OVF file, Im getting this error in the CreateImportSpecResult:
error = 'Host did not have any virtual network defined'.
This causes that the spec_params is None.
When I manually checked the OVF file, it does contain the NetworkSection in the xml.
I also make sure I am deploying to the correct datastore.
Is there a way to ignore the network setting when deploying? Or some other way to bypass that?
Thanks!


text:
Q: SQLite error "near "@gmail": syntax error "flutter Here's the error I get:
E/SQLiteLog(25090): (1) near "@gmail": syntax error .
It seems like there is a problem in email input.
I guess there is nothing wrong in the creating of database.
creating db:
class UsersTable {
  static const String tableName = 'Users';
  static const String id = 'id';
  static const String email = 'email';

  static const String createQuery = '''
  CREATE TABLE IF NOT EXISTS $tableName (
    $id integer primary key autoincrement,
    $email text not null unique);''';

}

in model class:
class Users {
  late final int id;
  late String email;

  Users({
    required this.id,
    required this.email,
  });

  Users.fromDb(Map<String, dynamic> map) {
    id = map[UsersTable.id];
    email = map[UsersTable.email];
  }

}

in UserService class which I think is where the problem arise:
class UserService {
...
      Future<Users> getOrCreateUser({
        required String email,
        bool setAsCurrentUser = true,
      }) async {
        try {
          //we found the user
          final user = await getUser(email: email);

          if (setAsCurrentUser) {
            _user = user;
          }
          return user;
        } on CouldNotFindUser {
          //we didn't find the user
          final createdUser = await createUser(email: email);
          if (setAsCurrentUser) {
            _user = createdUser;
          }
          return createdUser;
        } catch (e) {
          rethrow;
        }
      }
Future<Users> getUser({required String email}) async {
    await _ensureDbIsOpen();
    final db = _getDatabaseOrThrow();
    final results = await db.query(
      UsersTable.tableName,
      limit: 1,
      where: 'email = ?',
      whereArgs: [email.toLowerCase()],
    );
    if (results.isEmpty) {
      throw CouldNotFindUser();
    } else {
      return Users.fromDb(results.first);
    }
  }
...}

in main class:
...
Widget build(BuildContext context) {
    return FutureBuilder(
        future: _userService.getOrCreateUser(email: userEmail),
        builder: (context, snapshot) {
          return Provider(
            create: (ctx) => HomePageController(),
            dispose: (ctx, HomePageController controller) =>
...

how can I solve this error?


text:
Q: Getting jwt token from a request header or response header I'm looking for enlightenment in regards to request headers and response headers.
Below taken from some google article
Request headers contain more information about the resource to be fetched, or about the client requesting the resource. Response headers hold additional information about the response, like its location or about the server providing it.
I'm trying to get a Bearer Token from a logged in User. The token in the newBearer is one I need. It has all the information, but my problem is the Request header has a Authorization Bearer and the response header has a Authorization: New Bearer. Which one is the correct one to take?
Can you take newBeaer token? cause when I do I get a lot of complaints with the below code.
When I just take the Authorization it works fine.
import { Injectable } from '@angular/core';
@Injectable()
export class TokenInterceptorService implements HttpInterceptor {
   intercept(req: HttpRequest<any>, next: HttpHandler):   Observable<HttpEvent<any>> {

      let token = req.headers.get('Authorization');
      let parsedToken = token.slice(7) /// which gives me my long token
      localStorgae.setItem('token', parsedToken ) /// set in storage to decode later on
      return next.handle(req);
   }
}

Should I be taking the token from the response or request headers?

A: JWT works this way
You send a login request to server. Server sends a JSON response with the jwt token. Client get the jwt token and set the headers for the next request that require authorization.
Then you set a header with authorization bearer, send it to server, then server check for authorization, and response with a new jwt token for the next request.
That is simple, but there is a lack of information about the client side.


text:
Q: Finder thinks item exists after it's already been deleted (Samba) First, I copied foo.7z to my SMB share (zfs zpool, Ubuntu 18.04 LTS, Samba 4.7.6) through finder. Over SSH, I moved it elsewhere on the server. I tried copying a different foo.7z again to the same location as the old one, but finder says:
The operation can't be completed because an item with the name "foo.7z" already exists.
This is not true, as the file isn't there anymore after I moved it.
Here's my smb.conf on the ubuntu server:
[global]
mangled names = no
dos charset = CP850
access based share enum = yes
unix extensions = no
fruit:aapl = yes
fruit:model = MacPro
unix charset = UTF-8
fruit:resource = xattr
workgroup = WORKGROUP
server string = %h server (Samba, Ubuntu)
dns proxy = no
log file = /var/log/samba/log.%m
max log size = 1000
syslog = 0
panic action = /usr/share/samba/panic-action %d
server role = standalone server
passdb backend = tdbsam
obey pam restrictions = yes
unix password sync = yes
passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
pam password change = yes
map to guest = bad user
usershare allow guests = yes

[SMB Share]
 comment = SMB Share
 path = /tank
 browseable = yes
 read only = no
 guest ok = no
 ea support = yes
 vfs objects = catia fruit streams_xattr
 map archive = no
 spotlight = yes
 readdir_attr:aapl_rsize = yes
 readdir_attr:aapl_finder_info = yes
 readdir_attr:aapl_max_access = yes

Using High Sierra 10.13.6.

A: Some unix commands use a database of data instead of searching for it.For example locate uses a prebuilt database to search your disk. Much faster but database may be slow to update and hence you'd be using a dated set of filenames for example. The database may take a day or two to update.


text:
Q: jQuery ui google map check if marker is in view I am using
http://code.google.com/p/jquery-ui-map/
I am trying to find a way when looping through markers, of finding out if the markers are visible within the current viewport.
Does anybody know how to do this. I have tried isVisible()

A: Don't know about jquery-ui-map, but in the raw google maps api v3 it's fairly simple:
var bnd = map.getBounds();
var ne = bnd.getNorthEast();
var sw = bnd.getSouthWest();
var pos = marker.getPosition();
if (pos.lat() >= sw.lat() && pos.lat() <= ne.lat() &&
    pos.lng() >= sw.lng() && pos.lng() <= ne.lng()) { // marker is in view
    ....
}

A: In the beta version there is a inViewport, see jquery google maps plugin filter by property


text:
Q: Google Cloud Storage : how many can create ACL In the google document, it says:

"The maximum number of ACL entries you can create for a bucket or object is 100"

does that mean I can create just 100 Regardless of objects or buckets? or I can create 100 each objects and bucket?
Any help? Thanks.

A: All objects and all buckets have an ACL list. Any ACL list may have up to 100 entries, but no more. So a bucket can have 100 entries in its ACL, and an object in that bucket may also have 100 entries in that object's ACL.
Note: it is generally not recommended to place large numbers of ACL entries in an object or bucket's ACL list. Instead, consider one of these alternatives, which both have the advantage of not needing to modify the bucket or object when adding or removing users and groups:

*

*Add the user or groups you need to your project's OWNER, EDITOR, and VIEWER roles, and use those roles in your bucket and object ACLs.

*Add the user or groups you need to a google group and then add that google group to your bucket and object ACLs.


text:
Q: Tablayout+viewpager in fragment, need to clear a edittext data in viewpager I have developed a project with Tablayout with 3 viewpager items, getting data in edittext from each viewpager, I need to clear all the data from viewpager and set all us empty, when button click event occurs which was set in last viewpager item.
This is parent fragment, Homefragment.class
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    view = inflater.inflate(R.layout.activity_main, container, false);
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this, view);

    ButterKnife.bind(this, view);
    final ViewPager viewPager = ButterKnife.findById(view, R.id.viewpager2);
    setupViewPager(viewPager);
    TabLayout tabLayout = ButterKnife.findById(view, R.id.tabLayout);
    tabLayout.setupWithViewPager(viewPager);
    next = ButterKnife.findById(view, R.id.nxt_btn);

    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
        }

    });

    return view;

}

private void setupViewPager(final ViewPager viewPager) {
    final ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
    adapter.addFragment(new Customer_details(), "Customer Details");
    adapter.addFragment(new Order_details(), "Order Details");
    adapter.addFragment(new Payment_details(), "Payment Details");
    viewPager.setAdapter(adapter);
    viewPager.setCurrentItem(0);

    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if (viewPager.getCurrentItem() == 2) {
                next.setVisibility(View.INVISIBLE);
            } else if (viewPager.getCurrentItem() == 0) {
                next.setVisibility(View.VISIBLE);
            } else if (viewPager.getCurrentItem() == 1) {
                next.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

}

    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); ++i) {
            View innerview = ((ViewGroup) view).getChildAt(i);
            setupUI(innerview);
        }
    }
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    //unbinder.unbind();
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }
    public void onButtonPressed() {
        startActivity(new Intent(null, MainActivity.class));
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

}
@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP
                    && keyCode == KeyEvent.KEYCODE_BACK) {

                // handle back button
                Intent i=new Intent(getActivity(),MainActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(i);
                getActivity().finish();
                return true;

            }

            return false;
        }
    });

}

}

Customer.class
public class Customer_details extends Fragment {

public static int selectedid;
public static EditText cname, cnumber, cnumber2, caddress, cpincode, clandmark;
public static Spinner spinner, snum, snum1, sp1, sp2;
public static RadioGroup radioGroup;
public static RadioButton radioButton;
TextView ctype, name, contact1, contact2, dispatch, address, pincode, landmark, source;
private PayOrder_Interface pay;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //return
    final View view = inflater.inflate(R.layout.activity_cdetails, container, false);

    cname = (EditText) view.findViewById(R.id.cname);
    cnumber = (EditText) view.findViewById(R.id.cnumber1);
    cnumber2 = (EditText) view.findViewById(R.id.cnumber2);
    caddress = (EditText) view.findViewById(R.id.caddress);
    cpincode = (EditText) view.findViewById(R.id.cpincode);
    clandmark = (EditText) view.findViewById(R.id.clandmark);

    String[] values = {"Select", "Retail", "Bulk"};
    spinner = (Spinner) view.findViewById(R.id.spinner);

    final String[] value = {"Select", "+91", "+64", "+355", "+213", "+214", "+54", "+374", "+43", "+994", "+1", "+973", "+880", "+32", "+1-(441)", "+591", "+387", "+267", "+55", "359", "+673"};
    snum = (Spinner) view.findViewById(R.id.spinner3);

    String[] val = {"Select", "+91", "+64", "+355", "+213", "+214", "+54", "+374", "+43", "+994", "+1", "+973", "+880", "+32", "+1-(441)", "+591", "+387", "+267", "+55", "359", "+673"};
    snum1 = (Spinner) view.findViewById(R.id.spinner4);

    String[] v = {"Select", "Online", "Existing", "Sales Team", "Store", "Zomato"};
    sp1 = (Spinner) view.findViewById(R.id.spinner_2);

    String[] b = {"Select", "GaarG Store 1", "PG Tech"};
    sp2 = (Spinner) view.findViewById(R.id.spinner_bulk);

    radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected

            switch (checkedId) {
                case R.id.radioButton1:
                    // switch to fragment 1
                    break;
                case R.id.radioButton2:
                    // Fragment 2
                    break;
            }
            selectedid = radioGroup.getCheckedRadioButtonId();
           radioButton = (RadioButton) view.findViewById(selectedid);
        }
    });
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
    ArrayAdapter<String> a = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, val);
    ArrayAdapter<String> adapt = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, value);
    ArrayAdapter<String> adap = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, v);
    ArrayAdapter<String> bulk = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, b);
    adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    adapt.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    a.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    adap.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    bulk.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    spinner.setAdapter(adapter);
    snum1.setAdapter(a);
    snum.setAdapter(adapt);
    sp1.setAdapter(adap);
    sp2.setAdapter(bulk);
    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

    // String txt=(String)spinner.getSelectedItem();

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            Object item = parentView.getItemAtPosition(position);
          /*  if(item!=null){
                Toast.makeText(getContext(),item.toString() + "Selected",Toast.LENGTH_SHORT).show();
            }*/
            //EventBus.getDefault().post(value);
            switch (parentView.getSelectedItemPosition()) {

                case (0): {
                    sp2.setVisibility(View.GONE);
                    //Do Nothing
                }
                break;
                case (1): {
                    contact1.setVisibility(View.VISIBLE);
                    contact2.setVisibility(View.VISIBLE);
                    dispatch.setVisibility(View.VISIBLE);
                    address.setVisibility(View.VISIBLE);
                    pincode.setVisibility(View.VISIBLE);
                    landmark.setVisibility(View.VISIBLE);
                    source.setVisibility(View.VISIBLE);
                    cname.setVisibility(View.VISIBLE);
                    cnumber.setVisibility(View.VISIBLE);
                    cnumber2.setVisibility(View.VISIBLE);
                    caddress.setVisibility(View.VISIBLE);
                    cpincode.setVisibility(View.VISIBLE);
                    ctype.setVisibility(View.VISIBLE);
                    clandmark.setVisibility(View.VISIBLE);
                    spinner.setVisibility(View.VISIBLE);
                    sp1.setVisibility(View.VISIBLE);
                    snum.setVisibility(View.VISIBLE);
                    snum1.setVisibility(View.VISIBLE);
                    sp2.setVisibility(View.GONE);
                    radioGroup.setVisibility(View.VISIBLE);
                    // radioButton_1.setVisibility(View.VISIBLE);
                    //radioButton_2.setVisibility(View.VISIBLE);
                }
                break;
                case (2): {
                    contact1.setVisibility(View.GONE);
                    contact2.setVisibility(View.GONE);
                    dispatch.setVisibility(View.GONE);
                    address.setVisibility(View.GONE);
                    pincode.setVisibility(View.GONE);
                    landmark.setVisibility(View.GONE);
                    source.setVisibility(View.GONE);
                    cname.setVisibility(View.GONE);
                    cnumber.setVisibility(View.GONE);
                    cnumber2.setVisibility(View.GONE);
                    caddress.setVisibility(View.GONE);
                    cpincode.setVisibility(View.GONE);
                    clandmark.setVisibility(View.GONE);
                    ctype.setVisibility(View.VISIBLE);
                    spinner.setVisibility(View.VISIBLE);
                    snum.setVisibility(View.GONE);
                    snum1.setVisibility(View.GONE);
                    sp1.setVisibility(View.GONE);
                    sp2.setVisibility(View.VISIBLE);
                    radioGroup.setVisibility(View.GONE);
                    //  radioButton_1.setVisibility(View.GONE);
                    // radioButton_2.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
    return view;
}
public String getEditetxtValue() {
    return cname.getText().toString();
}
@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP
                    && keyCode == KeyEvent.KEYCODE_BACK) {

                // handle back button
                Intent a = new Intent(getActivity(), MainActivity.class);
                startActivity(a);
                getActivity().finish();
               return true;
            }
           return false;
        }
    });
}

Order.class
public class Order_details extends DialogFragment implements
DatePickerDialog.OnDateSetListener {

private static final String[] FLAVOURS = new String[]{"Venilla", "Stawberry", "Chocalate", "Mango", "Pineapple"};
public static EditText edittext, edmessage;
public static Spinner spinner, sp, select;
public static AutoCompleteTextView textView;
DatePickerDialog.OnDateSetListener ondate = new DatePickerDialog.OnDateSetListener() {

    public void onDateSet(DatePicker view, int year, int monthOfYear,
                          int dayOfMonth) {

        edittext.setText(String.valueOf(dayOfMonth) + "-" + String.valueOf(monthOfYear + 1)
                + "-" + String.valueOf(year));
    }
};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
    View view = inflater.inflate (R.layout.activity_odetails, container, false);
    edmessage = (EditText)  view.findViewById(R.id.ed_cake);
    String[] egg = {"Select", "Egg", "Eggless", "N/A"};
    spinner = (Spinner) view.findViewById(R.id.spinner_e);

    String[] weight = {"Select", "0.5kg", "1kg", "1.5kg", "2kg", "2.5kg", "3kg", "6kg", "5kg", "4kg", "4.5kg", "3.5kg", "7kg", "8kg,", "7.5kg", "10kg"};
    sp = (Spinner) view.findViewById(R.id.spinner_wt);

    String[] time = {"Select", "8Am- 9Am", "11.30pm-11.45pm", "9am-10am", "10am-11am", "11AM=12PM", "12PM-1PM", "1PM-2PM", "2PM-3PM", "3PM-4PM", "4PM-5PM", "5PM-6PM", "6PM-7PM", "7PM-8PM", "8PM-9PM"};
    select = (Spinner) view.findViewById(R.id.spinner_t);

    textView = (AutoCompleteTextView) view.findViewById(R.id.au_flavour);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, egg);
    ArrayAdapter<String> p = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, weight);
    ArrayAdapter<String> d = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, time);
    adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    ArrayAdapter<String> au = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_dropdown_item_1line, FLAVOURS);
    p.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    d.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    spinner.setAdapter(adapter);
    sp.setAdapter(p);
    textView.setAdapter(au);
    select.setAdapter(d);

getActivity().getWindow().setSoftInputMode(WindowManager.
LayoutParams.SOFT_INPUT_ADJUST_PAN);
    return view;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    edittext = (EditText) view.findViewById(R.id.ed_date);
    edittext.setInputType(InputType.TYPE_NULL);
    edittext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            showDatePicker();
        }
    });
}
public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager =
            (InputMethodManager) activity.getSystemService(
                    Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(
            activity.getCurrentFocus().getWindowToken(), 0);
}
public void setupUI(View view) {
    if (!(view instanceof EditText)) {
        view.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                 hideSoftKeyboard(getActivity());
                return false;
            }
        });
    }
    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); ++i) {
            View innerview = ((ViewGroup) view).getChildAt(i);
            setupUI(innerview);
        }
    }
}
private void showDatePicker() {

    Bundle bundle=new Bundle();
    Calendar calender = Calendar.getInstance();
    Bundle args = new Bundle();
    args.putInt("year", calender.get(Calendar.YEAR));
    args.putInt("month", calender.get(Calendar.MONTH));
    args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
    date.setArguments(args);

    date.setCallBack(ondate);
    date.show(getFragmentManager(), "Date Picker");
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_UP
                    && keyCode == KeyEvent.KEYCODE_BACK) {

                startActivity(new Intent(getActivity(), MainActivity.class));
                getActivity().finish();
                return true;
            }

            return false;
        }
    });
}

Payment.class
public class Payment_details extends Fragment {
public static TextView payment, advance, balance, discount, extra, extra_amount, delivery;
public static EditText e_amount, e_advance, e_balance, e_discount, e_extra, e_extra_amount, e_delivery_charges, e_remark;
public static Spinner spinner;
Context context;
Button addextra, reset, save;
private LinearLayout laytype, layamount, laybalance, laydiscount, layexamt, laydelivery, layextra;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_payment_details, container, false);

    e_amount = (EditText) view.findViewById(R.id.edtAmount);
    e_advance = (EditText) view.findViewById(R.id.edtAdvance);
    e_balance = (EditText) view.findViewById(R.id.edtBalance);
    e_discount = (EditText) view.findViewById(R.id.e_discount);
    e_extra = (EditText) view.findViewById(R.id.e_extra);
    e_remark = (EditText) view.findViewById(R.id.e_remarks);
    e_extra_amount = (EditText) view.findViewById(R.id.eextra_amount);
    e_delivery_charges = (EditText) view.findViewById(R.id.e_delivery);
    addextra = (Button) view.findViewById(R.id.add_extra);
    reset = (Button) view.findViewById(R.id.btn_reset);
    save = (Button) view.findViewById(R.id.save2);
    String[] ptype = {"Select", "Cash", "EDC", "Online", "NEFT", "Cheque", "Not Paid"};
    spinner = (Spinner) view.findViewById(R.id.spinner_pt);

    laydiscount.setVisibility(View.GONE);
    layextra.setVisibility(View.GONE);
    layexamt.setVisibility(View.GONE);
    laydelivery.setVisibility(View.GONE);

    if (Customer_details.spinner.getSelectedItem().toString().equalsIgnoreCase("Bulk")) {
        payment.setVisibility(View.GONE);
        advance.setVisibility(View.GONE);
        balance.setVisibility(View.GONE);
        e_advance.setVisibility(View.GONE);
        e_balance.setVisibility(View.GONE);
        spinner.setVisibility(View.GONE);
    }

    textWatcher(e_advance);
    textWatcher(e_discount);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, ptype);
    adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    spinner.setAdapter(adapter);
    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

    addextra.setOnClickListener(new View.OnClickListener() {
        int click = 0;

        //int i=0;
        @Override
        public void onClick(View v) {

            //  int count =++_clicks;
            if (click == 0) {
                click = 1;

                laydiscount.setVisibility(View.VISIBLE);
                layextra.setVisibility(View.VISIBLE);
                layexamt.setVisibility(View.VISIBLE);
                laydelivery.setVisibility(View.VISIBLE);

            } else {
                click = 0;
                laydiscount.setVisibility(View.GONE);
                layextra.setVisibility(View.GONE);
                layexamt.setVisibility(View.GONE);
                laydelivery.setVisibility(View.GONE);

            }
        }

    });

    reset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                clear();
                Toast.makeText(getActivity(), "Working", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            }

private void textWatcher(final EditText edit) {
    edit.addTextChangedListener(new TextWatcher() {
        int result,r=0;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            result = 0;
            //r=0;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            int e = parse(e_amount) - parse(e_advance);
            if (edit == e_discount && parse(e_discount) == 0) {
                result = e;
            }
            else{
                result = e - parse(e_discount);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {
            e_balance.setText(String.valueOf(result));

        }
    });

}

private int parse(EditText edt) {
    String s = edt.getText().toString();
    if (s.matches(""))s = "0";
    return Integer.parseInt(s);
}

public void clear() {

    Customer_details.spinner.setSelection(0);
    Log.v(Customer_details.cname.getText().toString(), "name");
    try {
        Customer_details.cname.setText("");
        Customer_details.snum.setSelection(0);
        Customer_details.cnumber.setText("");
        Customer_details.snum1.setSelection(0);
        Customer_details.sp2.setSelection(0);
        Customer_details.cnumber2.getText().clear();
        Customer_details.caddress.getText().clear();
        Customer_details.cpincode.getText().clear();
        Customer_details.clandmark.getText().clear();
        // Customer_details.radioButton.setChecked(false);
        Customer_details.sp1.setSelection(0);
        Customer_details.spinner.setSelection(0);
        Customer_details.cnumber.setText("");
        Order_details.spinner.setSelection(0);
        Order_details.textView.setText("");
        Order_details.sp.setSelection(0);
        Order_details.edmessage.setText("");
        Order_details.edittext.getText().clear();
        Order_details.select.setSelection(0);
        e_amount.setText("");
        spinner.setSelection(0);
        e_advance.setText("");
        e_balance.setText("");
        e_remark.setText("");
        e_discount.setText("");
        e_extra.setText("");
        e_extra_amount.setText("");
        e_delivery_charges.setText("");
        spinner.setSelection(0);
        e_amount.setText("");
        e_advance.setText("");
        e_balance.setText("");
        e_remark.setText("");
    } catch (Exception e) {
        Log.i("MYLOG", "Message was not handled " + e.getMessage());

    }
    Toast.makeText(getActivity(), "Cleared ", Toast.LENGTH_SHORT).show();
}
}

I have tried to clear the items by this method,

*

*edittext.setText(" ");

*edittext.getText().clear();
Only Order and Payment class data alone get cleared Customer data couldn't cleared. How to fix my problem?

A: try to set this mViewPager.setOffscreenPageLimit(3); inside setUpViewPager() method
Upate
By default setOffscreenPageLimit() will be set to 1, that means youll have 2 fragment pages active at once. Since you need to clear the texts from EditText of all the three fragment pages, then setting setOffscreenPageLimit(3) (because you are using 3 fragments) will have all 3 fragment page active and helpful in making necessary changes in all of them. For more information see the Docs

void setOffscreenPageLimit (int limit)
  Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.


text:
Q: Bitmap is null when tried to fetch image from frame affective I have integrated affectiva library and trying to fetch emotions using camera stream.
I tried to fetch the bitmap from the frame returned but it always returns null.Below is the code.
  byte[] imageBytes = ((Frame.ByteArrayFrame) frame).getByteArray();

We have some 518 kb of data but when converted to image it returns null.
 Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
    previewImage.setImageBitmap(bitmap);

I even tried the below code but again null bitmap
Bitmap bmp=frame.getOriginalBitmapFrame();

Could you please help me to fetch bitmap from the frame?

A: There are some sample conversion methods in Affectiva's affdexme-android sample app:
https://github.com/Affectiva/affdexme-android/blob/a0c732fb0378b9c0883d30fa21eaa9cf22b57eed/app/src/main/java/com/affectiva/affdexme/ImageHelper.java#L221
public static Bitmap getBitmapFromFrame(@NonNull final Frame frame) {
    Bitmap bitmap;

    if (frame instanceof Frame.BitmapFrame) {
        bitmap = ((Frame.BitmapFrame) frame).getBitmap();
    } else { //frame is ByteArrayFrame
        switch (frame.getColorFormat()) {
            case RGBA:
                bitmap = getBitmapFromRGBFrame(frame);
                break;
            case YUV_NV21:
                bitmap = getBitmapFromYuvFrame(frame);
                break;
            case UNKNOWN_TYPE:
            default:
                Log.e(LOG_TAG, "Unable to get bitmap from unknown frame type");
                return null;
        }
    }

    if (bitmap == null || frame.getTargetRotation().toDouble() == 0.0) {
        return bitmap;
    } else {
        return rotateBitmap(bitmap, (float) frame.getTargetRotation().toDouble());
    }
}

public static Bitmap getBitmapFromRGBFrame(@NonNull final Frame frame) {
    byte[] pixels = ((Frame.ByteArrayFrame) frame).getByteArray();
    Bitmap bitmap = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(pixels));
    return bitmap;
}

public static Bitmap getBitmapFromYuvFrame(@NonNull final Frame frame) {
    byte[] pixels = ((Frame.ByteArrayFrame) frame).getByteArray();
    YuvImage yuvImage = new YuvImage(pixels, ImageFormat.NV21, frame.getWidth(), frame.getHeight(), null);
    return convertYuvImageToBitmap(yuvImage);
}

/**
 * Note: This conversion procedure is sloppy and may result in JPEG compression artifacts
 *
 * @param yuvImage - The YuvImage to convert
 * @return - The converted Bitmap
 */
public static Bitmap convertYuvImageToBitmap(@NonNull final YuvImage yuvImage) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    yuvImage.compressToJpeg(new Rect(0, 0, yuvImage.getWidth(), yuvImage.getHeight()), 100, out);
    byte[] imageBytes = out.toByteArray();
    try {
        out.close();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Exception while closing output stream", e);
    }
    return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
}

public static Bitmap rotateBitmap(@NonNull final Bitmap source, final float angle) {
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}


text:
Q: Do we need to create subfolders in Documents before calling a writeToFile with a path that contains new folder? I am trying to write to the following path:
        NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *storePath = [docDir stringByAppendingPathComponent:@"/newfolder/test.jpg"];

        NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
        BOOL saved = [data writeToFile:storePath atomically:NO];
        NSLog(@"%c", saved);

Now, nothing gets printed and I can't see the file in my simulator. Is it because "newfolder" folder within the Documents main folder is not created yet. If so, is there a way to create it if it is not there yet?
Thanks!

A: Yes, you must make sure the folder is created first. Use NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error: passing in the path to the folder you wish to create (not the file you are trying to write).
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *storePath = [docDir stringByAppendingPathComponent:@"newfolder/test.jpg"];

[[NSFileManager defaultManager] createDirectoryAtPath:[storePath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];

NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];

You should check the return value of these methods and handle any failures.


text:
Q: Parental gate in Admob Banner iOS Is there any way to handle click on admob banner view? I have game for kids, so I've added parental gate in in-app purchases as well as in chartboost using their age gate. I'm looking for the same solution for admob banner (interstitial could be as well).
I've tried adding delegate and indeed:
- (void)adViewWillPresentScreen:(nonnull GADBannerView *)bannerView {
    NSLog(@"adViewWillPresentScreen");
}

is called, but I can't find a way to intercept this flow and show parental gate, before it'll open an url or cancel it when user failed to solve parental gate.
I've also tried handling it in AppDelegate:
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {

    NSLog(@"%@", url.absoluteString);

    return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                          openURL:url
                                                sourceApplication:sourceApplication
                                                       annotation:annotation];
}

But when I'm clicking the banner it's not called.
In chartboost there's Age Gate:
- (void)didPauseClickForConfirmation {

    [AppDelegate showParentalGate:^(BOOL passed) {
        [Chartboost didPassAgeGate:passed];
    }];

}

Is there anything like this for admob? How can I do this?


text:
Q: Is there a way to directly generate Step Definitions in Eclipse without Running Cucumber? Im doing integration testing with cucumber and Gradle in Eclipse.
For now my workflow is

*

*Write a feature file

*Run it to generate step skeletons

*Copy and implement them

This works good for new features and so on, but becomes quite bothersome if you have a large feature and implement new steps in the middle or towards the end.
To get the new step skeletons I need to run the whole feature.
Even with the
dryRun = true

option this takes up a long time.
I have heard that IntellyJ can generate these step skeletons directly
and I would like to know if something like this is possible in Eclipse?

A: Not for Eclipse, but it might prove helpful to you as a stop gap: https://chrome.google.com/webstore/detail/tidy-gherkin/nobemmencanophcnicjhfhnjiimegjeo
It's capable of generating Java step defs from the text you paste into the editor. Hope it helps in some way while you await an answer for Eclipse.

A: Yes there is a nice plugin for Eclipse that also has even more benefits: Cucumber People
The only Problem I got is, that it checks the steps after every save in the Cucumber console.
I also used the Natural plugin before.

A: Why is this a problem in Eclipse? If the feature file is big, then you only copy the modified scenario to a new feature file, and generate steps based on the new feature file.


text:
Q: SQL Server partition by or any other techniques In SQL Server 2012:
ID      RANK
5400      1
5400      1
5400      1
2587      2
2587      2
1200      3
1200      3
1200      3
1200      3

I need to generate last column like this, as these data will be are order by date and now I want to distinct ID as in the order they are.
Without this RANK column I can not do it, I think so because when I distinct on ID column its internally order it by ID ascending
Note: my ID column is primary key
Expected result set :
5400
2587
1200

Current result set :
1200
2587
5400

A: If you only want to select a distinct list of ID then I would suggest :
SELECT DISTINCT ID FROM TABLENAME

Otherwise, if you wish to add another column and set it to identity you can use the following code.
Please note that I have created #Temp1 in order to mimic your data and have create #Temp2 to import a DISTINCT list of ID's and RANK, then updated #Temp1 using the identity set on #Temp2 :
CREATE TABLE #Temp1 (ID INT)
INSERT INTO #Temp1 (ID)
VALUES ('5400'),
        ('5400'),
        ('5400'),
        ('2587'),
        ('2587'),
        ('1200'),
        ('1200'),
        ('1200'),
        ('1200')
ALTER TABLE #Temp1 ADD RANK INT

CREATE TABLE #Temp2 (ID INT, RANK int IDENTITY(1, 1))
INSERT INTO #Temp2 (ID)
    SELECT DISTINCT ID
    FROM #Temp1
    ORDER BY ID DESC

UPDATE #Temp1
SET #Temp1.RANK = #Temp2.RANK
FROM #Temp1
INNER JOIN #Temp2
       ON #Temp1.ID = #Temp2.ID

SELECT DISTINCT RANK, ID
FROM #Temp1

DROP TABLE #Temp1
DROP TABLE #Temp2

Hope this helps.

A: In my opinion, it is very unclear what you are asking.
Your expected result set is without a rank column.
Why do you want to have a row_number/dense_rank in the first place ?
You only group it by id, and sort it descending by id...
That needs no rank, and not a distinct either, that goes like this:
SELECT ID FROM TABLE_NAME
GROUP BY ID
ORDER BY ID DESC

Furthermore, you claim your ID column is primary key, but it has duplicates, which means it is not a primary key because primary-keys are by definition unique-keys.
My conclusion is that you input set is the table with the id as primary-key joined with some other table(s) in either a stored procedure or a table-valued-function, and that you don't know that "group by" exists, and that you don't know that you can specify the sort direction by specifying the ASC/DESC keyword.
By the way, if you need any more values than ID, you either need to put them into the group by, or you need to use an aggregate function, e.g.
SELECT ID, Product_Name, MAX(Price) FROM TABLE_NAME
GROUP BY ID, Product_Name
ORDER BY ID DESC

And be careful if you use dense_rank in some way, because this will have the effect of counting a NULL value as a distinct value. Example:
;WITH CTE AS
(
              SELECT 1 AS Id
    UNION ALL SELECT 2 AS Id
    UNION ALL SELECT 3 AS Id
    UNION ALL SELECT 3 AS Id
    UNION ALL SELECT 3 AS Id
    UNION ALL SELECT 3 AS Id
    UNION ALL SELECT 4 AS Id
    UNION ALL SELECT 5 AS Id
    UNION ALL SELECT NULL AS Id
)

SELECT
     Id
    ,DENSE_RANK() OVER (ORDER BY Id) AS rank
FROM CTE

ORDER BY rank DESC

A: Please check below answer.
declare @Temp table (id1 bigint identity(1, 1), Type int)

insert into @Temp
select 5400  union all
select 5400  union all
select 4500  union all
select 4500  union all
select 1800  union all
select 3200  union all
select 1800  union all
select 200  union all
select 3200

Now below is your query for get the rank.
select
DENSE_RANK()OVER(ORDER BY Type DESC) AS 'RANKNumber', Type from @Temp
group by Type


text:
Q: How to find a repository by port? I have a nexus3 RM OSS that hosts ~100 repositories, I would like to find which one listens on a specific port. from the web interface I have to go one by one the repos and find it.
The repositories' REST API (http://IP:PORT/service/rest/v1/repositories) doesn't display the port information, sample repo dumped:
{
  "name" : "my_repo_name",
  "format" : "docker",
  "type" : "hosted",
  "url" : "https://IP:PORT/repository/my_repo_name",
  "attributes" : { }
}

I can see in nexus.log information about the repos started and their respective ports, but this requires to restart nexus.


text:
Q: Failing to produce to Kafka topic because of 'Failed to connect to seed broker' error with KafkaJS I have the following file, producer.js, taken from https://kafka.js.org/docs/getting-started.
const { Kafka } = require('kafkajs')

const kafka = new Kafka({
  clientId: 'my-app',
  brokers: ['broker:9092'],
})

const producer = kafka.producer()

const main = async () => {
    await producer.connect()
    await producer.send({
      topic: 'quickstart',
      messages: [
        { value: 'Hello KafkaJS user!' },
      ],
    })

    await producer.disconnect()
}

main();

I have a single Kafka broker running with Docker as defined in the docker-compose.yml.
---
version: '3'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:7.0.1
    platform: linux/x86_64
    container_name: zookeeper
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  broker:
    image: confluentinc/cp-kafka:7.0.1
    platform: linux/x86_64
    container_name: broker
    ports:
    # To learn about configuring Kafka for access across networks see
    # https://www.confluent.io/blog/kafka-client-cannot-connect-to-broker-on-aws-on-docker-etc/
      - "9092:9092"
    depends_on:
      - zookeeper
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_INTERNAL:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092,PLAINTEXT_INTERNAL://broker:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1

  # kafka_ui:
  #   image: provectuslabs/kafka-ui:latest
  #   # platform: linux/x86_64
  #   container_name: kafka_ui
  #   depends_on:
  #     - broker
  #   ports:
  #     - 8080:8080
  #   environment:
  #     KAFKA_CLUSTERS_0_ZOOKEEPER: zookeeper:2181
  #     KAFKA_CLUSTERS_0_NAME: local
  #     KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: broker:9092

Once I start the containers, I can even write messages to a topic that I created called quickstart. But when I try to produce through the script using node producer.js, I get the following error:
{"level":"ERROR","timestamp":"2022-07-13T09:58:42.720Z","logger":"kafkajs","message":"[BrokerPool] Failed to connect to seed broker, trying another broker from the list: Connection error: getaddrinfo ENOTFOUND broker","retryCount":3,"retryTime":2142}

And of course, after a few retries, it times out. I'm not sure what I'm doing wrong as I followed the instructions from the KafkaJS documentation.
Any help would be highly appreciated!
P.S. I saw this solution and tried it but unfortunately, to no avail: Failed to connect to seed broker with kafkajs

A: If your code is not running in a container, you should change broker:9092 to localhost:9092 as your advertised listener is setting localhost as the address that is to be used externally for that port.


text:
Q: AsyncImage in List is broken on iOS 16 struct Item: Identifiable {
    let id: String
    let url = URL(string: "https://styles.redditmedia.com/t5_j6lc8/styles/communityIcon_9uopq0bazux01.jpg")!
}

struct Content: View {

    let model: [Item] = {
        var model = [Item]()
        for i in 0 ..< 100 {
            model.append(.init(id: String(i)))
        }
        return model
    }()

    var body: some View {
        List(model) { item in
            Row(item: item)
        }
    }

}

struct Row: View {

    let item: Item

    var body: some View {
        AsyncImage(url: item.url)
    }

}

Running code above with Xcode 14.1 on iOS 16.1 simulator, AsyncImage sometimes doesn't properly show downloaded image but grey rectangle instead when scrolling in list. Is this bug or am I missing something? Thanks

A: .fixedSize() fixed the problem me

A: My solution was to use VStack in ScrollView instead of List. It looks like it's working and it doesn't have any other drawbacks.


text:
Q: Can Angular Directives depend on xml transformations by xslt? I'm trying to create an Angular Directive menu with as little javascript as possible (I'm using angular so that config files can be specified on an app by app basis in custom directive). To create the menu, I have an xml file being translated by xslt into an html page. When I view the xml in a browser, it comes out styled as I want it. CSS alone is sufficient to provide the functionality I want.  When I cite this html page as a templateURL for an angular directive, it does not load saying :Template for directive 'siteMapMenu' must have exactly one root element.
Of course the message is correct, but removing the nodes isn't an option in xslt processing, correct?
sample xml:
<?xml version="1.0" encoding="utf-8" ?>
<?xml-stylesheet  type="text/xsl" href="Views/Shared/SiteMapScout.xslt"?>
<mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0"
            xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0 MvcSiteMapSchema.xsd">...(rest of sitemap spec)

sample XSLT:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"  exclude-result-prefixes="msxsl" xmlns:t="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0"
>

  <xsl:output  omit-xml-declaration="yes" method="html" indent="yes"/>

      <xsl:template match="/">

            <link rel="stylesheet" type="text/css" href="Content/CSS/jqueryslidemenu.css" />

    <xsl:for-each select="/t:mvcSiteMap/t:mvcSiteMapNode/t:mvcSiteMapNode">

              <xsl:value-of select="./@title"></xsl:value-of>

              <xsl:if test="count(./t:mvcSiteMapNode) > 0">

                  <xsl:for-each select="./t:mvcSiteMapNode">

                          <xsl:value-of select="./@title"></xsl:value-of>

                  </xsl:for-each>

              </xsl:if>

        </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

Sample Directive:
; (function () {
    'use strict';
    angular.module('scout').directive("siteMapMenu", siteMapMenu);

    function siteMapMenu() {

        return {
            replace: true,
            restrict: 'E',
            templateUrl: "ScoutSitemap.xml",
            //templateUrl: "TestMap1.html",
            controller: [
                '$scope', '$filter', siteMapController
            ]
        };

    }

    function siteMapController($scope, $filter) {
        $scope.ShowMaintenance = false;
        $scope.ShowReports = false;
        $scope.ShowFileDownload = false;
        $scope.ShowHelp = false;

    }

})();

A: I added the following methods and accessed them appropriately from the directive's controller to achieve what I was shooting for.
function loadXMLDoc(filename) {

    var xhttp = {};
    if (window.ActiveXObject) {
        xhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        xhttp = new XMLHttpRequest();
    }

    xhttp.open("GET", filename, false);
    try { xhttp.responseType = "xml" } catch (err) { } // Helping IE11
    xhttp.send("");

    return xhttp.responseXML;
}

function displayResult($scope) {
    var xml = {};
    var xsl = {};
    var xhttp = {};
    var xsltProcessor = {};
    var resultDocument = {};
    xml = loadXMLDoc("ScoutSitemap.xml");

    xsl = loadXMLDoc("Views/Shared/SiteMapScout.xslt");
    if (window.ActiveXObject || xhttp.responseType == "msxml-document")
    {
        ex = xml.transformNode(xsl);
        document.getElementById("myfill").innerHTML = ex;
    }
        // code for Chrome, Firefox, Opera, etc.
    else if (document.implementation && document.implementation.createDocument) {

         xsltProcessor = new XSLTProcessor();
         xsltProcessor.importStylesheet(xsl);

        resultDocument = xsltProcessor.transformToFragment(xml, document);
        $scope.resp = resultDocument.textContent;

        document.getElementById("myfill").appendChild(resultDocument);
    }
}


text:
Q: Android canvas reusing bitmap I have a lot of geometries that need to be draw on a canvas (Overlay in osmdroid but i don't think is important.
Because i have so many objects it is not possible to create on bitmap for each object(geometry).
draw method looks like this:
protected void draw(Canvas c, MapView osmv, boolean shadow) {
        Bitmap airSpaceBitmap=Bitmap.createBitmap(c.getWidth(), c.getHeight() , Config.ARGB_8888);
        Path path = new Path();
        for (Airspace airspace : restrictedAirspaces) {
            airSpaceBitmap.eraseColor(Color.TRANSPARENT);//clean current bitmap
            Canvas airSpaceCanvas=new Canvas(airSpaceBitmap);
            path.reset();
            //build the path
            airSpaceCanvas.drawPath(path, AIRSPACE_RESTRICTED);
            //draw other stuff in the bitmap
            //clip only the needed part from the draw
            airSpaceCanvas.clipPath(clipPath, Region.Op.REPLACE);
            c.drawBitmap(airSpaceBitmap, 0, 0, null);
        }

    }

The problem is that only last draw (last bitmap) is draw not all.
Any idea on why and how to fix this?


text:
Q: Include sender address in disclaimer (incoming mail) I have a mail flow rule setup to flag email from outside our domain.  It prepends a disclaimer into the email.  Today I saw an email from another domain that included the senders email address and friendly name in their disclaimer (see below).

Below is the disclaimer text i use in my rule.  What code would i need to insert (ADDRESS HERE) for Exchange to insert the senders email and friend name?

 2.0pt'>
 style='font-size:10.0pt;color:#9C6500′> style='font-size:10.0pt;color:black'> #FFFF00"> [EXTERNAL SENDER (ADDRESS HERE) - Use Caution Opening Links or Files]

<o:p></o:p>
}

A: After several days with MS tech support, it turns out that this is not possible with Exchange Server.
Turns out this can be done in Cisco ESA.


text:
Q: XSLT 1.0: copy everything except certain nodes according to value and variable I have the following (simplified) XML that I get in a system environment:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<IS_LOG>
    <USER>19291</USER>
    <DATE>2011-08-15</DATE>
    <TIME>15:36:36</TIME>
    <SYST>sy1</SYST>
    <MATERIALS>
        <item>
            <sy>100</sy>
            <mat>000000000000310000</mat>
        </item>
        <item>
            <sy>100</sy>
            <mat>000000000000491078</mat>
        </item>
    </MATERIALS>
</IS_LOG>
</root>

The system that I work with passes me a variable at runtime that is not included in the XML structure above.
I have the following XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl" version="1.0">

<!-- System variable whose value I normally only get only at runtime;
for test purposes set locally -->
<xsl:variable name="SenderService" select="'AT'"/>

<xsl:template match="@*|node()">
    <xsl:choose>
        <xsl:when test="$SenderService='AT'">
            <xsl:copy>
                <xsl:apply-templates mode="AT" select="@*|node()"/>
            </xsl:copy>
        </xsl:when>
        <xsl:otherwise>
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
        </xsl:otherwise>
   </xsl:choose>
</xsl:template>

<xsl:template mode="AT" match="item[mat > 000000000000299999 and mat < 000000000000399999]"/>

</xsl:stylesheet>

Now I need to copy all elements item excluding the ones where mat is in the number range of 300000 to 399999 and SenderService is 'AT'.
If to test it locally I change the SenderService in my XSLT to e.g. 'Z', the output looks fine, all items get copied:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<IS_LOG>
    <USER>19291</USER>
    <DATE>2011-08-15</DATE>
    <TIME>15:36:36</TIME>
    <SYST>sy1</SYST>
    <MATERIALS>
        <item>
            <sy>100</sy>
            <mat>000000000000310000</mat>
        </item>
        <item>
            <sy>100</sy>
            <mat>000000000000491078</mat>
        </item>
    </MATERIALS>
</IS_LOG>
</root>

But if I set SenderService to 'AT' the output looks like this:
    <?xml version="1.0" encoding="UTF-8"?><root>

    19291
    2011-08-15
    15:36:36
    sy1

            100
            000000000000491078

</root>

The correct item gets copied but without the tags. How can I change the XSLT?

A: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:variable name="SenderService" select="'AT'"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="item[mat > 000000000000299999 and mat < 000000000000399999]">
        <xsl:if test="$SenderService != 'AT'">
            <xsl:copy-of select="."/>
        </xsl:if>
    </xsl:template>

</xsl:stylesheet>


text:
Q: Why Application insight is not working after doing slot swapping in azure app service? I am using application insight for measuring performance and also storing some telemetry data of my web application and it was working fine till last month.
But from last month I am unable to see any traffic in app insight. In last month just I have added one slot in my app service. I have checked instrumentation key, it's same and correct and there is no change in application settings and configuration in app service.
Could you please suggest me if any additional settings I need to take care ?
I suspect this issue is due to adding of slot because in other environment it's working fine.

A: You could go to Visual Studio configure Application Insights through there and then redeploy the application to slot.
For more information, you could refer to this doc: Application Insights support for Multiple Environments, Stamps and App Versions, , specifically the 'Multi Stamp Support'.

A: How are you enabling application insights for the App in Azure Web App? Are you using extensions or do you take nuget dependency at build time?
If using extension, please navigate to this url to find the status of application insights enablement: https://yoursitename.scm.azurewebsites.net/ApplicationInsights
Have you ensured that that instrumentation key is available in all slots? This is most likely an instrumentation key issue.


text:
Q: How to get the region shown in the image ? i want to get the red region as specified in the image below :

remember that the red region that is shown in the image is just for clarification , it is not present in original image , below is the original image attached :

i also have the iris point in this region, i already got that point , if that point can help me so i can share that image too.
can someone help me in this .....

A: For this specific image, let's call it BW, you can find the center region as:
BWnoBorder= imclearborder(BW); %# remove the white that touches the border
OnlyCenter = bwareaopen(BWnoBorder,1000); %# remove all small pixel areas

A: A robust method might be the snake region growing algorithm.

A: Seems like you thresholded the eye illuminated by IR or something. To answer your question or even to ask it correctly you have to show a number of images to evaluate the stability and noise in eye socket regions. Otherwise one can come up with a solution that works for the image above but not in general.
For example, I can invert your image, get the largest Connected Component (the dark region) and erode it till it becomes thin, see below. It is easy to get an ellipse from this binary mask but will it work in general case with your noisy input?

A good thing to start is to say what do you expect to find. Say you are looking for an eye, dark surrounding area and a bright skin tone - make it 3 Mixed models that settle simultaneously in the EM fashion. Provide some shape priors to increase accuracy. think about other visual cues such as specs on the iris, saccades, FA from blinks, etc.


text:
Q: Recycle and GetNextDocument / GetNextCategory in NotesViewNavigator? How do I do a recycle for GetNextDocument or GetNextCategory in a NotesViewNavigator?   Neither takes an argument so you can't use the conventional method of using a temp variable to pre get the next document like you might in a view.
I suppose the solution would be to just use getNext with an argmenumnt but can GetNextDocument / GetNextCategory  still be used?
The error I am getting is on line 20.  Without the recycle the code runs fine.  From what I understand recycle destroys the object so I can understand the reason for the error.  My questition is if there is another way around this?
[TypeError] Exception occurred calling method NotesViewNavigator.getNextDocument() null
occurs on line 20
 1: var viewName = "vwParticipantsProjectIDEquipmentIDUsername";
 2:
 3:
 4: var v:NotesView = database.getView(viewName);
 5: var nav:NotesViewNavigator = v.createViewNavFromCategory(sessionScope.get("ExportProjectID"));
 6:
 7:
 8: var viewEnt:NotesViewEntry = nav.getFirstDocument();
 9:
 10: while (viewEnt != null)
 11: {
 12:
 13:    if (viewEnt.isDocument())
 14:    {
 15:
 16:        var doc:NotesDocument = viewEnt.getDocument();
 17:    }
 18:
 19:    viewEnt.recycle();
 20:    viewEnt = nav.getNextDocument();
 21: }

A: This is the pattern that I tend to use:
var documentEntry = nav.getFirstDocument();
while( documentEntry != null ){
  var nextDocumentEntry = nav.getNextDocument();
  // do stuff
  documentEntry.recycle();
  documentEntry = nextDocumentEntry;
}

A: Why don't you try to apply the old pattern like this:
var viewName = "vwParticipantsProjectIDEquipmentIDUsername",
    v:NotesView = database.getView(viewName),
    nav:NotesViewNavigator = v.createViewNavFromCategory(sessionScope.get("ExportProjectID")),
    viewEnt:NotesViewEntry = nav.getFirstDocument(),
    tmp:NotesViewEntry;
while (viewEnt !== null)
{
    if (viewEnt.isDocument())
    {
        var doc:NotesDocument = viewEnt.getDocument();
    }
    tmp = viewEnt;
    viewEnt = nav.getNextDocument();
    tmp.recycle();
}

I did not test it, but I guess that works...


text:
Q: Issue using services in angular v 1.2.19 I am getting this error:
TypeError: Cannot read property 'prototype' of undefined
at Object.instantiate (http://localhost:3000/angular/angular.min.js:35:144)
at Object.<anonymous> (http://localhost:3000/angular/angular.min.js:35:435)
at Object.d [as invoke] (http://localhost:3000/angular/angular.min.js:35:36)
at http://localhost:3000/angular/angular.min.js:36:288
at c (http://localhost:3000/angular/angular.min.js:34:305)
at d (http://localhost:3000/angular/angular.min.js:35:6)
at Object.instantiate (http://localhost:3000/angular/angular.min.js:35:165)
at $get (http://localhost:3000/angular/angular.min.js:67:421)
at link (http://localhost:3000/lib/angular-route.min.js:7:248)
at K (http://localhost:3000/angular/angular.min.js:54:390)

I have checked my getter/setter syntax many times because I have seen others with this same issue. To my knowledge, mine is correct. Here is my code:
Main module app.js:
angular.module('loc8rApp', ['ngRoute']);

function config ($routeProvider){
  $routeProvider
.when('/', {
  templateUrl: 'home/home.view.html',
  controller: 'homeCtrl',
  controllerAs: 'vm'
})
.otherwise({redirectTo: '/'});
};

angular
  .module('loc8rApp')
  .config(['$routeProvider', config]);

Service loc8rData.js:
angular
  .module('loc8rApp')
  .service('loc8rData', loc8rData);

var loc8rData = function ($http) {
  var locationByCoords = function (lat, lng) {
    return $http.get('/api/locations?lng=' + lng + '&lat=' + lat + '&maxDistance=20');
  };
  return {
locationByCoords : locationByCoords
  };
}

Second service: geolocation.services.js:
angular
  .module('loc8rApp')
  .service('geolocation', geolocation);

var geolocation = function () {
  var getPosition = function (cbSuccess, cbError, cbNoGeo) {
    if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(cbSuccess, cbError);
}
else {
  cbNoGeo();
}
 };
      return {
    getPosition : getPosition
  };
}

Controller homeCtrl.js:
angular
  .module('loc8rApp')
  .controller('homeCtrl', homeCtrl);
function homeCtrl ($scope, loc8rData, geolocation) {
  var vm = this;
  vm.pageHeader = {
    title: 'Loc8r',
    strapline: 'Find places to work with wifi near you!'
  };
  vm.sidebar = {
    content: "Looking for wifi and a seat? Etc etc"
  };
  vm.message = "Checking your location";
  vm.getData = function (position) {
var lat = position.coords.latitude,
    lng = position.coords.longitude;
vm.message = "Searching for nearby places";
loc8rData.locationByCoords(lat, lng)
  .success(function(data) {
    vm.message = data.length > 0 ? "" : "No locations found nearby";
    vm.data = { locations: data };
    })
  .error(function (e) {
    vm.message = "Sorry, something's gone wrong";
    });
  };
  vm.showError = function (error) {
    $scope.$apply(function() {
      vm.message = error.message;
    });
  };
  vm.noGeo = function () {
$scope.$apply(function() {
  vm.message = "Geolocation is not supported by this browser.";
});
  };
  geolocation.getPosition(vm.getData,vm.showError,vm.noGeo);
}

In Layout.jade I have:
 html(ng-app='loc8rApp')

and in the body:
    .containter
      div(ng-view)
        block content

and then I have my scripts aligned with body
body

....
script(src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')
script(src='/angular/angular.min.js')
script(src='/lib/angular-route.min.js')
script(src='/bootstrap/js/bootstrap.min.js')
script(src='/javascript/validation.js')
script(src='/app.js')
script(src='/common/services/loc8rData.js')
script(src='/common/services/geolocation.service.js')
script(src='/home/homeCtrl.js')

The HTML:

{{ vm.pageHeader.title }}
      {{ vm.pageHeader.strapline }}

    Filter results
    <input id="filter" type="text", name="filter", ng-model="textFilter">

{{ vm.message }}

        {{ location.name }}

        {{ location.distance }}

{{ location.address }}

        {{ facility }}

{{ vm.sidebar.content }}

I have searched this high and low and so has my buddy. Know this is a long post, but if you're up for it, that would be pretty cool. thanks

A: You are declaring two of your functions as variables, but you are using them before they are defined. For example:
angular.module('loc8rApp').service('geolocation', geolocation);
var geolocation = function () {
    //....
}

In this case, when the first line tries to use the function geolocation, it is still undefined. If you use the other notation for declaring functions it will work:
angular.module('loc8rApp').service('geolocation', geolocation);
function geolocation() {
    //....
}

This is because the functions declared in this way are processed before the rest of the code.
Th same thing applies to your loc8rData function.

A: The previous answer is totally correct. This is because of hoisting in Javascript. Variable declarations and and function declarations are moved to the top of their respective scopes, but variable assignments are not. Therefore, if it was function declaration, not function expression as it is in the example, it would work.
var x; // variable declaration
x = 3; // variable assignment
var geolocation = function () { // function expression
//....
}
function geolocation() { // function declaration
//....
}

So for example in var x = 3; Javascript engine sees it as two separate statements. var x; in compiling time and x = 3; at execution time. Therefore, the function expression declaration was hoisted, however the assignment of the function expression was not.