text:
Q: how to extract the value of specefic div in html with crawling in apache nutch? I do crawling with nutch 2.2 and the data that i retrieve is the metatag,how to extract the value of specefic div in html with crawling in apache nutch

A: You will have to write a plugin that will extend HtmlParseFilter to achieve your goal.
You can use some html parser like Jsoup for this and extract URLs that you want and add them as outlinks.
Sample HtmlParseFilter implementation:-
        public ParseResult filter(Content content, ParseResult parseResult,
              HTMLMetaTags metaTags, DocumentFragment doc) {
                // get html content
                String htmlContent = new String(content.getContent(), StandardCharsets.UTF_8);
                // parse html using jsoup or any other library.
                Document document = Jsoup.parse(content.toString(),content.getUrl());
                Elements elements = document.select(<your_css_selector_query);
                // modify/select only required outlinks
                if (elements != null) {
                    Outlink outlink;
                    List<String> newLinks=new ArrayList<String>();
                    List<Outlink> outLinks=new ArrayList<Outlink>();
                    String absoluteUrl;
                    Outlink outLink;
                    for (Element element : elements){
                     absoluteUrl=element.absUrl("href");
                     if(includeLinks(absoluteUrl,value)) {
                        if(!newLinks.contains(absoluteUrl)){
                          newLinks.add(absoluteUrl);
                          outLink=new Outlink(absoluteUrl,element.text());
                          outLinks.add(outLink);
                          }
                        }
                      }
                    Parse parse = parseResult.get(content.getUrl());
                    ParseStatus status = parse.getData().getStatus();
                    Title title = document.title();
                    Outlink[] newOutLinks = (Outlink[])outLinks.toArray(new Outlink[outLinks.size()]);
                    ParseData parseData = new ParseData(status, title, newOutLinks, parse.getData().getContentMeta(), parse.getData().getParseMeta());
                    parseResult.put(content.getUrl(), new ParseText(elements.text()), parseData);
                    }
                   //return parseResult with modified outlinks
                   return parseResult;
            }

Build new plugin using ant and add plugin in nutch-site.xml.
<property>
    <name>plugin.includes</name>
    <value>protocol-httpclient|<custom_plugin>|urlfilter-regex|parse-(tika|html|js|css)|index-(basic|anchor)|query-(basic|site|url)|response-(json|xml)|summary-basic|scoring-opic|urlnormalizer-(pass|regex|basic)|indexer-elastic</value>
  </property>

And in parser-plugins.xml you can use your custom plugin instead of default plugin used by tika by something like this :-
<!--
    <mimeType name="text/html">
        <plugin id="parse-html" />
    </mimeType>

        <mimeType name="application/xhtml+xml">
        <plugin id="parse-html" />
    </mimeType>
-->

    <mimeType name="text/xml">
        <plugin id="parse-tika" />
        <plugin id="feed" />
    </mimeType>

    <mimeType name="text/html">
        <plugin id="<custom_plugin>" />
    </mimeType>

                <mimeType name="application/xhtml+xml">
        <plugin id="<custom_plugin>" />
    </mimeType>

A: You need to override the parsefilter and use Jsoup selector to select particular div.


text:
Q: Which of these has continuous sample path? Which or these statements is true and what is the rule for continuous space:
$(\mathbb{R},\mathcal{B}(\mathbb{R}),\mathbb{P})$, where $Z = \{ Z_t: 0\leq t\leq 10 \}$:
1) $Z_t(\omega) := t*\omega$

*

*Z has continuous sample path

2) $Z_t(\omega) := I_{[t,\infty]}(\omega)$

*

*Z has continuous sample path

*Z has right continuous sample path
3) $Z_t(\omega) := I_{[-t,t]}(\omega)$

*

*Z has continuous sample path

*all the sample paths of Z are continuous (does this paraphrased sentence makes difference)
4) $Z_t(\omega) := t*I_{[-1,1]}(\omega)$

*

*Z has continuous sample path

*all the sample paths of Z are continuous (does this paraphrased sentence makes difference)

redpajama_set_name: RedPajamaStackExchange


text:
Q: WakeLock Acquisition Issue In Broadcast Receiver I developing an application where i need a broadcast receiver to generate notifications
on receiving messages from GCM push.
The code i am using refuses to compile, stating that
   "Cannot make a static reference to the non-static method acquire() from
  the type PowerManager.Wakelock"

The IDE (eclipse) now suggests i should
 remove argument to match "acquire()"

However when i do that, the next error shown is:
 The method acquire(long) in the type PowerManager.WakeLock is not applicable
  for the arguements(Context)....

The code for the broadcast receiver is :
   private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
    String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);

    WakeLock.acquire(getApplicationContext());

    // Showing received message
    lblMessage.append(newMessage + "\n");
    Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();

    // Releasing wake lock
    WakeLock.release();
}

Where am i missing it?

A:
How to acquire the wakelock in broadcastReceiver.?

private PowerManager.WakeLock wakeLock;  //Declaration of Instance variable.

@Override
public void onReceive(Context context, Intent intent) {
    //......Code.....
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP
                       | PowerManager.ON_AFTER_RELEASE,"Wake Lock");
    wakeLock.acquire(15*1000);
    //......Code....
}

Add permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WAKE_LOCK" />


text:
Q: How to create custom auto generated id? And how do I find auto generated id? I have a dealer sign up  and  once the dealer signs up , It takes him to a
 confirmation page where the dealer profile is shown  and can confirm it.
So when I accept the values from the dealer I insert the values into a temporary table with an auto generated ID (which is a string) and then display the Profile in another page.
My questions are:

*

*How do you generate an ID automatically when the dealer clicks on submit (type VARCHAR Example. RBCE001). This ID will be the dealer_ID(PK).

*Once generated and added to the temporary table , How do I find the auto-generated ID and display the information?

*I also have to insert the auto generated dealer id in various other tables. I cannot do so without knowing it.

P.S I cannot use POST variables or SESSIONS as the information provided by the dealer is used to get multiple values from the DB. And then displayed. I do not require hard codes, I just require the logic or direct me in the right direction .


text:
Q: Left Join between 3 tables I have 3 tables as follows:
Table 1 contains the following
Id    Name      Section    Salary
---------------------------------
1     Mark      It         1000
2     Dad       Hr         2000

Table 2 contains this sample data:
Id    Item         Salary
--------------------------
1     Holday         50
1     Food           30
1     Rent          100
2     Food          200
2     Rent          200

Table 3 contains this data:
Id    Descriptions    Cost
---------------------------
1     Bonce            150
1     Rate             300
2     Car              100
2     Bonce             15
2     Rate              30

I need to have the data like the attached screenshot:

A: That is an interesting computing problem independent of your use. It does not a simple join the tables. That is the part of SQL Server enforce, in your report tool you need to do the adjusts.
Table preparation
DECLARE @table1 table (Id int, Name varchar(10), Section varchar(10), Salary decimal(18,2))
DECLARE @table2 table (Id int, Item varchar(10), Salary decimal(18,2))
DECLARE @table3 table (Id int, Descriptions varchar(10), Cost decimal(18,2))

INSERT @table1 values
(1, 'Mark', 'It', 1000)
,(2, 'Dad ', 'Hr', 2000)

INSERT @table2 Values
(1,'Holday', 50)
,(1,'Food ', 30)
,(1,'Rent ',100)
,(2,'Food ',200)
,(2,'Rent ',200)

INSERT @table3 values
(1, 'Bonce', 150)
,(1, 'Rate ', 300)
,(2, 'Car ', 100)
,(2, 'Bonce', 15)
,(2, 'Rate ', 30)

The Select
;WITH
lv0(n) AS (SELECT 0 FROM   (VALUES (0), (0))G(n)), --2
lv1(n) AS (SELECT 0 FROM   lv0 a CROSS JOIN lv0 b), -- 4
lv2(n) AS (SELECT 0 FROM   lv1 a CROSS JOIN lv1 b), -- 16
lv3(n) AS (SELECT 0 FROM   lv2 a CROSS JOIN lv2 b), -- 256
lv4(n) AS (SELECT 0 FROM   lv3 a CROSS JOIN lv3 b), -- 65,536
--lv5(N) as (select 0 from lv4  a cross join lv4 b), -- 4,294,967,296
tally(n) AS (SELECT Row_number() OVER( ORDER BY (SELECT NULL)) FROM   lv4),
t1 AS (SELECT Row_number() OVER( ORDER BY id ) N ,* FROM   @table1),
t2 AS (SELECT Row_number() OVER( ORDER BY id ) N ,* FROM   @table2),
t3 AS (SELECT Row_number() OVER( ORDER BY id ) N ,* FROM   @table3)
SELECT a.NAME
       ,a.section
       ,a.section
       ,b.item
       ,b.salary
       ,c.descriptions
       ,c.cost
       ,a.id
       ,b.id
       ,c.id
FROM   tally t
       CROSS JOIN t1 a
       LEFT JOIN t2 b
              ON t.n = b.n
                 AND a.id = b.id
       LEFT JOIN t3 c
              ON t.n = C.n
                 AND a.id = c.id
WHERE  a.id IS NOT NULL
       AND ( b.id IS NOT NULL
              OR c.id IS NOT NULL )
ORDER  BY a.n
          ,b.n
          ,c.n

The result
NAME       section    section    item       salary                                  descriptions cost                                    id          id          id
---------- ---------- ---------- ---------- --------------------------------------- ------------ --------------------------------------- ----------- ----------- -----------
Mark       It         It         Holday     50.00                                   Bonce        150.00                                  1           1           1
Mark       It         It         Food       30.00                                   Rate         300.00                                  1           1           1
Mark       It         It         Rent       100.00                                  NULL         NULL                                    1           1           NULL
Dad        Hr         Hr         NULL       NULL                                    Car          100.00                                  2           NULL        2
Dad        Hr         Hr         Food       200.00                                  Bonce        15.00                                   2           2           2
Dad        Hr         Hr         Rent       200.00                                  Rate         30.00                                   2           2           2


text:
Q: Is Flash/Actionscript any safer than Javascript for persistent online game? I'm finding lately how unsecure Javascript is when programming a game (I'm trying to do a turn based RPG and currently the battle calculations are done through Javascript which any player can cheat with of course giving themselves as much XP as they want), so I'm wondering if I were to move my battle screen to flash if this would be any more secure, or is there just as easy of a way to cheat this?

A: Come on. It's the same question really. Answer remains the same too:
No matter what the game, whether JS Flash or native binary, if the scoring system is vulnerable, people will tamper if the game is good enough. Stick to clever serverside every time.
This is not a problem that can be solved by obfuscation at the client end. There's plenty of prior art concerning keeping high-score tables/game data secure. Sharpen your google-fu and have a look.
Although the title of this post would suggest it's not applicable, I'd consider the difference between a browser/non-browser game to be irrelevant in this regard. As such, take a look:
Secure Online Highscore Lists for Non-Web Games

A: This is very slightly safer as flash source is harder to read then js source. However neither is particularly safe.

A: As I said in a previous answer, a secure system can not trust client score input.  It doesn't matter whether the intended program is Flash or JavaScript.  Once you send the program to the client they have any required key.  So you can't rely on the client giving you accurate scores.  The only reliable way to do it is to move score calculation to the server.  Then, for a bot to play it still would have to calculate every movement manually.


text:
Q: Configuring FreeMarker In Spring Application I am new to freemarker,but i want to fetch the data from Spring Application to my view which has extension .ftl.I am using ${message} but it displays as usual.It should display the data which is availble in message from Spring Application.
I am configured  dispatcherServlet as below
   <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
       <property name="templateLoaderPath" value="/WEB-INF/freemarker/"/>
      </bean>

  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="cache" value="true"/>
       <property name="prefix" value="/WEB-INF/jsp/"/>
       <property name="suffix" value=".ftl"/>
  </bean>

A: You don't use InternalResourceViewResolver with Freemarker, you use FreemarkerViewResolver. Replace that, you should be fine.
Also, I suggest not putting your freemarker templates in /WEB-INF/jsp. They're not JSPs, and should never be treated as such.


text:
Q: Calculate Naive Baysian classifier I'm preparing Dell EMC Associate data science certificate. The following is one of the mock questions and I'm having problem to calculate it by hand and need help. The correct answer is $Y=1$, $probability = 4/54$ and $Y=0$, $probability = 1/54$
However, I'm not able to get correct answer.

Consider the training data set shown in above table. What are the classifications ($Y=0$ or $Y=1$), and the probabilities of the classifications for the tuple $X (0,0,1)$ using Naive Bayesian classifier?
Calculations:
$$
P(Y=1)P(X_1=0|Y=1)P(X_2=0|Y=1)P(X_3=1|Y=1)  \\ P(Y=0)P(X_1=0|Y=0)P(X_2=0|Y=0)P(X_3=1|Y=0)
$$
\begin{align}
P(Y=1) &= 9/18  \\
P(Y=0) &= 9/18  \\
P(X_1=0|Y=1) &= 2/9  \\
P(X_2=0|Y=1) &= 1/9  \\
P(X_3=1|Y=1) &= 2/9
\end{align}
But,
$$\frac 2 9 \times \frac 1 9 \times \frac 2 9 \times \frac 9 {18} \ne \frac 5 {54}$$

A: ** CORRECTION - the corrected answer is for the tuple (1,0,0), not for (0, 0, 1) -  typo on the question
$$P(Y=0|X_1=1,X_2=0,X_3=0)\\= P(Y=0)\times P(X_1=1|Y=0)\times P(X_2=0|Y=0)\times P(X_3=0|Y=0)\\=1/2\times2/3\times1/3\times2/3=4/54$$
$$P(Y=1|X_1=1,X_2=0,X_3=0)\\= P(Y=1)\times P(X_1=1|Y=0)\times P(X_2=0|Y=0)\times P(X_3=0|Y=0)\\=3/6\times1/3\times 1/3\times1/3=1/54$$
$4/54 > 1/54$ => the correct answer is Classification $Y = 0$, $Probability = 4/54$


text:
Q: How to serialize Kotlin data-class with default values into JSON using kotlinx.serialization? There is an example of a class with a default value:
@Serializable
data class TestClass(
    val obligatory: String,
    val optional: Int = 0
)

It can be correctly deserialize from jsons like: { "obligatory":"text", "optional":1 } and { "obligatory":"text" }.
At the same time, the result of its serialization has to contain the attribute "optional".
As a result of serialization:
Json.encodeToString(TestClass("text"))

I expect { "obligatory":"text", "optional":0 }, however now I have { "obligatory":"text" }.
How should I change my code to achieve the expected result?

A: By default, Kotlinx Serialization doesn't encode default values. I guess it assumes you're using the same data model on the other side.
You can force serializing default values when you configure your serializer:
val json = Json { encodeDefaults = true }

json.encodeToString(TestClass("text"))

Since version 1.3.0, it is now also possible to change this behaviour only for specific properties using the @EncodeDefault annotation (independently of the format's config). So if you wanted this only for this specific property, you could write (and keep the default format config):
@Serializable
data class TestClass(
    val obligatory: String,
    @EncodeDefault
    val optional: Int = 0,
)

Conversely, if you have enabled the encoding of default values globally in your format configuration, you can override this behaviour to not encode the default for a specific property:
@Serializable
data class TestClass(
    val obligatory: String,
    @EncodeDefault(EncodeDefault.Mode.NEVER)
    val optional: Int = 0,
)

val json = Json { encodeDefaults = true }
// then this will NOT encode the default, despite the format's config
json.encodeToString(TestClass("text"))

A: As @Joffrey mentioned you can configure the serializer.
Another option is to use the @EncodeDefault annotation as the documentation mentions:
@Serializable
data class TestClass(
    val obligatory: String,
    @EncodeDefault val optional: Int = 0
)


text:
Q: how to customize export data(listview) SuiteCRM I am able to customize if i write create_export_query() in main modules(modules/Leads/lead.php)
but I want this should be upgrade safe code,
can we add create_export_query() method in custom path instead of in lead.php
if so in which file we can add this function other than main module location?
custom/modules/Leads/lead.php will work?
thanks
Naren

A: custom/modules/Leads/lead.php will not work until you change beanFile location into main bean.
There are 2 ways to do this.
1) Make an extension, custom/Extension/application/Ext/Include, make
a new file CustomLeads.php, put your custom BeanFile location here
for lead module.

2) As export is certainly an action,you may create a custom
controller,ie custom/modules/Leads/controller.php, create a new
function action_export, put your custom code there.

Overriding bean of Suite core module is not recommeneded as it may crack whole system at any point. You should go with #2.


text:
Q: Get historical Klines for multiple pair combination with a base (USDT) At the moment I have a a very manual process for returning a single pair of historical candlestick data from Binance e.g AVAXUSDT
I would like to be able to get candlestick data from Binance for multiple pair combinations with USDT (or other) as the base currency e.g. AVAXUSDT, LUNAUSDT, ADAUSDT etc.
Here's part of my script returning the single pair
candlesticks = client.get_historical_klines("AVAXUSDT", Client.KLINE_INTERVAL_12HOUR, "1 Jan, 2019", "18 Sep, 2021")

How might I get many pairs?

A: A possible solution:
import binance
import time

# tqdm not necessary, is only used for showing progress during klines iteration
from tqdm import tqdm

def multiple_klines(quote_currency: str) -> dict:
    klines = {}

    # You don't need API key/secret for this type of requets
    client = binance.Client()

    # Extract trading pairs from exchange information
    exchange_info = client.get_exchange_info()
    symbols = [x['symbol'] for x in exchange_info['symbols']]

    # Filter list
    selected_symbols = list(filter(lambda x: x.endswith(quote_currency), symbols))

    # Iterate over filtered list of trading pairs
    for symbol in tqdm(selected_symbols):
        klines[symbol] = client.get_historical_klines(
            symbol, client.KLINE_INTERVAL_12HOUR,
            "1 Jan, 2019", "18 Sep, 2021"
        )

        # Prevent exceeding rate limit:
        if int(client.response.headers['x-mbx-used-weight-1m']) > 1_000:
            print('Pausing for 30 seconds...')
            time.sleep(30)

    return klines

klines_dict = multiple_klines('USDT')

Notes:

*

*No authentication needed (API key/secret) for this type of calls. But be aware of the rate limits (allowed calls to the API per minute).

*Your selected time span and interval for the klines call will not contain all the data from start to end, because the API only returns 500 "rows" (per default, 1000 max). Your selected time span is 992 days, and therefore 1984 "rows" with a 12 hour interval.

*Returns a dict containing the trading pairs (e.g. BTCUSDT) as key and the klines data as value.

*Klines data is returned as nested list. You can find the documentation here.

A: You can literate list of altcoins like this:
alts_list = ['1INCH', 'ADA', 'ATOM', 'ANKR', 'ALGO', 'AVAX', 'AAVE','AUDIO', 'AR',
            'BAT', 'CHZ', 'COTI', 'CAKE','FTT','FLOW','APE','AGLD', 'BNB','ETH',
           'DOT', 'DOGE', 'EOS', 'ETC', 'ENJ', 'EGLD',  'FTM', 'FIL', 'AXS',
            'HOT', 'IOTA', 'ICP', 'KSM', 'LINK', 'LTC', 'LUNA','GALA', 'HBAR',
             'MATIC', 'MANA', 'NEO', 'NEAR', 'ONE', 'RVN', 'SAND', 'XMR','XTZ', 'ZEC',
             'SOL', 'TFUEL', 'THETA', 'UNI', 'VET', 'WAVES', 'XRP', 'XLM', 'ZIL'
     ]
for alt in alts_list:
        klines = client.get_historical_klines(alt + "USDT", Client.KLINE_INTERVAL_1MINUTE,
                                              "250 minutes ago UTC")


text:
Q: How to change button color on button click in C#? I am creating an online test application, in which I am generating approximately 100 buttons at run time on form load. Here is the piece of code:w
private void addQuestion_Reviewbutton()
        {
            for (int i = 1; i <= clsGlobalVars.gnTotalQuestion; i++)
            {
                Button button = new Button();
                button.Location = new Point(160, 30 * i + 10);
                button.Click += new EventHandler(ButtonClickOneEvent);
                button.Tag = i;
                button.Name = "Question" + i;
                button.Text = i.ToString();
                button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button));
                button.BackgroundImageLayout = ImageLayout.Stretch;//.Zoom;
                button.FlatAppearance.BorderSize = 0;
                button.Size = new System.Drawing.Size(47, 41);
                button.BackColor = Color.Transparent;
                button.FlatStyle = FlatStyle.Flat;
                button.Font = new System.Drawing.Font("Segoe UI Semibold", 12);
                button.ForeColor = Color.White;
                button.Cursor = Cursors.Hand;
                flowLayoutPanel1.Controls.Add(button);

            }
        }

and on this button click, I am changing the background-color.
void ButtonClickOneEvent(object sender, EventArgs e)
        {
            Button button = sender as Button;
            //button.BackColor = Color.Yellow;
            button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button_Orange));
            lblQuestionNo.Text = ((int)button.Tag).ToString()+".";
            btnNext.Focus();

        }

I have a button on the form Named "Next". Now my problem is that if I am currently in question "1." and I press the button next I want to change the background image of the button whose text is "2".

A: Yo check this !
tldr; the guidance are

*

*Is the click event go to ButtonClickOneEvent ?

*How to call other button

*...

*profit?
  protected void Page_Load(object sender, EventArgs e)
 {
    addQuestion_Reviewbutton();
 }

  void ButtonClickOneEvent(object sender, EventArgs e)
 {
     Button button = sender as Button;

     var currentbtn_id = button.ID;
     int nextid =  Convert.ToInt32( currentbtn_id.Substring("Question".Length)) + 1;
    var nextBtn = flowLayoutPanel1.FindControl("Question"+ nextid.ToString() );
     (nextBtn as Button).BackColor = Color.Red;

 }


text:
Q: Detect last call of JQuery Plugin Constructor after multiple instantiation I'm building a JQuery Plugin that users will be able to call multiple times depending on specific options and preferences.
I'm looking for a way to know when they make the last call, because I need to execute some code during the very last call.
For example, let's say the code is thus:
$('body').myPlugin(options_1);
$('body').myPlugin(options_2);
$('body').myPlugin(options_3);

Is there a way for me to determine how many times that my plugin constructor has been defined e.g. before my plugin code is run, or from the last plugin constructor?!
Just as an analogy, in JQuery there is the .last() method to get the last item in a set of matched elements. I'm trying to do the same thing, only this time with Javascript Constructors, so can run some code at the end of all the calls.


text:
Q: dynamic sql not working . Regular sql working I am creating two table and trying to do select * into using sql and dynamic sql . I am not sure why the same query in dynamic sql is throwing me error . Can you please help
Note: I know I can use create table and insert into to make it work. But my question is why below is not working with dynamic sql
create table emp_info (emp_id int,sal float)
create table emp_sal(emp_id int,sal float)

insert into emp_info values (1,1000)
insert into emp_info values (2,1000)
insert into emp_sal values (1,1000)
insert into emp_sal values (2,1000)

BEGIN
   SELECT A.emp_id,A.sal  into  #EE_tmp
   FROM emp_info A, emp_sal B
   WHERE A.emp_id = 1   AND A.emp_id = B.emp_id
   select * from  #EE_tmp
 END

Result: emp_id    sal 1   1,000

BEGIN
    DECLARE @dsql varchar(10000)
    SET @dsql = ' SELECT A.emp_id,A.sal  into  #EE_tmp'
                 + ' FROM emp_info A, emp_sal B'
                 + '  WHERE A.emp_id = 1'
                 +'  AND A.emp_id = B.emp_id'
                 EXECUTE(@dsql)
                 select * from #EE_tmp
 END

Result:

Error: #EE_tmp not found. Specify owner.objectname or use sp_help to
  check whether the object exists (sp_help may produce lots of output).


text:
Q: How to boot using EFI with custom Ubuntu 22 image? I have a customized Ubuntu ISO, generated with genisoimage until Ubuntu 20. Unfortunately, Ubuntu 22.04 removed isolinux from its ISO, see here: https://github.com/covertsh/ubuntu-preseed-iso-generator/issues/5
I'm moving to xorriso to build an Ubuntu 22 ISO with this commands:
dd if=ubuntu-22.04-desktop-amd64.iso bs=1 count=432 of=/tmp/boot_hybrid.img
dd if=ubuntu-22.04-desktop-amd64.iso bs=512 skip=7129428 count=8496 of=/tmp/efi.img

xorriso -as mkisofs -r \
  -V 'Ubuntu 22.04 LTS MODIF (EFIBIOS)' \
  -o output/custom_ubuntu22.iso \
  --grub2-mbr /tmp/boot_hybrid.img \
  -partition_offset 16 \
  --mbr-force-bootable \
  -append_partition 2 28732ac11ff8d211ba4b00a0c93ec93b /tmp/efi.img \
  -appended_part_as_gpt \
  -iso_mbr_part_type a2a0d0ebe5b9334487c068b6b72699c7 \
  -c 'boot.catalog' \
  -b 'boot/grub/i386-pc/eltorito.img' \
 -no-emul-boot \
  -boot-load-size 4 \
  -boot-info-table \
  --grub2-boot-info \
  -eltorito-alt-boot \
  -e '--interval:appended_partition_2:::' \
  -no-emul-boot \
  ./iso

Here is what happens when I try to use EFI in VirtualBox:

Booting without EFI works fine.
I'm using ddrescue to create a bootable USB key, it's not working anymore with this new ISO.
How can I make this ISO bootable on EFI?
Thanks!


text:
Q: javascript navigator objects not showing in alert box I've tried many time to solve this but, I'm get entire code in alert box.
Can anyone solve this?
function detail(){
        var txt="";
        txt ="
Browser CodeName: "+ navigator.appCodeName +"
";
        txt +="
Browser Name: "+ navigator.appName +"
";
        txt +="
Browser Version: "+ navigator.appVersion +"
";
        txt +="
Cookies Enabled: "+ navigator.cookieEnable +"
";
        txt +="
Browsr Language: "+ navigator.language +"
";
        txt +="
Browser Online: "+ navigator.onLine+"
";
        txt +="
Platform: "+ navigator.platform +"
";
        txt +="
User-agent header: "+ navigator.userAgent +"
";
        txt +="
User-agent language: "+ navigator.systemLanguage +"
";

        alert(txt);
    }

When user click on button it shows alert with navigator details of browser
    <input type="button" value="Detail" onclick="detail()"/>

A: I presume you wanted each item on a new line hence the
 tags. You can't put HTML markup in an alert box but you can use \n.
function detail(){
    var txt="";
    txt ="Browser CodeName: "+ navigator.appCodeName +"\n";
    txt +="Browser Name: "+ navigator.appName +"\n";
    txt +="Browser Version: "+ navigator.appVersion +"\n";
    txt +="Cookies Enabled: "+ navigator.cookieEnable +"\n";
    txt +="Browsr Language: "+ navigator.language +"\n";
    txt +="Browser Online: "+ navigator.onLine+"\n";
    txt +="Platform: "+ navigator.platform +"\n";
    txt +="User-agent header: "+ navigator.userAgent +"\n";
    txt +="User-agent language: "+ navigator.systemLanguage +"\n";

    alert(txt);
}

http://jsfiddle.net/Me3xq/

A: Did a quick research not sure if this can meet your requirement.. You can use Unicode characters and the escape characters \n and \t. An example:
alert(
    'This is an alert with basic formatting\n\n'
    + "\t• list item 1\n"
    + '\t• list item 2\n'
    + '\t• list item 3\n\n'
    + 'Simple table\n\n'
    + 'Char\t| Result\n'
    + '\\n\t| line break\n'
    + '\\t\t| tab space'
);

or if you want to use something more perfect use the modal div popup .. here is the link

A: alert(message)

message -- Specifies the text to display in the alert box, or an object converted into a string and displayed
So the coming result is correct. You can't write HTML code in alert.
If you want to write it to DOM use:
document.getElementsByTagName('body')[0].innerHTML=(txt);


text:
Q: globally style all html buttons only without requiring a 'class','id' or 'name' The following styles all input tags, which means any 'type' of input tag gets styled.
input {
 color:#050;
 font: bold 84% 'trebuchet ms',helvetica,sans-serif;
 background-color:#ffffff;
 border:1px solid;
 border-color: #696 #363 #363 #696;

}
how do I isolate it so all button input 'types' are styled differently than text input 'types'
with out needing to add/use 'id','class' or 'name'.
This must be a cross-browser solution.

A: Using css2 selectors you can do what citricsquid and pixeltocode suggested...
These selectors mentioned were added at the IE7 version .. so you cannot do what you want with CSS only on pre-IE7
Either use classes or javascript for IE6..
You can read about it over at miscrosoft: CSS Compatibility and Internet Explorer

A: you can match all HTML buttons using
input[type=submit] { color: #050; }

A: input[type=text]{
  color:#FF9900;
}

input[type=password]{
  color:#FFFF00;
}

input[type=submit]{
  color:#FFFFFF;
}

It supports password, submit, text, select, radio and a couple more. I'll edit in the list when I find it. You should note that some behave strangely, for example an input box (text) with 100px width and 2px padding will appear differently to a submit input box with the same properties, you'll need to pad the submit with an extra 3/4 pixels, if I remember correctly.


text:
Q: iOS InApp purchases do not work in Production (okay in testflight) I have 3 in-apps purchases available in the app.
On the release that is in production, I go to the screen to choose a subscription plan.
When I click the subscribe button, no bottom sheet opens up to confirm the price/subscription and ask the user to validate.
It is working fine in the testflight with the exact same build:

A: The issue was coming from a wrong paramater passed to the validateIosReceipt function used in the code
The second paramater should be false (isTests) when in production otherwise the wrong receipt validation url is being called
But it means the same build cannot be used for TestFlight and for Production, as for TestFlight that parameter should be true, but in production should be false

A: You could use this extension on Bundle to determine the correct value for your isTests parameter:
public extension Bundle {
    var isTests: Bool {
        #if DEBUG
            return true
        #else
            return self.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
        #endif
    }
}

For debugging and TestFlight builds, this returns true, and for production builds false.


text:
Q: Decorate the active tab in R shiny tabPanel: add nice looking border-top As I am learning R shiny, I realize how little I know about css and html, and would appreciate your help. Currently I would like the active tab in tabPanel to show a color "bar" on top. My solution is to use the following style.css
.content-wrapper .tabbable .nav .active {
    border-top: 3px solid red;
}

The result looks like:
It is basically what I wanted, except that I would want the red line be shorter, not going outside of the tab itself. I tried to change the length of the border-top but was not successful. Any suggestion please? Thank you very much!
Reproducible code see below:
library("shiny")
library("shinydashboard")

ui = dashboardPage(
    dashboardHeader(title = "Title"),
    dashboardSidebar(),
    dashboardBody(
      tags$head(
        #add css style sheet to shiny dashboard
        tags$link(rel = "stylesheet", href = "style.css")),

      tabsetPanel(
        tabPanel(title = HTML(paste("Tab A"))),
        tabPanel(title = HTML(paste("Tab B")))
    )))

server = function(input, output, session) {}

shinyApp(ui = ui, server = server)


text:
Q: OAuth middleware cross-application possible? I'm trying to split my project into three parts. There is the single-page-application, the OAuth-middleware and finally my WebApi.
The user should be able to log in, thats what I need the SPA & middleware for.
Also it should be possible to perform AJAX-requests from JavaScript to my WebApi if the middleware approves (the user is authorized).
Thats how the middleware Startup.cs is configured:
public void Configuration(IAppBuilder app)
{
  app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

  OAuthAuthorizationServerOptions opt = new OAuthAuthorizationServerOptions
  {
    TokenEndpointPath = new PathString("/Security/Token"),
    ApplicationCanDisplayErrors = true,
    AllowInsecureHttp = true,
    Provider = new OAuthAuthorizationServerProvider
    {
      OnValidateAuthorizeRequest = ValidateAuthorizeRequest,
      OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
      OnValidateClientAuthentication = ValidateClientAuthentication,
      OnGrantRefreshToken = GrantRefreshToken,
    },
    RefreshTokenProvider = new AuthenticationTokenProvider
    {
      OnCreate = CreateRefreshToken,
      OnReceive = ReceiveRefreshToken,
    }
  };
  app.UseOAuthAuthorizationServer(opt);

  OAuthBearerAuthenticationOptions _opt = new OAuthBearerAuthenticationOptions();
  app.UseOAuthBearerAuthentication(_opt);
}

Login already works (I get a 200 Status code when communicating with security/token) and JavaScript calls to resources placed in the middleware also work.
I assume, if this is possible, I have to configure another Owin Startup.cs for my WebApi.
What I've done is:
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        OAuthBearerAuthenticationOptions cOpt = new OAuthBearerAuthenticationOptions();
        cOpt.Realm = "http://localhost:61188/Security/Token"; //auth server
        cOpt.AuthenticationMode = AuthenticationMode.Active;
        //cOpt.AccessTokenProvider = new AuthenticationTokenProvider();
        cOpt.Provider = new OAuthBearerAuthenticationProvider
        {
            OnValidateIdentity = ValidateIdentity,
            OnRequestToken = RequestToken
        };
        app.UseOAuthBearerAuthentication(cOpt);
    }

Do you have any ideas what to do to make the requests to my WebApi possible?
If you need more of my code, just ask ;)

A: We implemented this for our BackOffice single page application. We provide our users a login page in which they enter their credentials. We send them to the authentification server which retuns the request-, refresh token and the expire date. Then we store both in a cookie and in memory (the cookie is used to authenticate the user when he refreshes the page without reentering the credentials).
var requestToken, refreshToken, expireDate;

$.ajax({
    method: 'post',
    url: '/api/token',
    data: {
        username: 'John Doe',
        password: 'secret',
        grant_type: 'password'
    },
    success: function(res) {
        requestToken = res.requestToken;
        refreshToken = res.refreshToken;
        expireDate = res.expireDate;
    }
})

To request data from webapi the request token is attached to the Authorization header.
$.ajax({
    url: '/api/article',
    headers: {
        'Authorization': 'Bearer' + token
    }
})

To renew the request token a timer is set to the expire date minus some seconds.
setTimeout(function() {
    $.ajax({
        method: 'post',
        url: '/token',
        data: {
            refresh_token: refreshToken,
            grant_type: 'refresh_token'
        },
        headers: {
            'Authorization': 'Bearer' + token
        },
        success: function() {
           // store new token
        }
    });
}, new Date(expireDate) - (new Date()) - 120000);

A: Adding the Microsoft.Owin.Host.SystemWeb reference to my project solved the issue. I'm still getting Unauthorized-responses when using $.ajax, but angulars resource and http services are working correctly.
I also could limit the resource servers owin startup action to:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
OAuthBearerAuthenticationOptions opt = new OAuthBearerAuthenticationOptions();
app.UseOAuthBearerAuthentication(opt);


text:
Q: ERROR: layout-large already exists. Use a different qualifier I have two layouts, for one I create more layouts for different screen sizes.  But when I do the same for the latter I get this error. For example, there is a "Large" for mainlayout but not for the second layout, still, I am taking this error.

OK is disabled.

A: Android Studio displays your project files in the Android view. This view does not reflect the actual file hierarchy on disk. To see the actual file structure of the project including all files hidden from the Android view, select Project from the dropdown at the top of the Project window.
When ever you changed then you see layout-large already exists in your res folder.
For custom layout folder, Go into your modules gradle.build file and create a sourceSets definition like below
sourceSets {
    main {
        res.srcDirs = ['src/main/res',
                       'src/main/res/layouts/custom_layout_folder_name'

        ]
    }
}


text:
Q: multiline regex with lookahead I`m currently trying to read a log file with regex. My logs begin with a timestamp followed by a random multiline message which can include multiple new lines, returns and all types of character.
The regex should capture everything starting with the timestamp, the actual log message until we reach a new timestamp. At the moment I do this by using a positive lookahead till the next timestamp.
On the webside regex101 the code works more or less. In our security event manager the same regex doesn't work. I need to save every event with the timestamp being the first capturing group and the log message being the second capturing group.
(\w{3}\s{1}\w{3}\s{1}\d{2}\s{1}\d{2}\:\d{2}\:\d{2}\s{1}\d{4})((\r||.|\n)*)(?=(\w{3}\s{1}\w{3}\s{1}\d{2}\s{1}\d{2}\:\d{2}\:\d{2}\s{1}\d{4}))

Example log:

Tue Sep 14 08:57:47 2021
Thread 1 advanced to log sequence 186 (LGWR switch)
Current log# 2 seq# 186 mem# 0: D:\ORADB\DV1\REDO02A.LOG
Current log# 2 seq# 186 mem# 1: H:\ORADB\DV1\REDO02B.LOG
Tue Sep 14 09:07:40 2021
Thread 1 advanced to log sequence 187 (LGWR switch)
Current log# 3 seq# 187 mem# 0: D:\ORADB\DV1\REDO03A.LOG
Current log# 3 seq# 187 mem# 1: H:\ORADB\DV1\REDO03B.LOG
Tue Sep 14 09:22:09 2021
Thread 1 advanced to log sequence 188 (LGWR switch)
Current log# 4 seq# 188 mem# 0: D:\ORADB\DV1\REDO04A.LOG
Current log# 4 seq# 188 mem# 1: H:\ORADB\DV1\REDO04B.LOG

regex101
Btw the code only works when I include the \r||.|\n "or null" part of the regex, which I dont understand at all.

A: You can use [\s\S]* to match any characters since \s is for whitespace (including new lines) while \S is for non-whitespace. For it to not span the whole text, in other words for it to be non-greedy, use the ? symbol e.g. [\s\S]*? Try this pattern:
(\w{3}\s\w{3}\s\d{2}\s\d{2}:\d{2}:\d{2}\s\d{4})([\s\S]*?)(?=\w{3}\s\w{3}\s\d{2}\s\d{2}:\d{2}:\d{2}\s\d{4}|\Z)

Where:

*

*( - Start of 1st capturing group

*

*\w{3}\s\w{3}\s\d{2}\s - Match Tue Sep 14

*\d{2}:\d{2}:\d{2}\s\d{4} - Match 08:57:47 2021

*) - End of 1st capturing group

*( - Start of 2nd capturing group

*

*[\s\S]*? - Match any characters including new lines. The match will be in a non-greeedy way (thus the least possible match).

*) - End of 2nd capturing group

*(?= - Start of look ahead assertion

*

*\w{3}\s\w{3}\s\d{2}\s\d{2}:\d{2}:\d{2}\s\d{4} - The next part must either be the timestamp (this is the same pattern as the matching of the timestamp in the first part of this whole regex).

*| - Or

*\Z - Or the next part must be the end of string

*) - End of look ahead assertion. Note that since the pattern before this is non-greedy, this will always be the closest timestamp, thus is always the next timestamp.


text:
Q: TypeError: Cannot read property 'length' of undefined angular-cli after update I am getting the above error saying TypeError: Cannot read property 'length' of undefined after I converted and updated my old angular project.
Everything seems to be setup correctly but I am not sure why I am getting this error. I look around SOF and nothing popped out and most were out dated.
I also posted it on GitHub Link Here
package.json
{
  "name": "DemoTestApp",
  "version": "0.0.1",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": ""
  },
  "scripts": {
      "ng": "ng",
      "start": "ng serve",
      "pree2e": "webdriver-manager update --standalone false --gecko false",
      "test": "karma start",
      "e2e": "protractor"
  },
    "dependencies": {
        "@angular/common": "^2.3.1",
        "@angular/compiler": "^2.3.1",
        "@angular/core": "^2.3.1",
        "@angular/forms": "^2.3.1",
        "@angular/http": "^2.3.1",
        "@angular/platform-browser": "^2.3.1",
        "@angular/platform-browser-dynamic": "^2.3.1",
        "@angular/router": "^3.3.1",
        "core-js": "^2.4.1",
        "rxjs": "^5.0.1",
        "ts-helpers": "^1.1.1",
        "zone.js": "^0.7.2"
    },
    "devDependencies": {
        "@angular/compiler-cli": "^2.3.1",
        "@types/jasmine": "2.5.38",
        "@types/node": "^6.0.42",
        "angular-cli": "1.0.0-beta.24",
        "codelyzer": "~2.0.0-beta.1",
        "jasmine-core": "2.5.2",
        "jasmine-spec-reporter": "2.5.0",
        "karma": "1.2.0",
        "karma-chrome-launcher": "^2.0.0",
        "karma-cli": "^1.0.1",
        "karma-jasmine": "^1.0.2",
        "karma-remap-istanbul": "^0.2.1",
        "protractor": "~4.0.13",
        "ts-node": "1.2.1",
        "tslint": "^4.0.2",
        "typescript": "~2.0.3",
        "jest-cli": "*"
    }
}

angular-cli:
{
  "project": {
    "version": "1.0.0-beta.24",
    "name": "Test-Demo"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "app",
      "mobile": false,
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "addons": [],
  "packages": [],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "prefixInterfaces": false,
    "inline": {
      "style": false,
      "template": false
    },
    "spec": {
      "class": false,
      "component": true,
      "directive": true,
      "module": false,
      "pipe": true,
      "service": true
    }
  }
}

If I need to post anything else let me know. This error really has me stumped.


text:
Q: mongo priority 0 member not being used Folks,
  We have seen a very strange issue with MongoDB v2.6.9 when slaves with priority=0 are not being used for read requests and are not returned as part of discovery.  When changing the priority to a non-zero value solves the issue and make these members discoverable.
Making the priority a non-zero value is not the desired behavior, as this setting will allow the member to become primary.  These members are in a separate AWS region, and we want to avoid a split-brain situation.
Current Config:  (Notice we prefer the west region to always be primary)
rs0:PRIMARY> rs.config()
{
    "_id" : "rs0",
    "version" : 24,
    "members" : [
        {
            "_id" : 7,
            "host" : "west1:27017",
            "priority" : 1000,
            "tags" : {
                "dc" : "west"
            }
        },
        {
            "_id" : 8,
            "host" : "west2:27017",
            "priority" : 1000,
            "tags" : {
                "dc" : "west"
            }
        },
        {
            "_id" : 9,
            "host" : "west3:27017",
            "priority" : 1000,
            "tags" : {
                "dc" : "west"
            }
        },
        {
            "_id" : 10,
            "host" : "east1:27017",
            "votes" : 0,
            "priority" : 2,
            "tags" : {
                "dc" : "east"
            }
        },
        {
            "_id" : 11,
            "host" : "east2:27017",
            "votes" : 0,
            "priority" : 2,
            "tags" : {
                "dc" : "east"
            }
        }
    ]
}

Using the 1.4.x NodeJS driver, all reads go to {west} nodes, ignoring the {east} instances.

A: Though its strange but I am not sure if it has something to do with the mongo version.
however, looking at your configuration I don't think east member would ever become the primary.
It has lower priority than other members so only one of the west member can become the primary.
http://docs.mongodb.org/manual/core/replica-set-elections/
Every replica set member has a priority that helps determine its eligibility to become a primary. In an election, the replica set elects an eligible member with the highest priority value as primary. By default, all members have a priority of 1 and have an equal chance of becoming primary. In the default, all members also can trigger an election.

A: We have found a bug in 1.4.38 NodeJS MongoDB Driver and are forking it to fix the issue.  It is ignoring any passive mongodb members.
https://github.com/mongodb/node-mongodb-native/commits/V1.4.38


text:
Q: In an ideal world, everybody has/(would have) enough to eat I'm doing an exercise and I have the following sentence under "would" unit:

In an ideal world, everybody (have) enough to eat.

It's obvious, that I should put would have have here but the question is can I use just has:

In an ideal world, everybody has enough to eat.

Are both options grammatically correct? If so, does 'has' in the sentence sound unnaturally in any way?

A: Can you use "has"?  Absolutely.  This changes it from a pure hypothetical to a definitive prediction of what you consider an essential characteristic of an "ideal world".  It sounds much the same as an observation of something that is not hypothetical.
Examples:

In Los Angeles, everyone has a car.  (observation)
  In future Los Angeles, everyone has a flying car.  (prediction)
In France, many people eat croissants for breakfast (observation)
  In an ideal France, everyone eats croissants for breakfast. (prediction)

A: Both options are definitely grammatical.
The structure of the second sentence is the same as a more obviously correct sentence, such as: In France, everybody has red shoes.
So the question is not whether it's grammatically correct (it is) to say "In an ideal world, everybody has enough."  The question is whether it's good style.
Matters of style are largely subjective.  There's no one right answer. To me, the second sentence is fine. I would more likely say, "would have" since this is a hypothetical world, so when I say the sentence, I mean to imply: "If the world were an ideal world, everyone would have enough."  You could also use "will have" if you're feeling optimistic.  This would imply that in the future, we'll reach that ideal state.

A: Both are fine as styles; it's almost down to preference. Using "has" is just a bit unnatural, the speaker asking the listener to oblige him a bit by imagining this supposed world and ascribing qualities to it.  It can be a bit more forceful, especially as a retort to someone arguing for a different opinion of the ideal world. (Bob:"In an ideal world, prisons would rehabilitate criminals." Alice:"An ideal world has no criminals!")
If you are going to go into a long list of statements about the ideal world, you might want to stick with the "has" scheme so that you don't have so many "would"s to type or say, but you might sound a little like an unrealistic person, and if you are unsure about having the support of your audience, "would" is more tactful.


text:
Q: Is it possible to make a custom html head tag in ejs? I have a for loop that will create different head tags to create a nested effect. Is this possible in ejs? Code is something like
<%- for(var i = 0;i<2;i++){ %> <%- <h{i}>Content here</h{i+1} }%>
Expected result should be something like
Content here
Content here

A: This would do the work for you.
<% for(var i = 1; i<=2; i++){ %>
   <h<%= i %>>Content here</h<%= (i+1) %>>
<% } %>


text:
Q: Data length larger than configured limit with Azure Application Gateway WAF we have the WAF in the Application Gateway configured to "Prevention" mode. A couple of use cases in the application require files to be uploaded. Currently those file upload requests are being blocked by the WAF. Firewall Log:
{
...
"properties": {

"requestUri": "/api/v1/attachments",
"ruleSetType": "OWASP",
"ruleSetVersion": "3.0",
"ruleId": "0",
"message": "",
"action": "Blocked",
"site": "Global",
"details": {
  "message": "Request body no files data length is larger than the configured limit (131072).. Deny with code (413)",
  "data": "",
  "file": "",
  "line": ""
},
...
 }
}

is it possible to deactivate this rule or change the limit or...?
would scaling up (pricing tier) help?
I found this but do not want to believe it.

A: Microsoft Support helped us to resolve the issue.
Specifically these comments helped:
with the proper file-upload field there should be no issue. Here's an example:
Content-Disposition: form-data; name="a"; filename="somefile.jpg"
Content-Type: image/jpeg

some jpeg content larger than 128k

This could also happen if "Content-Type: application/json" or "Content-Type: text/xml" is used in the request headers.

A: After several conversations with Microsoft we found that the WAF considers only file attachments if they are sent using multipart/form-data

If you send it this way the WAF will understand it is a file and thus will apply the limits configured for files instead than for bodies.
There is no other way to send files supported by the WAF for now.


text:
Q: MagicalRecord updating entity's relationship objects not working I pass a object to another view controller, and I am trying to update this entity's relationship objects. As you can see below, the "self.stock" is the entity passed to this view controller. First, I delete all it's relationship objects and then add new relationship objects to it.
Stock.h
@class Photo, StockCategory, StockOption;

@interface Stock : NSManagedObject

@property (nonatomic, retain) NSString * name;

@end

@interface Stock (CoreDataGeneratedAccessors)

- (void)addCategoriesObject:(StockCategory *)value;
- (void)removeCategoriesObject:(StockCategory *)value;
- (void)addCategories:(NSSet *)values;
- (void)removeCategories:(NSSet *)values;

- (void)addOptionsObject:(StockOption *)value;
- (void)removeOptionsObject:(StockOption *)value;
- (void)addOptions:(NSSet *)values;
- (void)removeOptions:(NSSet *)values;

@end

Update button action
- (void)submit
{
    self.stock.name = name;

    for (StockCategory *category in self.stock.categories) {
        [category MR_deleteEntity];
    }

    for (StockOption *option in self.stock.options) {
        [option MR_deleteEntity];
    }

    //it seems below not working
    //self.optionsObject contains an array of Option objects, the same as self.categoriesObject below.
    //I am sure array contains actual objects in it.
    for (StockOption *option in self.optionsObject) {
        [self.stock addOptionsObject:option];
    }

    for (StockCategory *cateogry in self.categoriesObject) {
        [self.stock addCategoriesObject:cateogry];
    }

    NSError *error = nil;
    if (![self.stock.managedObjectContext save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]); //no error displayed. but I have used sqlite app to view it's documents, I can see the optionsObject and categoriesObject are not empty.
    }
}


text:
Q: pause between background pic and first textView i'm a new android developer, writing my first app. i want to bring up before the background pic and after a few seconds the first textView. is possible do something like this? and what methods should i use?

A: If I'm understanding right, you want to show your image and after few seconds you want to show your textview.
1 - Make textview visibility in visible by using android:visibility="invisible"
2 - For this you will have to load the image in OnCreate method.
3 - Create a thread and in that thread make your textview visible after delay
 Handler h = new Handler();

         h.postDelayed(new Runnable() {

                @Override
                public void run()
                {
                 textview.setVisibility(View.VISIBLE);
                }

            }, 3000); //3000 = 3sec


text:
Q: gojs-react. When onModelChange happens, how can I differ model changes made by me programmatically from changed made via UI? When I edit the diagram via UI, onModelChange event happens.
When I edit model of diagram via code (model.set(node, deletable, false)), onModelChange event occurs.
I want to have a way to ignore second type of changes. Because I do them during handling the first type of changes. So I am getting recursion.

A: Your onModelChange handler should be setting skipsDiagramUpdate to true. This prevents the handler from being called on changes the GoJS model already knows of.
https://gojs.net/latest/intro/react.html#UsingWrapperComponentWithinApp
https://github.com/NorthwoodsSoftware/gojs-react-basic


text:
Q: Launching a program so that it opens in center of the launching application Launching a program so that it opens in center of the launching application.
Platform: Mac
Launching mechanism: a c++ program launches using system()
Currently I observe the program launched pushes it to left most part of the screen.

A:
Launching a program so that it opens in center of the launching application.

On Mac OS X systems, programs don't launch into a specific area of the screen. When they launch, they become the "front" application, and take over the menubar area with their own menus. They may choose to open a window after they have opened, or not.
Find out if the program in question accepts apple events / applescript commands. If so, you may be able to ask the program to position a window in a particular location.
Also, if you still have to use system, you can send apple events with the osascript command.

A: If you're using system, there's really nothing you can do, since you've implicitly delegated everything about the process except its startup args to the OS. There may be ways to accomplish this using other OSX-specific APIs, but not with the parameters you've outlined here.


text:
Q: Mongodb query for 2 level grouping Suppose I have documents that, among others, have these fields:
{
    "class" : String,
    "type" : String,
    "name" : String,
}

For example, many like this:
{
    "class": "class A",
    "type": "type 1",
    "Name": "ObjectA1"
}

{
    "class": "class A",
    "type": "type 2",
    "Name": "ObjectA2_1"
}

{
    "class": "class A",
    "type": "type 2",
    "Name": "ObjectA2_2"
}

{
    "class": "class B ",
    "type": "type 3",
    "Name": "ObjectB3"
}

What I want is a query that returns me the following structure
{
    "class A" : {
        "type 1" : ["ObjectA1"],
        "type 2" : ["ObjectA2_1", "ObjectA2_2"]
    },
    "class B" : {
        "type 3" : ["ObjectB3"]
    }
}

I tried using aggregate with $group but could not do this. Any thoughts?
PS: I would like to do this on mongodb shell, not mongoose or something like this.

A: The problem with using the aggregation framework will be that you cannot specify an arbitrary key name for a property of an object. So reshaping using that would not be possible without being able to specify all of the possible key names.
So to get the result you would need to work something in JavaScript such as mapReduce:
First define a mapper:
var mapper = function () {

  var key = this["class"];
  delete this._id;
  delete this["class"];

  emit( key, this );

};

Then a reducer:
var reducer = function (key, values) {

  var reducedObj = {};

  values.forEach(function(value) {
    if ( !reducedObj.hasOwnProperty(value.type) )
      reducedObj[value.type] = [];

    reducedObj[value.type].push( value.Name );

  });

  return reducedObj;
};

And because you have ( in your sample at least ) possible items that will be emitted from the mapper with only 1 key value you will also need a finalize function:
var finalize = function (key,value) {

    if ( value.hasOwnProperty("name") ) {
        value[value.type] = value.name;
        delete value.type;
        delete value.name;
    }

    return value;
};

Then you call the mapReduce function as follows:
db.collection.mapReduce(
    mapper,
    reducer,
   { "out": { "inline": 1 }, "finalize": finalize }
)

And that gives the following output:
    "results" : [
            {
                    "_id" : "class A",
                    "value" : {
                            "type 1" : [
                                    "ObjectA1"
                            ],
                            "type 2" : [
                                    "ObjectA2_1",
                                    "ObjectA2_2"
                            ]
                    }
            },
            {
                    "_id" : "class B ",
                    "value" : {
                            "type" : "type 3",
                            "Name" : "ObjectB3"
                    }
            }
    ],

While the result is formatted in a very mapReduce way, it is definitely much the same as your result.
But if you really did want to take that further, you can always do the following:
Define another mapper:
var mapper2 = function () {
    emit( null, this );
};

And another reducer:
var reducer2 = function (key,values) {

  reducedObj = {};

  values.forEach(function(value) {
    reducedObj[value._id] = value.value;
  });

  return reducedObj;

};

Then run the first mapReduce with the output to a new collection:
db.collection.mapReduce(
    mapper,
    reducer,
   { "out": { "replace": "newcollection" }, "finalize": finalize }
)

Followed by a second mapReduce on the new collection:
db.newcollection.mapReduce(
    mapper2,
    reducer2,
   { "out": { "inline": 1 } }
)

And there is your result:
    "results" : [
            {
                    "_id" : null,
                    "value" : {
                            "class A" : {
                                    "type 1" : [
                                            "ObjectA1"
                                    ],
                                    "type 2" : [
                                            "ObjectA2_1",
                                            "ObjectA2_2"
                                    ]
                            },
                            "class B " : {
                                    "type" : "type 3",
                                    "Name" : "ObjectB3"
                            }
                    }
            }
    ],

A: I found a workaround for what I needed. It's not the same but solves my problem.
db.myDb.aggregate(
{
    $group:{
        _id: {
            class_name : "$class",
            type_name : "$name"
        },
        items: {
            $addToSet : "$name"
        }
    }
},
{
    $group:{
        _id : "$_id.class_name",
        types : {
            $addToSet : {
                type : "$_id.type_name",
                items : "$items"
            }
        }
    }
})

this gave me something like:
{
    _id : "class A",
    types: [
        {
            type: "type 1",
            items: ["ObjectA1"]
        },
        {
            type: "type 2",
            items: ["ObjectA2_1", "ObjectA2_2"]
        }
    ]
},
{
    _id : "class B",
    types: [
        {
            type: "type 3",
            items: ["ObjectB3"]
        }
    ]
}

Both code and example were written here so there may be typos.
So this is about it. I want to thank #Neil Lunn for his awesome answer and dedication.
Marcel


text:
Q: How to count total occurence of checked field? I have a checkbox field called Has_Key__c that checks whether an employee has a key to the building or not.
I want to make a sum of all checked Has_Key__c and compare it with a total number of available keys. There is a field that holds this total number, called Total_Keys__c
I want to output Total_Keys__c - Sum(Has_Key__c) somewhere, preferably in a field as well.
What's the easiest way to do so? Formula? Apex? Rollup Summary?

A: You can do this with standard functionality using a roll up summary field and a formula field. This might be accomplished with three objects: Building__c, Key__c, and Building_Key__c. The Building__c would store data about each building, and Key__c would represent a key (e.g. serial number, etc). Building_Key__c would have two master-detail relationships (called a "join object"), one to Building__c and one to Key__c, with a lookup field to a User. From here, you can build a roll up summary that counts the number of keys that are assigned to each building, and, with a field called Total_Keys__c on Building__c, you can then calculate how many keys are left.


text:
Q: AWS Disaster Recovery whitepaper The link is broken https://media.amazonwebservices.com/AWS_Disaster_Recovery.pdf.
I have an error:
<Error>
  AccessDenied
  <Message>Access Denied</Message>
  <RequestId>B80C4C4115C5CEFE</RequestId>
  <HostId>
JVaBsDqLa/6/gfpoqZyfe7lNu7ALgH/PCanmT11Bfn34UJTFaE9Rr/IMwBh6ARpNK21BdzrCzuo=
  </HostId>
</Error>

Does anyone know where I can get it?

A: AWS White Papers can be downloaded from their whitepaper site. I can confirm that it is not available right now, only AWS knows why. It will probably be available again soon.
I happen to have a version from October 2014, which was current as of October 2018 when I downloaded it. This suggests it is an older white paper that is due a refresh. I have put it on my website for download - now removed.


text:
Q: Bash command to sum on group I am totally embarrassed to ask this but I am a total newbie on linux. I have a requirement to perform group sum on data in a text file using only bash. I have achieved some part of requirement but i am unable to get it work for a more complex sum.
Lets say I have a file tst.txt conatining data like below.
fruit   apple   2
fruit   orange  1
veg     carrot  4
veg     chilli  3
fruit   apple   1
fruit   orange  2

Now i want to get three different outputs.
One is the unique occurrence of all the fruits and vegetables.
I used below code to achieve this.
cut -f 2 tst.txt | sort | uniq | wc -l

It gives me the output 4 which are unique values in column 2.
Now I want to sum on different groups.
I have so far got the count of groups like below.
sort -u tst.txt | cut -f 2 | uniq -ic

It gives me below output.
2 apple
2 orange
1 carrot
1 chilli

Now is the difficult part for me. I want to know how many unique fruits are there. Out put should be like this.
fruit 2

Because there are only 2 unique fruits.
I also want to sum number of fruits. That will be
fruit 6

Then i want to get highest average group. In my case it will be
veg 3.5

I would really appreciate if you guys could help me out. Solution must be working on a CSSE Linux computer.
I have came across the solutions which use awk or loop but I want to use simple command like i used earlier and strictly bash with no loops (If that's possible at all). If it cannot be achieved without external commands, then which approach is simplest?


text:
Q: What are some books on history and development of calculus? I am well versed with modern calculus but I want to know how people in history developed the subject. I want to learn how Newton and Leibniz came up with it, what Greeks did with the method of exhaustion et cetera

A: The Calculus Gallery: Masterpieces from Newton to Lebesgue by William Dunham.
It's easy to follow, provides the most important examples or methods by Newton, Weirstrass, Cauchy, Cantor and so on. It also explains some basic concepts, but I like it mostly for its easiness to understand and follow.
Link here: https://www.amazon.com/Calculus-Gallery-Masterpieces-Newton-Lebesgue/dp/0691136262/ref=sr_1_1?ie=UTF8&s=books&qid=1273235330&sr=8-1


text:
Q: visitors IP address doesnt show I have a problem with getting visitor ip address
I am using asp net mvc
I used the following code to save the visitors IP addresses bur unfortunately It didnt work on my local network many visited my page from the LAN but didnt catch any of them , I had a website of many pages and if users visited the another page also a problem it wont catch at all because I have the code in the Home index
please let me know what is wrong with my code and where I have to place the code in the project so it will catch and visitors for any page if the user clicked a link rather the home
here is my code
home controller
public ActionResult Index()
        {
            string currip = string.Empty;
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                currip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else if (System.Web.HttpContext.Current.Request.UserHostAddress.Length != 0)
            {
                currip = System.Web.HttpContext.Current.Request.UserHostAddress;

            }
         //   string currip = HttpContext.Request.UserHostAddress.ToString(); // tried this didnt work it gave me single ip for all visitors
             //   vs.Ip = currip;
                vs.Ip = HttpContext.Request.UserHostAddress.ToString();
                vs.lastaccess = DateTime.Now;
                vs.visits += 1;
                _db.SaveChanges();

           return view();
}

UPDATE
when using
currip = System.Web.HttpContext.Current.Request.UserHostAddress;
for post method adding login information ip appears but for visit it doesnt appear because it is get method
anything to do with that ?

A: public static string getIPAddress(HttpRequestBase request)
    {
        string ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(ipAddress))
        {
            ipAddress = request.ServerVariables["REMOTE_ADDR"];
        }

        return ipAddress;
    }

UPDATE
You can use Visit Attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class VisitAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var descriptor = filterContext.ActionDescriptor;
        var controller = descriptor.ControllerDescriptor.ControllerName;
        var action = descriptor.ActionName;
        var user = filterContext.HttpContext.User.Identity.Name;

        // your code here
     }
}

Then you can call form your controller or action like this:
[Visit]
public class YourController : Controller
{

}

A: additional to Wowo Ot answer which i tried but didnt work and the answer was logically correct but the problem with my code was
old code
vs.visits += 1;
_db.SaveChanges();

I had to edit my code
to
vs.visits += 1;
_db.visit.add(vs); // here was the missing code
_db.SaveChanges();


text:
Q: Difficulty in changing the message of progress dialog in async task I have created an async task and want to change the message of progress dialog during different stages of doBackground. Here is the code:
public class sc extends AsyncTask<Integer,String,Void>
    {
        ProgressDialog dialog;
        protected void onPreExecute()
        {
            dialog=new ProgressDialog(Loc.this);
            dialog.show();
        }
        @Override
        protected Void doInBackground(Integer... params)
        {

            onProgressUpdate("Contacting server..Please wait..");
            //Do some work
            onProgressUpdate("Processing the result");
            //Do some work
            onProgressUpdate("Calculating..");
            dialog.dismiss();
            return null;
        }
        protected void onProgressUpdate(String ui)
        {
            dialog.setMessage(ui);
        }

}

But the problem is that, progress dialog is only showing the first message always. Kindly help me to find a solution.

A: protected Void doInBackground(Integer... params)
{
    onProgessUpdate("Contacting server..Please wait..");
    ...
}

Urrrm, nope, that won't work.
Try...
publishProgress("Contacting server..Please wait..");

You have to "publish" your progress in doInBackground(..) in order for onProgressUpdate(...) to be called.
Also don't call dialog.dismiss() in doInBackground(...) call it in onPostExecute(...) instead.

A: I think it should be..
publishProgress("Your Dialog message..");

not
onProgessUpdate("Processing the result");

in doInBack..()
Something like,
protected Long doInBackground(URL... urls) {
      publishProgress("Hello");
     return null;
 }

 protected void onProgressUpdate(String msg) {
     dialog.setMessage(msg);

 }

A: The issue might also be that you haven't set an "initial message". If you don't set a message for your ProgressDialog before attempting to do so inside of onProgressUpdate it will not work.
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Title");
progressDialog.setMessage("Initial message needed");

public class foo extends AsyncTask<Void,Integer,Void> {
    ...
}

Also note that, if you need both a progress update and a message, you can use an Integer variable argument with one of the integers defining the amount of progress and the other defining the message as an index of a String[] array of messages (if the messages are known beforehand).


text:
Q: Need to remove space and double quotes from file name and file path for all files in directory recursively in .cmd file I am able to get list of all the file names, path size etc using the below code but I have not been able to get rid of double quotes in the file name and file path. Also i have spaces in the file name that breaks when the file name is listed.
@echo off
setlocal enabledelayedexpansion

   if exist Z:\ (net use Z: /delete)
net use Z: "\\my drive path"
SET Path1=Z:\
pushd
SET "Path2=Z:\folder1"

for /f "skip=1 tokens=1,2,3,4,5* delims=,] " %%i in ('forfiles /p "%Path2%" /s /m ""*.mmp"" /c "cmd /c echo @fsize 0x22@file0x22 @path @fdate @ftime"') do (
set FILE_SIZE_WINDOWS=%%i
set FILE_NAME=%%~j
set FILE_PATH=%%~k
set FILE_DATE=%%l
set FILE_TIME=%%m
set "unit=B"
for %%b in (KB MB GB TB PB EB ZB YB) do if 1024 lss !FILE_SIZE_WINDOWS! (
set "unit=%%b"
if  !FILE_SIZE_WINDOWS! lss 2147483647 (set /a "FILE_SIZE_WINDOWS=FILE_SIZE_WINDOWS/1024") else (set "FILE_SIZE_WINDOWS=!FILE_SIZE_WINDOWS:~0,-3!"))
if "!FILE_NAME!" neq "!FILE_NAME:Admin=!" (set Developer=Admin
echo !Developer!)
echo !FILE_NAME! !FILE_SIZE_WINDOWS!!unit! !FILE_PATH! !FILE_DATE! !FILE_TIME! !Developer!
if "!FILE_NAME!" == "!FILE_NAME:Undo=!" (echo !FILE_NAME! does not contain Undo
echo !FILE_NAME! !FILE_SIZE_WINDOWS!!unit! !FILE_PATH! !FILE_DATE! !FILE_TIME! !Developer! >> List.txt
) else (
echo !FILE_NAME! !FILE_SIZE_WINDOWS!!unit! !FILE_PATH! !FILE_DATE! !FILE_TIME! !Developer! >> UndoList2.txt
)
)
echo Done
popd
endlocal

Expected output:
Filename.mmp C:\Filepath


text:
Q: Programming a function that saves and returns values in python I am currently experimenting with Python and programming a little text-adventure. In my game the player has certain properties like hp, attack damage and inventory slots for items.
I want to be able to call these properties from everywhere in my code. For that I created a function that receives three values:
"edit": to specify if a variable should be edited
"info_id": to specify which variable should be accessed
"value": the new value for the variable
This is what it looks like in my code:
def player_info(edit, info_id, value):

  if edit == 1:
  ##function wants to edit value
      if info_id == 1:
          player_hp = value
          print ("Assigned hp to: ", player_hp)
          ##the "prints" are just to check if the asignments work -> they do
          return player_hp

      elif info_id == 2:
          player_attack = value
          print ("Assigned attack to: ", player_attack)
          return player_attack
      elif info_id == 3:
          item_1 = value
          return item_1
      elif info_id == 4:
          item_2 = value
          return item_2
       elif info_id == 5:
          item_3 = value

  elif edit == 0:
  ##function wants to retrieve value
      if info_id == 1:
          return player_hp
      elif info_id == 2:
          return player_attack
      elif info_id == 3:
          return item_1
      elif info_id == 4:
          return item_2
      elif info_id == 5:
          return item_3

There are actually 10 item slots (going up to info_id==13) but they are all the same anyway.
I define all variables at the beginning of my code:
  player_info(1,1,20)
  player_info(1,2,5)
  n=3
  while n<=13:
      player_info(1,n,0)
      n=n+1
##items are not fully implemented yet so I define the item slots as 0

The definition works, I can tell because of the control "print" I implemented in the code. Still when I call a variable, e.g. the health like this:
player_info(0,1,0)

I get an error:
local variable 'player_hp' referenced before assignment

Does the function not save the variable properly? Or what is the problem?
Is there a better way to save variables? Are global variables the way to go in this case?
Thanks for the help!

A: First of all, your error is caused because of retrieving a variable that is not assigned - that just doesn't work. When you edit player_hp, it's not stored anywhere. you are returning it to the function that called it and not assigning it to anything. It just gets lost.
Second of all, you should really indent with 4 spaces (or tabs) - it's much more readable than 2 spaces. Not only for you, but for anyone trying to help too.
And lastly, the proper way to go about this would be to learn about classes. Global variables should never be used in python, only in special cases, or when you are learning, but just skip ahead to the class.
You should create something like
class Player:

    def __init__(self):
        self.hp = 20  # or another starting hp
        self.attack = 3  # or another starting attack
        self.inventory = []

Then you can just create an instance of Player class and pass it to the functions where it's relevant
player1 = Player()
print(player1.hp) # Prints out player's hp
player1.hp -= 5  # Remove 5 hp from the player. Tip: Use method to do this so that it can check if it reaches 0 or max etc.
player1.inventory.append("axe")
print(player1.inventory[0]) #  Prints out axe, learn about lists, or use dictionary, or another class if you want this not to be indexed like a list

A: You asked, "Does the function not save the variable properly?"
In general, Python functions do not save their state. The exception is functions that use the yield statement. If you write a function like this
def save_data(data):
    storage = data

and call it like this
save_data(10)

you will not be able to get the value of storage later. In Python, if you need to save data and retrieve it later, you would normally use classes.
Python classes allow you do do things like this:
class PlayerData(object):
    def __init__(self, hp=0, damage=0):
        self.hp = hp
        self.damage = damage
        self.inventory = list()
        self.max_inventory = 10

    def add_item(self, item):
        if len(self.inventory) < self.max_inventory:
            self.inventory.append(item)

    def hit(self, damage):
        self.hp -= damage
        if self.hp < 0:
            self.hp = 0

    def attack(self, other):
        other.hit(self.damage)

if __name__ == '__main__':
    player1 = PlayerData(20, 5)
    player2 = PlayerData(20, 5)
    player1.attack(player2)
    print player2.hp
    player1.add_item('sword')
    player1.add_item('shield')
    print player1.inventory

Output
15
['sword', 'shield']

This really only scratches the surface of how to use classes. In a more complete implementation, you might have an Item base class. Then you might create Sword and Shield classes that inherit from Item.


text:
Q: How to get the "Authentication" Object with Spring WebFlux? Using SpringMVC and Spring Security I can implement a Controller like this one (in Java):
@RestController
@RequestMapping("/auth")
class AuthController {
    private final AuthService authService;

    AuthController(AuthService authService) {
        this.authService = authService;
    }

    @GetMapping("/roles")
    Collection<String> findRoles(Authentication authentication) {
        final Object principal = authentication.getPrincipal();
        ...;
    }
}

But, how do I basically inject the object of org.springframework.security.core.Authentication
in a handler class (or in a service class) when using Spring WebFlux and Spring Security (incl.
the reactive parts)?

A: There are a lot of examples:
https://github.com/spring-projects/spring-security
This one shows how to get Principal in case of rest controller:
https://github.com/spring-projects/spring-security/blob/b6895e6359e404e4ea101b78eb3135612dfe1769/samples/javaconfig/hellowebflux/src/main/java/sample/HelloUserController.java#L35
And this one shows how to get Principal in case of webflux:
https://github.com/spring-projects/spring-security/blob/b6895e6359e404e4ea101b78eb3135612dfe1769/samples/javaconfig/hellowebfluxfn/src/main/java/sample/HelloUserController.java#L37

A: //@AuthenticationPrincipal Mono<UserLogin> principal
//@AuthenticationPrincipal Mono<Authentication> principal

@GetMapping("/me")
public Mono<Map<String, Object>> current(@AuthenticationPrincipal Mono<Principal> principal) {
    return principal
            .map(user ->
                    Map.of(
                            "name", user.getName(),
                            "roles", AuthorityUtils.authorityListToSet(((Authentication) user)
                                    .getAuthorities())
                    )
            );
}

You can also use :
 ReactiveSecurityContextHolder.getContext()
            .map(m->m.getAuthentication())
            .map(m->m.getPrincipal());


text:
Q: How to use Microsoft.Identity.Web for authorization for Azure.Storage.Blobs? I am using Microsoft.Identity.Web (0.2.3-preview) for OAuth authentication with azure AD. I would like to achieve access to azure blob storage with Azure.Storage.Blobs (12.x).
I managed to find an example with Azure.Storage.Blob (11.x)
string[] scopes = new string[] { "user.read", "https://storage.azure.com/user_impersonation" };
var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
var tokencr = new TokenCredential(accessToken);
var storagecr = new StorageCredentials(tokencr);
var blob = new CloudBlockBlob(new Uri(containerUri),storagecr);

where _tokenAcquisition is Microsoft.Identity.Web.ITokenAcquisition obtained via constructor DI.
With Blobs(ver 12) I would like to use BlobContainerClient(Uri blobContainerUri, Azure.Core.TokenCredential credential, Azure.Storage.Blobs.BlobClientOptions options = default) instead of CloudBlockBlob, but I didn't manage to find any equivalent to Microsoft.Azure.Storage.Auth(v11). The parameter Azure.Core.TokenCredential (TokenCredential parameter) doesn't seem to have any equivalent implementation.
Is it possible to use Microsoft.Identity.Web for authorization for Azure.Storage.Blobs?
Note
It is a research project not a production application.


text:
Q: Retrieving nested JSON array / Objects in Android from a complicated JSON response I have to parse the below nested JSON array's data into my application. I am confused how to get the values out of it.Because it is too complicated The url is "http://gaadiready.com/flight_api/getFlightSearchResults/?key=PPSYrvnMnS&trip_type=domestic&flight_mode=ONE&from=Bangalore/BLR&to=Calicut/CCJ&depart_date=05-06-2015&return_date=06-06-2015&no_adult=1&no_child=0&no_infant=0&cabin_type=E"
The JSON response consist of nested arrays and objects.I am using Volley library functions for parsing the JSON. I want get the values from the response so as to generate a listview. But I did not get the outputs.Anybody help me out for this issue. I am not familiar with nested JSON arrays.
{"tag":"Flight SearchResults","success":"1","xml_filename":"dom_20150527135409.xml",

"data":

[{"depart_from_location":"Bangalore","depart_from_location_code":"BLR","depart_to_location":"Calicut","depart_to_location_code":"CCJ","depart_date":"Fri, 05 June 2015","return_from_location":"Calicut","return_from_location_code":"CCJ","return_to_location":"Bangalore","return_to_location_code":"BLR","return_date":"Sat, 06 June 2015",

"departure_details":[{"flight_id":"arzoo11","flights_count":"2",

"flight_details":

[{"image_filename":"http:\/\/live.arzoo.com\/FlightWS\/image\/AirIndia.gif","air

line_name":"Air India","flight_number":"608","departure_location_code":"BLR","arrival_location_code":"BOM","departure_location":"Bangalore ","departure_time":"21:20","arrival_location":"Mumbai","arrival_time":"23:00","fare_rules":"This fare is Non Refundable Booking Class : T|Cancellation Penalty: All bookings done are subject to cancellation penalty levied by the airlines.
In addition to the airlines cancellation penalty, we charge a service fee of Rs. 50 per passenger for all cancellations.|Date Change Penalty: In addition to the airlines date change penalty, we charge a service fee of Rs. 50 per passenger.|"},{"image_filename":"http:\/\/live.arzoo.com\/FlightWS\/image\/AirIndia.gif","airline_name":"Air India","flight_number":"657","departure_location_code":"BOM","arrival_location_code":"CCJ","departure_location":"Mumbai","departure_time":"10:00","arrival_location":"Calicut","arrival_time":"13:05","fare_rules":"This fare is Non Refundable Booking Class : T|Cancellation Penalty: All bookings done are subject to cancellation penalty levied by the airlines.
In addition to the airlines cancellation penalty, we charge a service fee of Rs. 50 per passenger for all cancellations.|Date Change Penalty: In addition to the airlines date change penalty, we charge a service fee of Rs. 50 per passenger.|"}],

"fare_details":

{"base_fare":"7301","airport_tax":"5365","service_tax":"46","transaction_charge":"0","total":12962,"total_amount":"12962.00"}},

My code that I have tried so far is given below, I am using volley for the parsing
private void json_parser(JSONArray jarray){
  try  {

        flightList=new ArrayList<Flight>();
      for (int i = 0; i < jarray.length(); i++) {

            JSONObject object = jarray.getJSONObject(i);

          JSONArray departure_details=object.getJSONArray("departure_details");
          if(departure_details!=null)
          {
              for(int j=0;j<departure_details.length();j++)
              {
                  JSONObject object2=departure_details.getJSONObject(j);
                  String flight_count=object2.getString("flight_count");

            JSONArray flight_details=object2.getJSONArray("flight_details");
                  if(flight_details!=null)
                  {
                      for(int k=0;k<flight_details.length();k++)
                      {
    JSONObject object3=flight_details.getJSONObject(k);
                          String flight_name=object3.getString("airline_name");
                          String dep_location_code=object3.getString("departure_location_code");
                          String arr_location_code=object3.getString("arrival_location_code");
    String dep_time=object3.getString("departure_time");
                          String arr_time=object3.getString("arrival_time");

          JSONObject fare_details=object.getJSONObject("fare_details");
                          Toast.makeText(getApplicationContext(),object.getString("depart_from_location_code"), Toast.LENGTH_LONG).show();
           flightList.add(new Flight( object.getString("depart_from_location_code"),object.getString("depart_to_location_code"),flight_count,flight_name,object.getString("depart_date"),object.getString("depart_date"),dep_time,arr_time,dep_location_code,arr_location_code,dep_location_code,arr_location_code));

        }}}}}
        list.setAdapter( new FlightListAdapter(ctx, R.layout.flight_list, flightList) );

A: private void json_parser(JSONArray jarray) {
    try {

        ArrayList flightList = new ArrayList<Flight>();
        for (int i = 0; i < jarray.length(); i++) {

            JSONObject object = jarray.getJSONObject(i);

            JSONArray departure_details = object
                    .getJSONArray("departure_details");
            if (departure_details != null) {
                for (int j = 0; j < departure_details.length(); j++) {
                    JSONObject object2 = departure_details.getJSONObject(j);

                    String flight_count = object2
                            .getString("flights_count");

                    JSONObject fare_details = object2
                            .getJSONObject("fare_details");

                    String base_fare, airport_tax, service_tax, transaction_charge, total, total_amount;

                    Log.i("fare_details",
                            "fare_details:" + fare_details.toString());
                    for (int k = 0; k < fare_details.length(); k++) {
                        base_fare = fare_details.getString("base_fare");
                        airport_tax = fare_details.getString("airport_tax");
                        service_tax = fare_details.getString("service_tax");
                        transaction_charge = fare_details
                                .getString("transaction_charge");
                        total = fare_details.getString("total");
                        total_amount = fare_details
                                .getString("total_amount");

                    }

                    JSONArray flight_details = object2
                            .getJSONArray("flight_details");
                    if (flight_details != null) {
                        Log.i("flight_details", "flight_details:"
                                + flight_details.toString());

                        for (int k = 0; k < flight_details.length(); k++) {
                            JSONObject object3 = flight_details
                                    .getJSONObject(k);
                            String flight_name = object3
                                    .getString("airline_name");
                            String dep_location_code = object3
                                    .getString("departure_location_code");
                            String arr_location_code = object3
                                    .getString("arrival_location_code");
                            String dep_time = object3
                                    .getString("departure_time");
                            String arr_time = object3
                                    .getString("arrival_time");

                            flightList
                                    .add(new Flight(
                                            object.getString("depart_from_location_code"),
                                            object.getString("depart_to_location_code"),
                                            flight_count,
                                            flight_name,
                                            object.getString("depart_date"),
                                            object.getString("depart_date"),
                                            dep_time, arr_time,
                                            dep_location_code,
                                            arr_location_code,
                                            dep_location_code,
                                            arr_location_code));
                        }

                    }

                }
            }
        }
        Log.i("array list length", "" + flightList.size());

    } catch (Exception e) {
        e.printStackTrace();
    }

}


text:
Q: Trying to make a histogram with ui.Chart.image.histogram() in GEE I'm trying to make a histogram with the difference of two NDVI images from different dates, but I'm having trouble with the ui.Chart.image.histogram() function when I try to perform with my large asset (https://code.earthengine.google.com/?asset=users/felolillorobles/Araucania_ODEPA_2019_Buffer) to obtain the histogram, equivalent to 46881041 pixels in the region.
The Error is the following:

Error generating chart: Image.reduceRegion: Too many pixels in the region. Found 46881041, but maxPixels allows only 10000000.

The error suggests I set MaxPixels to a limit suitable for my computation, or set BestEffort to true. However, when I do this, I must change my original variable (ee.Image) to a dictionary using a reducer. This throws another error when I try to pass this new reduced variable (ee.Dictionary) as an input to ui.Chart.image.histogram(), because the function expects an ee.Image (like my original variable).
Another way that I've been trying this is with an ee.Reducer.histogram(), which allows me to use my large asset, but then, I don't know how to graph with the values contained in the resulting dictionary. Is possible to pass this dictionary object to an ui.Chart.image.histogram()?
Here is my script, the characters in // are other options that i was trying:
// CALCULO DE DNDVI PARA SENTINEL 2A SR

//Imagen Sentinel 2A en la fecha 1
var IMGSentinel2A= ee.ImageCollection("COPERNICUS/S2")
.filterDate ('2016-10-01', '2017-03-31')
.filterBounds (geometry)
.filterMetadata ("CLOUDY_PIXEL_PERCENTAGE",'Less_Than', 5);
var Sentinel2filtro = ee.Image(IMGSentinel2A.max());
var Sentinel2Clip = Sentinel2filtro.clip (geometry);

//BANDAS FECHA 1
var b2_1 = Sentinel2Clip.select('B2');
var b3_1 = Sentinel2Clip.select('B3');
var b4_1 = Sentinel2Clip.select('B4');
var b5_1 = Sentinel2Clip.select('B5');
var b8_1 = Sentinel2Clip.select('B8');
var b11_1 = Sentinel2Clip.select('B11');
var b12_1 = Sentinel2Clip.select('B12');

//Imagen Sentinel 2A en la fecha 2
var IMGSentinel2A2= ee.ImageCollection("COPERNICUS/S2")
.filterDate ('2018-10-01', '2019-03-31')
.filterBounds (geometry)
.filterMetadata ("CLOUDY_PIXEL_PERCENTAGE",'Less_Than', 5);
// .filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 10));
 var Sentinel2filtro2 = ee.Image(IMGSentinel2A2.median());
 var Sentinel2Clip2 = Sentinel2filtro2.clip (geometry);

//BANDAS FECHA 2
var b2_2 = Sentinel2Clip2.select('B2');
var b3_2 = Sentinel2Clip2.select('B3');
var b4_2 = Sentinel2Clip2.select('B4');
var b5_2 = Sentinel2Clip2.select('B5');
var b8_2 = Sentinel2Clip2.select('B8');
var b11_2 = Sentinel2Clip2.select('B11');
var b12_2 = Sentinel2Clip2.select('B12');

//Normalized differences
var normdif1 = Sentinel2Clip.normalizedDifference(['B8', 'B4']);
var normdif2 = Sentinel2Clip2.normalizedDifference(['B8', 'B4']);
var dndvi = normdif1.subtract(normdif2);
print (dndvi)

//   var hist = dndvi.reduceRegion({
//   reducer: ee.Reducer.histogram(),
//   geometry: geometry.geometry(),
//   scale: 10,
//   bestEffort: true,
// });

var hist = dndvi.reduceRegion({
 reducer: ee.Reducer.mean(),
geometry: geometry.geometry(),
scale: 10,
bestEffort: true,
 });

 print(hist)

 // Pre-define some customization options.

var options = {
  title: 'HISTOGRAMA dNDVI',
  fontSize: 20,
  hAxis: {title: 'banda'},
  vAxis: {title: 'Frecuencia'},
  series: {
    0: {color: 'blue'},
}};
// Make the histogram, set the options.
var histogram = ui.Chart.image.histogram(hist, geometry, 30)
    .setSeriesNames(['dNDVI'])
    .setOptions(options);
    // Display the histogram.
print(histogram);

A: Below is a conceptual example, based on your analysis, for generating histograms by region reduction and charting the results using either ee.Array or ee.FeatureCollection objects. I prefer these methods over charting by image histogram because they are more flexible, and in the case of the ee.FeatureCollection option, the histogram table can be exported as an asset, which can help when in-browser processing times out, allowing you to make histogram charts from very large regions at small scales.
Code Editor script
/**
 * Copyright 2020 Google LLC.
 * SPDX-License-Identifier: Apache-2.0
 */

// Define a region of interest.
var geometry = ee.Geometry.Polygon(
  [[[-73.16191843371962, -37.8098361104156],
    [-73.16191843371962, -39.593041263040206],
    [-71.14043405871962, -39.593041263040206],
    [-71.14043405871962, -37.8098361104156]]], null, false);

// Display the region of interest.
Map.centerObject(geometry);
Map.addLayer(geometry);

// Filter image collection 1 and reduce to max.
var sentinel2a = ee.ImageCollection("COPERNICUS/S2")
  .filterDate('2016-10-01', '2017-03-31')
  .filterBounds(geometry)
  .filterMetadata("CLOUDY_PIXEL_PERCENTAGE",'Less_Than', 5)
  .max();

// Filter image collection 2 and reduce to median.
var sentinel2b = ee.ImageCollection("COPERNICUS/S2")
  .filterDate('2018-10-01', '2019-03-31')
  .filterBounds(geometry)
  .filterMetadata("CLOUDY_PIXEL_PERCENTAGE",'Less_Than', 5)
  .median();

// Calculate difference between two dates of normalized difference (DNDVI).
var normDif1 = sentinel2a.normalizedDifference(['B8', 'B4']);
var normDif2 = sentinel2b.normalizedDifference(['B8', 'B4']);
var dndvi = normDif1.subtract(normDif2);

// Calculate a histogram of DNDVI using a region reduction with the
// `autoHistogram()` reducer. Note that scale is set to 1000 so that the
// operation will not time out while interactive in the Code Editor browser.
// If you have a large region and a small scale, see the below section on
// exporting the result as an asset to avoid time out errors.
var hist = dndvi.reduceRegion({
  reducer: ee.Reducer.autoHistogram(),
  geometry: geometry,
  scale: 1000,
  bestEffort: true,
});

// #############################################################################
// ### HISTOGRAM CHART USING ARRAYS ###
// #############################################################################

// The result of the region reduction by `autoHistogram` is an array. Get the
// array and cast it as such for good measure.
var histArray = ee.Array(hist.get('nd'));

// Subset the values that represent the bottom of the bins and project to
// a single dimension. Result is a 1-D array.
var binBottom = histArray.slice(1, 0, 1).project([0]);

// Subset the values that represent the number of pixels per bin and project to
// a single dimension. Result is a 1-D array.
var nPixels = histArray.slice(1, 1, null).project([0]);

// Chart the two arrays using the `ui.Chart.array.values` function.
var histColumnFromArray = ui.Chart.array.values({
  array:nPixels,
  axis: 0,
  xLabels: binBottom})
  .setChartType('ColumnChart');
print(histColumnFromArray);

// #############################################################################
// ### HISTOGRAM CHART USING A FEATURE COLLECTION ###
// #############################################################################

// Cast the histogram table array as a list.
var histList = histArray.toList();

// Map over the list to create a list of features per bin and set respective
// bin bottom and number of pixels properties.
var featureList = histList.map(function(bin) {
  bin = ee.List(bin);
  var props = {
    binBottom: ee.Number(bin.get(0)),
    nPixels: ee.Number(bin.get(1))
  };
  return ee.Feature(geometry, props);
});

// Convert the feature list to a feature collection.
var featureCol = ee.FeatureCollection(featureList);

// #############################################################################
// OPTIONALLY EXPORT THE FEATURE COLLECTION

// If your region reduction times out in the browser, export the above
// feature collection as an asset. When it completes, start a new script
// that imports it and then chart it using the options following. Here is
// an example of exporting the region as an asset:

Export.table.toAsset({
  collection: featureCol,
  description: 'histogram_table',
  assetId: 'histogram_table'
});

// #############################################################################

// Chart histogram from the constructed feature collection as a line chart.
var histLineFromFc = ui.Chart.feature.byFeature({
  features: featureCol,
  xProperty: 'binBottom',
  yProperties: ['nPixels']})
  .setChartType('LineChart');
print(histLineFromFc);

// Chart histogram from the constructed feature collection as a column chart.
var histColumnFromFc = ui.Chart.feature.byFeature({
  features: featureCol,
  xProperty: 'binBottom',
  yProperties: ['nPixels']})
  .setChartType('ColumnChart');
print(histColumnFromFc);