text:
Q: SQL Server Express and created SSIS package I created with the import tool (SQL Server 2019 Express, SSMS 18.1) some SSIS import packages for testing. Now I want to delete them that they can't be used by accident.
Of course, I know I have no SSIS running, but when the packages are created by the SQL Server Management Studio they must be stored somewhere. How can I delete them?

A:
I can only give the package a name and can't decide where, so I think there is a standard location.

By default, SSIS packages created using the Import/Export wizard are stored within the MSDB database.

To access the stored packages, you should connect to Integration Services from the SQL Server Management Studio.

Then you should see the stored packages within the MSDB directory as shown below.

More information can be found in the following articles:

*

*View packages in SSMS

*How to retrieve information about SSIS packages stored in MSDB Database


text:
Q: Office 2013 display bug I've started getting a really weird bug in Office 2013 - every time I open any program in the suite I get the visual bug seen in the screenshot. The programs work, the problem seems to be purely visual, but I don't even know where to start with troubleshooting it. I reinstalled Office, to no effect. No other application is affected by the bug, and I'm running windows 7.
Has anyone seen anything like it, or have any idea what the issue might be?
Thanks
Wyatt

A: You can try turning off Office's GPU rendering:

*

*First open any Office 2013 program. For example open Word 2013. It'll open in new Start Screen mode. Click on "Blank document" option.

*Now click on "File" menu present in the ribbon and then click on "Options" link given at the end of the left-sidebar.

*It'll open Options window. Click on "Advanced" tab and scroll down a little. Look for following 2 options in "Display" section:
Disable hardware graphics acceleration
Use subpixel positioning to smooth fonts on screen
First option would be unchecked and second option would be checked by default.

*Enable "Disable hardware graphics acceleration" option and click on OK button. Restart the program and it should fix the problem.
source

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set parameter value with CASE WHEN NOT EXISTS always comes out to 0 I have a parameter (@noMatch int output) which I assign a value to based on the CASE found in my stored procedure below:
ALTER PROCEDURE [dbo].[p_trips_non_aggregate_insert]
     @trips u_trips_non_aggregate readonly,
     @rowCount int OUTPUT,
     @noMatch int OUTPUT
WITH RECOMPILE
AS
    BEGIN TRANSACTION
    SET NOCOUNT ON

    INSERT INTO [dbo].[trips_non_aggregate]
        ([LøyvehaverID], [KjøretøyID], [Ordrenummer], [c], [År], [Måned], [Betaling (brutto)], [Betaling (netto)], [LøyvehaverFakturaID], [IsProcessed], [RowIsChecked])

        SELECT DISTINCT
            [LøyvehaverID], [KjøretøyID], [Ordrenummer], [c], [År], [Måned], [Betaling (brutto)], [Betaling (netto)], [LøyvehaverFakturaID], [IsProcessed], [RowIsChecked]
        FROM
            @trips AS o
        WHERE
            [IsProcessed] = '0'
            AND NOT EXISTS (SELECT [Ordrenummer]
                            FROM [dbo].[trips_non_aggregate] AS i
                            WHERE i.[Ordrenummer] = o.[Ordrenummer])

        SET @rowCount = @@ROWCOUNT

        SET @noMatch =
            CASE WHEN NOT EXISTS
                (SELECT [LøyvehaverID]
                    FROM [dbo].[trips_non_aggregate] AS i
                    INNER JOIN [license_holder] AS o ON i.[LøyvehaverID] = o.[Foretaksnavn])
            THEN 1 ELSE 0
        END

    UPDATE [dbo].[trips_non_aggregate]
    SET [Betaling (netto)] = (SELECT [Betaling (brutto)] / ([MVAsats] / 100 + 1)
                              FROM [tblMVAkoder]
                              WHERE [ID] = 'MVAkode2')

    UPDATE [dbo].[trips_non_aggregate]
    SET [RowIsChecked] = (SELECT [RowIsChecked] = 0)

    COMMIT TRANSACTION

So that when I insert to my database, I am able to flag any entry into ColumnA that does not already exist in ColumnB. But when I test with fake data, the outcome is always 0.
Why could that be?
This is how I check its value in C#:
if (Convert.ToInt32(cmd.Parameters["@noMatch"].Value) == 1)
{
    // do something
}

A: It looks like you're doing some kind of preflight checking so that you don't insert any data at all from the batch, if one or more incoming u_trips_non_agg records don't have a Licence Holder. We can check before we do the insert:
ALTER PROCEDURE [dbo].[p_trips_non_aggregate_insert]
     @trips u_trips_non_aggregate readonly,
     @rowCount int OUTPUT
WITH RECOMPILE
AS

    IF EXISTS (
      SELECT null FROM @trips t
      WHERE NOT EXISTS (
        SELECT null FROM license_holder lh WHERE t.[LøyvehaverID] = lh.[Foretaksnavn]
      )
    )
      THROW 51000, 'At least one of the records being inserted does not have a related licence holder record', 1;

    BEGIN TRANSACTION
    SET NOCOUNT ON

    INSERT INTO [dbo].[trips_non_aggregate]
        ([LøyvehaverID], [KjøretøyID], [Ordrenummer], [c], [År], [Måned], [Betaling (brutto)], [Betaling (netto)], [LøyvehaverFakturaID], [IsProcessed], [RowIsChecked])

        SELECT DISTINCT
            [LøyvehaverID], [KjøretøyID], [Ordrenummer], [c], [År], [Måned], [Betaling (brutto)], [Betaling (netto)], [LøyvehaverFakturaID], [IsProcessed], [RowIsChecked]
        FROM
            @trips AS o
        WHERE
            [IsProcessed] = '0'
            AND NOT EXISTS (SELECT [Ordrenummer]
                            FROM [dbo].[trips_non_aggregate] AS i
                            WHERE i.[Ordrenummer] = o.[Ordrenummer])

        SET @rowCount = @@ROWCOUNT

        SET @noMatch =
            CASE WHEN NOT EXISTS
                (SELECT [LøyvehaverID]
                    FROM [dbo].[trips_non_aggregate] AS i
                    INNER JOIN [license_holder] AS o ON i.[LøyvehaverID] = o.[Foretaksnavn])
            THEN 1 ELSE 0
        END

    UPDATE [dbo].[trips_non_aggregate]
    SET [Betaling (netto)] = (SELECT [Betaling (brutto)] / ([MVAsats] / 100 + 1)
                              FROM [tblMVAkoder]
                              WHERE [ID] = 'MVAkode2')

    UPDATE [dbo].[trips_non_aggregate]
    SET [RowIsChecked] = (SELECT [RowIsChecked] = 0)

    COMMIT TRANSACTION

An EXISTS returns true or false depending on whether the query returns any row. It doesn't matter what data is selected; all EXISTS cares about is whether there is any row or not. You can conceive that it stops as soon as it finds one, so it can be quite optimal to not run a massive million rows query just to know if there is one row or not
We actually use it twice, an inner and an outer:
  SELECT null FROM @trips t
  WHERE NOT EXISTS (
    SELECT null FROM license_holder lh WHERE t.[LøyvehaverID] = lh.[Foretaksnavn]
  )

The first one to run conceptually in the inner one:
SELECT null FROM license_holder lh WHERE t.[LøyvehaverID] = lh.[Foretaksnavn]

This is coordinated with the outer one, and you could conceive it working like:
For `t.[LøyvehaverID]` = 1
SELECT null FROM license_holder lh WHERE 1 = lh.[Foretaksnavn]

For `t.[LøyvehaverID]` = 2
SELECT null FROM license_holder lh WHERE 2 = lh.[Foretaksnavn]

And so on; it's basically, for every row in the outer table @trips checking if there is a row in in licence_holder such that @trips.[LøyvehaverID] equals licence_holder.[Foretaksnavn].
If there is a row, then null is returned. If there is not a row, then 0 rows are returns, and that's what NOT EXISTS picks up on. In other words, this structure:
  FROM @trips t
  WHERE NOT EXISTS (
    SELECT null FROM license_holder lh WHERE t.[LøyvehaverID] = lh.[Foretaksnavn]
  )

will find all @trips rows that do not have a matching licence_holder row

All that is wrapped in another EXISTS, which effectively stops looking as soon as at least one case of "a @trips row that doesn't have a licence_holder row" is found
In total this:
EXISTS (
  SELECT null FROM @trips t
  WHERE NOT EXISTS (
    SELECT null FROM license_holder lh WHERE t.[LøyvehaverID] = lh.[Foretaksnavn]
  )
)

means:
there exists a row in @trips where there does not exist a matching row in licence holder

And then we key off of that to throw an exception if it is the case

A: Is parameter direction configured like
    cmd.Parameters.Add("@noMatch", SqlDbType.Int);
    cmd.Parameters["@noMatch"].Direction = ParameterDirection.Output;


text:
Q: Raymarching fractals I try to render a fractal according to this tutorial: http://blog.hvidtfeldts.net/index.php/2011/08/distance-estimated-3d-fractals-iii-folding-space/comment-page-1/#comment-20302 the one under "A REAL FRACTAL". The problem is, that my ray is missing the fractal, all I get is a black image. I think my rays miss the fractal. My question is:
What sensible defaults should I use for "Scale" and "Iteration"?
Code for generating the fractals:
distanceFromPoint(vec3 z) {
  vec3 a1 = vec3(1,1,1);
  vec3 a2 = vec3(-1,-1,1);
  vec3 a3 = vec3(1,-1,-1);
  vec3 a4 = vec3(-1,1,-1);
  vec3 c;
  int n = 0;
  float dist, d;
  while (n < Iterations) {
   c = a1; dist = length(z-a1);
   d = length(z-a2); if (d < dist) { c = a2; dist=d; }
   d = length(z-a3); if (d < dist) { c = a3; dist=d; }
   d = length(z-a4); if (d < dist) { c = a4; dist=d; }
   z = Scale*z-c*(Scale-1.0);
   n++;
  }
return (length(z) ) * pow(Scale, -float(n));

Is the construction of the rays correct? Code of my "main" Method:
vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / u_ws.xy;
p.x *= u_aspect;

vec3 ro = 1.1*vec3(2.5*sin(0.25*ctime),1.0+1.0*cos(ctime*.13),2.5*cos(0.25*ctime));
vec3 ww = normalize(vec3(0.0) - ro);
vec3 uu = normalize(cross( vec3(0.0,1.0,0.0), ww ));
vec3 vv = normalize(cross(ww,uu));
vec3 rd = normalize( p.x*uu + p.y*vv + 2.5*ww );

float totalDistance = 0.0;
vec4 color = vec4(trace(ro, rd));

A: When ray-marching, you should avoid functions like sin / cos because it may become quickly very expensive.
If not sure about how to implement your rays, you can check Inigo Quilez work (very neat):
http://www.iquilezles.org/www/articles/terrainmarching/terrainmarching.htm
Also worth checking his other samples :
http://www.iquilezles.org/www/index.htm
Looks like your are trying Mikael Hvidtfeldt Christensen's tutorials, have you checked his great shader editor Fragmentarium ? (many samples too)
It seems that your tutorial page is showing snaps from Fragmentarium.
Ooops, this post looks old..


text:
Q: Understanding the PBBS Adjacency Graph format. I'm trying to figure out a way to convert an Edge list representation i.e. Edge(start, end), of a graph, and the one described here and here.
I've tried figuring it out on my own, but the documentation is incredibly terse. I mainly don't understand what the numerical values are counted from:
Is the offset the number of lines from where the offset is written? Is it just the line number of the beginning of the adjacency list? If I subtract the neighbouring offsets will I get the size of the contiguous block? Is it off by one?
Too many questions that could have been cleared up with an example, but unfortunately everything that uses this suite never actually explains how it's supposed to be interpreted.
e.g. if I had a directed graph that looked like this
Edge(1,2), Edge (2,4), Edge(3,4), Edge(1,3), ..., Edge(i,j)

how would it be represented in the Adjacency Graph format of PBBS.
I understand that this is very specific, and that it probably really is simple to understand, but I'm having trouble personally. I can't understand it. If anyone could help, I'd much appreciate it.

A: I have never used this format, but it's not difficult to understand with a example.

Here is the ordered list of all out edges of the graph shown above:
0-6  line 0
1-5  line 1
2-4  line 2
2-6  line 3
3-0  line 4
3-6  line 5
3-7  line 6
5-4  line 7

Out-edge list for vertex
0 starts at line 0, mark it as [0, 1)
1 starts at line 1, mark it as [1, 2)
2 starts at line 2, mark it as [2, 4)
3 starts at line 4, mark it as [4, 7)
4 starts at line 7, mark it as [7, 7)
5 starts at line 7, mark it as [7, 8)
6 starts at line 8, mark it as [8, 8)
7 starts at line 8, mark it as [8, 8)

According to the format description,

The offset for a vertex i refers to the location of the start of a contiguous block of out edges for vertex i in the sequence of edges. The block continues until the offset of the next vertex, or the end if i is the last vertex.

It should be written as,
0
1
2
4
7
7
8
8

0-6
1-5
2-4
2-6
3-0
3-7
5-4

As how to convert edge-list graph to adjacency list graph, you can sort the graph by comparing edges nodes. Assume e1 = (source1, target1), e2 = (source2, target2), e1 < e2 if
source1 < souce2
or
source1 == source2 and target1 < target2


text:
Q: WooCommerce add a custom fee using ajax to cart totals on checkout page I am trying make it when user changes the Shipping address select dropdown it dynamically add a fee to cart totals using ajax.I could able to to get the value but when select a another state it wont update the totals.
My ajax request:

jQuery(document).ready(function () {
    jQuery('#shipping_state').change(function () {
        var data = {
            action: 'woocommerce_custom_fee',
            security: wc_checkout_params.update_order_review_nonce,
            add_order_fee: 'state',
            post_data: jQuery('form.checkout').serialize()
        };
        jQuery.ajax({
            type: 'POST',
            url: wc_checkout_params.ajax_url,
            data: data,
            success: function (code) {
                var result = '';
                result = jQuery.parseJSON(code);
                if (result.result === 'success') {

                    jQuery('body').trigger('update_checkout');
                }
            },
            dataType: 'html'
        });
        return false;
    });
})

And in functions.php

add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');

function woo_add_cart_fee() {
global $woocommerce;
$destsuburb = $woocommerce->customer->get_shipping_state();

/*Then I use $destsuburb as a variable to API and get a shipping cost returning $shipping_cost*/

$woocommerce->cart->add_fee('Shipping and Handling:', $shipping_cost);
}

I am getting different Shipping cost according to the State,but its not changing the front end value through add_fee()

A: Finally I found a solution using a session variable to store the Ajax value and add_fee()
My ajax request:

jQuery(document).ready(function () {

    jQuery('#State').click(function () {
        if (jQuery('#ship-to-different-address-checkbox').is(':checked')) {
            var state = jQuery('#shipping_state').val();
            var post_code = jQuery('#shipping_postcode').val();
        } else {
            var state = jQuery('#billing_state').val();
            var post_code = jQuery('#billing_postcode').val();

        }
        console.log(state + post_code);
        var data = {
            action: 'woocommerce_apply_state',
            security: wc_checkout_params.apply_state_nonce,
            state: state,
            post_code: post_code
        };

        jQuery.ajax({
            type: 'POST',
            url: wc_checkout_params.ajax_url,
            data: data,
            success: function (code) {
                console.log(code);
//                jQuery('.woocommerce-error, .woocommerce-message').remove();

                if (code === '0') {
//                    $form.before(code);
                    jQuery('body').trigger('update_checkout');
                }
            },
            dataType: 'html'
        });

        return false;
    });

});

And in functions.php

wp_enqueue_script('neemo_state', get_template_directory_uri() . '/js/state_test.js', array('jquery'));
wp_localize_script('neemo_state', 'wc_checkout_params', array('ajaxurl' => admin_url('admin-ajax.php')));

add_action('wp_ajax_woocommerce_apply_state', 'calculate', 10);
add_action('wp_ajax_nopriv_woocommerce_apply_state', 'calculate', 10);

function calculate() {
    if (isset($_POST['state'])) {
        global $woocommerce;
        $weight = WC()->cart->cart_contents_weight;
        $state = $_POST['state'];
        if ($state === "VIC") {
            $val = 1;
        } else {
            $val = 2;
        }
        session_start();
        $_SESSION['val'] = $val;
    }
}

add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');

function woo_add_cart_fee() {
    session_start();
    $extracost = $_SESSION['val'];
    WC()->cart->add_fee('Shipping & Handling:', $extracost);
}

A: I had to code for accepting donation just before checkout and adding that donation amount to the cart as a fee - and to provide flexibility for user to change the donation amount any number of times before proceeding to pay. I used the following code and it worked so well. I had Donation amount and a donateNow button - <input type="button" id="donateNowBtn" value="Donate Now!"
code in function.php
add_action( 'wp_footer', 'woocommerce_click_donate_button', 80 );
function woocommerce_click_donate_button() {
    if (is_checkout()) {
    ?>
    <script type="text/javascript">
    jQuery( document ).ready(function( $ ) {
        $('#donateNowBtn').click(function(){
            jQuery('body').trigger('update_checkout');
        });
    });
    </script>
    <?php
    }
}

add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_fee( $cart ){
        if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }

    if (isset($post_data['donation_amount'])) {
        $donation_amount = $post_data['donation_amount'] ;
        WC()->cart->add_fee( 'Donation Amount', $donation_amount );
    }

}


text: Q: Create Block that changes textures like End Portal Frame I'm trying to create my first Mod in Minecraft. I already got an ore block, a brick block and an item that I get when breaking the ore block. No I wanted to go further and create a block that changes its texture when rightclicked with an item. Like the end portal frame where the "eye of ender gets inserted into the frame". At first I don't want to try it with 3D textures. only a texture switch. After this works I'll try to make 3D textures, but I haven't found any good tutorial for any of these things


text:
Q: Json String that doesn't want to be deserialized I am stuck on a json deserialization, it seems that there's something I can't catch on this json :
{
    "success" : true,
    "message" : "",
    "result" : [{
            "Currency" : "DOGE",
            "Balance" : 0.00000000,
            "Available" : 0.00000000,
            "Pending" : 0.00000000,
            "CryptoAddress" : "DLxcEt3AatMyr2NTatzjsfHNoB9NT62HiF",
            "Requested" : false,
            "Uuid" : null

        }, {
            "Currency" : "BTC",
            "Balance" : 14.21549076,
            "Available" : 14.21549076,
            "Pending" : 0.00000000,
            "CryptoAddress" : "1Mrcdr6715hjda34pdXuLqXcju6qgwHA31",
            "Requested" : false,
            "Uuid" : null
        }
    ]
}

Here is the code I am trying :
       if (stream == null) return account;
        var re = new StreamReader(stream);
        var json = re.ReadToEnd();
        var jobj = (JObject)JsonConvert.DeserializeObject(json);
        var items = jobj.Children()
            .Cast<JProperty>()
            .Select(j => new
            {
                ID = j.Name,
                Other = (string)j.Value["Currency"]
            })
            .ToList();

But unfortunately, nothing happens with this code, and I'm quite stuck as to why. After searching around here, and trying several other solutions found on similar thread, this one is the closest I could get to deseraliaze my string.
I have two class I wish to fill in with this json :
public class AccountCurrencies
{
    public string Jsonid { get; set; }
    public string Currency { get; set; }
    public double Balance { get; set; }
    public double Available { get; set; }
    public double Pending { get; set; }
    public string CryptoAddress { get; set; }
    public bool Requested { get; set; }
    public object Uuid { get; set; }
}

public class AccountWrapper
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public List<AccountCurrencies> AccountAllCurrencies  { get; set; }
}

A: You are missing two things here. Firstly to get the Json into your class structure is a single line of code:
var yourObject = JsonConvert.DeserializeObject<AccountWrapper>(json);

Secondly, you need to tell the serialiser the the AccountAllCurrencies property is called "result" in the Json data. To do this, use the JsonProperty attribute:
public class AccountWrapper
{
    public bool Success { get; set; }
    public string Message { get; set; }

    //Add this line
    [JsonProperty("result")]
    public List<AccountCurrencies> AccountAllCurrencies  { get; set; }
}


text:
Q: Copy behavior of UITabBarController Is it possible to copy behavior of UITabBarController with the code bellow?
What I am trying to do is to have a "drawer menu" to work as a UITabBarController. Each time you press any of the menu items the selected VC for that menu item will become the new root VC and the navigation stack will reset making that VC becoming the 1st VC in stack.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let AccountVc = storyboard.instantiateViewControllerWithIdentifier("AccountVc")
        let navigationController = self.view.window?.rootViewController as! UINavigationController

        //Remove both login scene and menu scene
        self.presentingViewController!.presentingViewController!.dismissViewControllerAnimated(false) { () -> Void in
            navigationController.setViewControllers([AccountVc], animated: false)
        }
    })

The code above works, in this case it removes the MenuVC together with the loginVC and then resets the navigation setting AccountVC to be the new root.
Is there any better way to do this?


text:
Q: How Best To Implement ViewModel( in AndroidX) So Data Survives Configuration Changes I am trying to implement a ViewModel architecture for a RecyclerView in AndroidX, following the example as stated in enter link description here and enter link description here. Items in the recyclerView get selected on position clicked, but for some reason, the selected item de-select and revert to default after the device is rotated and configuration changed. I know there have been answers for questions like this in the past, but all I have seen are either not directly applicable in my case or are simply for deprecated cases.
CAN SOMEONE PLEASE TELL ME WHAT I AM DOING WRONG!
Below are snippets from my Code:
Dependencies added
dependencies {

def lifecycle_version = "2.2.0"

// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"

// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"

// Saved state module for ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

// Annotation processor
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha02'

}
Repository Class:
public class TopicRepository {
private Application application;
private SharedPreferences sharedPreferences;
private ArrayList<RootTopic> topicGroupList;
private MutableLiveData<ArrayList<RootTopic>>topicGroupMLD;

public TopicRepository(Application application) {
    this.application = application;

}

public LiveData<ArrayList<RootTopic>> getRootTopicLD(String subject){
    if (topicGroupMLD == null){
        topicGroupMLD = new MutableLiveData<ArrayList<RootTopic>>();
        generateTopicGroup(subject);
    }
        return topicGroupMLD;
}

private void generateTopicGroup(final String subject){
    Log.d(TAG, "generateTopicGroup: CALLED");
    isRequestingMLD.postValue(true);
    final String subjectTopicGroupList = subject + "TopicGroupList";

    sharedPreferences = application.getSharedPreferences(AppConstant.Constants.PACKAGE_NAME, Context.MODE_PRIVATE);
    String serializedTopicGroup = sharedPreferences.getString(subjectTopicGroupList, null);
     if (serializedTopicGroup != null){

         Gson gson = new Gson();
         Type type = new TypeToken<ArrayList<RootTopic>>(){}.getType();
         topicGroupList = gson.fromJson(serializedTopicGroup, type);
         topicGroupMLD.postValue(topicGroupList);

     }else {//       - Not saved in SP

         Log.d(TAG, "getTopicGroup: NOT IN SP");
         new ActiveConnectionCheck(new ActiveConnectionCheck.Consumer() {
             @Override
             public void accept(Boolean internet) {
                 Log.d(TAG, "accept: CHECKED INTERNET");
                 if (internet){
                     Log.d(TAG, "accept: INTERNET CONNECTION = TRUE");
                     internetCheckMLD.postValue(AppConstant.Constants.IS_INTERNET_REQUEST_SUCCESS);

                     FirebaseFirestore fbFStore = FirebaseFirestore.getInstance();
                     CollectionReference lectureRef = fbFStore.collection(subject);
                     lectureRef.orderBy(AppConstant.Constants.POSITION, Query.Direction.ASCENDING)
                             .get().addOnSuccessListener(
                             new OnSuccessListener<QuerySnapshot>() {
                                 @Override
                                 public void onSuccess(QuerySnapshot queryDocumentSnapshots) {

                                     ArrayList<Topic>topicList = new ArrayList<>();
                                     ArrayList<String> rootTitleList = new ArrayList<>();

                                     for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots){
                                         Topic topic = snapshot.toObject(Topic.class);
                                         topicList.add(topic);
                                     }

                                     Log.d(TAG, "onSuccess: TopicListSize = " + topicList.size());

                                     for (Topic topic : topicList){
                                         String rootTopicString = topic.getRootTopic();
                                         if (!rootTitleList.contains(rootTopicString)){
                                             rootTitleList.add(rootTopicString);
                                         }
                                     }

                                     Log.d(TAG, "onSuccess: RootTitleListSize = " + rootTitleList.size());

                                    for (int x = 0; x < rootTitleList.size(); x ++){
                                        RootTopic rootTopic = new RootTopic(rootTitleList.get(x), new ArrayList<Topic>());
                                        topicGroupList = new ArrayList<>();
                                        topicGroupList.add(rootTopic);
                                    }

                                     for (int e = 0; e < topicList.size(); e++){
                                         addTopicToGroup(topicGroupList, topicList.get(e));
                                     }

                                     topicGroupMLD.postValue(topicGroupList);
                                     Gson gson = new Gson();
                                     String serializedTopicGroup = gson.toJson(topicGroupList);
                                     sharedPreferences.edit().putString(subjectTopicGroupList, serializedTopicGroup).apply();

                                     Log.d(TAG, "onSuccess: TOPICGROUPSIZE = " + topicGroupList.size());
                                     Log.d(TAG, "onSuccess: SERIALIZED GROUP = " + serializedTopicGroup);
                                     isRequestingMLD.postValue(false);

                                 }
                             }
                     ).addOnFailureListener(
                             new OnFailureListener() {
                                 @Override
                                 public void onFailure(@NonNull Exception e) {
                                     isRequestingMLD.postValue(false);
                                     Log.d(TAG, "onFailure: FAILED TO GET TOPICLIST e = " + e.toString());
                                 }
                             }
                     );

                 }else {
                     internetCheckMLD.postValue(AppConstant.Constants.IS_INTERNET_REQUEST_FAIL);
                     Log.d(TAG, "accept: InternetCONECTION = " + false);
                 }
             }
         });

     }

}

private void addTopicToGroup(ArrayList<RootTopic>rootGroup, Topic topic){
    for (int x = 0; x < rootGroup.size(); x++){
        RootTopic rootTopic = rootGroup.get(x);
        if (rootTopic.getRootTopicName().equals(topic.getRootTopic())){
            rootTopic.getTopicGroup().add(topic);
        }
    }
}

}
My ViewModel class
public class LectureViewModel extends AndroidViewModel {

public static final String TAG = AppConstant.Constants.GEN_TAG + ":LectureVM";

private Application application;
private TopicRepository topicRepository;
private ArrayList<RootTopic> topicGroupList;

public LectureViewModel(@NonNull Application application) {
    super(application);
    this.application = application;
    topicRepository = new TopicRepository(application);

}

public LiveData<ArrayList<RootTopic>> getRootTopicListLD(String subject){

    return topicRepository.getRootTopicLD(subject);
}

}
Activity Implementing ViewModel
public class LectureRoomActivity extends AppCompatActivity {

public static final String TAG = AppConstant.Constants.GEN_TAG + " LecRoom";
private LectureViewModel lectureRoomVM;
private String subject;
private RecyclerView mainRecyclerView;

private RootTopicAdapter rootTopicAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lecture_room);

    Intent intent = getIntent();
    subject = intent.getStringExtra(AppConstant.Constants.SUBJECT);

    mainRecyclerView = findViewById(R.id.recyclerView);

    downloadVM = new ViewModelProvider(this).get(DownloadLectureViewModel.class);
    lectureRoomVM = new ViewModelProvider(this).get(LectureViewModel.class);
    lectureRoomVM.getRootTopicListLD(subject).observe(
            this,
            new Observer<ArrayList<RootTopic>>() {
        @Override
        public void onChanged(ArrayList<RootTopic> rootTopics) {
            if (rootTopics != null){
                currentTopic = lectureRoomVM.getCursorTopic(subject, rootTopics);
                setUpRec(rootTopics, currentTopic);
            }
        }
    });

}

private void setUpRec( ArrayList<RootTopic>topicGroup, CursorTopic currentTopic){
     rootTopicAdapter = new RootTopicAdapter(topicGroup,
            new ArrayList<String>(), currentTopic.getParentPosition(),
            currentTopic.getCursorPosition());

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(
            this, RecyclerView.VERTICAL,false);

    mainRecyclerView.setHasFixedSize(true);
    mainRecyclerView.setLayoutManager(linearLayoutManager);
    mainRecyclerView.setAdapter(rootTopicAdapter);

    Log.d(TAG, "setUpRec: SETTING REC");
}

}

A: For saving and restoring UI related data you better use savedInstanceState Bundle to survive the last state. To achive this you simply override two methods in you UI activity. See the sample code snippet below.
In your RootTopicAdapter
// Add this where you detect the item click, probably in your adaptor class
private int lastRecyclerViewIndex; // define the variable to hold the last index
...

@Override
public void onClick(View v) {
    lastRecyclerViewIndex = getLayoutPosition();
}

public int getLastIndex() {
    return lastRecyclerViewIndex;
}

In your view model class
public class LectureViewModel extends AndroidViewModel {

    public static final String TAG = AppConstant.Constants.GEN_TAG + ":LectureVM";

    private Application application;
    private TopicRepository topicRepository;
    private ArrayList<RootTopic> topicGroupList;
    public boolean mustRestore; // Is there any data to restore
    public int lasIndexSelected;

    public LectureViewModel(@NonNull Application application) {
        super(application);
        this.application = application;
        topicRepository = new TopicRepository(application);

    }

    public LiveData<ArrayList<RootTopic>> getRootTopicListLD(String subject){

        return topicRepository.getRootTopicLD(subject);
    }
}

In you UI activity which uses the RecyclerView
public class LectureRoomActivity extends AppCompatActivity {
    ...
    private LectureViewModel lectureRoomVM;
    ...
    private RecyclerView mainRecyclerView;

    private RootTopicAdapter rootTopicAdapter;

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lecture_room);

        Intent intent = getIntent();
        subject = intent.getStringExtra(AppConstant.Constants.SUBJECT);

        mainRecyclerView = findViewById(R.id.recyclerView);

        downloadVM = new ViewModelProvider(this).get(DownloadLectureViewModel.class);
        lectureRoomVM = new ViewModelProvider(this).get(LectureViewModel.class);
        lectureRoomVM.getRootTopicListLD(subject).observe(
                this,
                new Observer<ArrayList<RootTopic>>() {
            @Override
            public void onChanged(ArrayList<RootTopic> rootTopics) {
                if (rootTopics != null){
                    currentTopic = lectureRoomVM.getCursorTopic(subject, rootTopics);
                    setUpRec(rootTopics, currentTopic);
                    // Exactly here, after setting up the data get your index for example
                    if(lectureRoomVM.mustRestore){
                        // Check the item count in the adaptor to avoid crashes
                        if(mainRecyclerView.getAdapter().getItemCount >= lastRecyclerViewIndex){
                            mainRecyclerView.findViewHolderForAdapterPosition(lastRecyclerViewIndex).itemView.performClick();
                        }
                        // After the restoration set the mustRestore to false
                        lectureRoomVM.mustRestore = false;
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(E, "onDestroy");
        /*
         * Here just set the mustRestore to true in order to be able to restore in onCreate method.
         * If the application itself is not destroyed your data will still be live in the
         * memory thanks to the ViewModel's life cycle awarness.
         */
        lectureRoomVM.mustRestore = true;
    }
}

There you go. Try this logic carefully without bugs. Then I think you will achive what you want to get.


text:
Q: Receber o valor de uma variável de um input e comparar com uma predefinida pra gerar um alert e redirecionar Bom dia, eu sou novo com React Native e estou tentando comparar o valor de uma variável que recebi através de um Textinput com uma já predefinida para gerar um alert e me redirecionar pra outra screen, só que não consigo fazer as comparações funcionar e muito menos a variavel receber o valor para pular de tela ou não, poderiam me dar uma força?
Peguei o return pra retomar o valor, mas não consigo comparar as variávels login-login1 e senha-senha1 nele.
import React, {useState} from 'react';
import { Sucess } from './src/screens/Sucess';
import { Denied } from './src/screens/Denied';

export default function App(){

  const [login1,setlogin1] = useState('');
  const [senha1,setsenha1] = useState('');

  const ConfereSenha = () => {
    let login = "test";
    let senha = "1234";

    return(
      if(login1 != login && senha1 != senha){
        alert("Senha incorreta")
        <Denied />
      } else {
        alert("Acesso liberado")
        <Sucess />
      })
  }

<TextInput secureTextEntry={true} placeholder='Login' onChangeText={(login1)=>setlogin1(login1)} maxLength={10}></TextInput>

<TextInput secureTextEntry={true} onChangeText={(senha1)=>setsenha1(senha1)} maxLength={10}

<TouchableOpacity style={styles.botaolog} onPress={ConfereSenha}>ENTRAR</TouchableOpacity>

A: Bom dia Eder, tudo bem? No react a expressão:
return(
  if(login1 != login && senha1 != senha){
    alert("Senha incorreta")
    <Denied />
  } else {
    alert("Acesso liberado")
    <Sucess />
  }
)

É incorreta. Acredito que você esteja utilizando JSX, então você poderia fazer
if(login1 != login && senha1 != senha){
  alert("Senha incorreta")
} else {
  alert("Acesso liberado")
}

return(
  {login1 != login && senha1 != senha ? <Denied /> : <Sucess />}
)

Estes 3 elementos devem estar dentro do retorno do render do componente App também.

<TextInput secureTextEntry={true} placeholder='Login' onChangeText={(login1)=>setlogin1(login1)} maxLength={10}></TextInput>

<TextInput secureTextEntry={true} onChangeText={(senha1)=>setsenha1(senha1)} maxLength={10}

<TouchableOpacity style={styles.botaolog} onPress={ConfereSenha}>ENTRAR</TouchableOpacity>

Entretanto, mesmo com as correções, não irá funcionar da maneira que você espera. Seu código possui um conjunto de outros erros. Te aconselharia a olhar a documentação do React de forma que você conseguisse corrigir os erros de  lógica e JSX.


text:
Q: How to store search result? I am working on my personal site, where I want to store my customers recent search result limited to that particular session.
I am using PHP platform and Javascripts.
Here is an example of what I am exactly looking at :
It stores your previously searched domain name for that particular session so that user can make decision by comparing those results.
Thanks.
EDIT- Well Thanks for all of your answers and suggestions.
But If you have noticed
above example
It looks like some kind of script loading a new content on the same page without refreshing it and keeping previous search content <div> as it is.
How to achieve this using javascripts or some sort of div layer ????

A: UPDATE START
This example uses page reload. If you want to do it without page reload, you can but you'll have to use AJAX to load new search results. But then, it's not a PHP question. I suggest looking at jquery library, as it makes it easy. Tutorials: http://docs.jquery.com/Tutorials and e.g. this one ( http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax ).
When loading data via AJAX, the page rendering result (in my example search.php) should return only HTML for results part, not whole HTML page. This is generally a first part of my tutorial (without session).
But I really think that AJAX in here is not really needed. Session is more reliable and allows access to your page from older / mobile browsers where not always JS works correctly.
UPDATE END
Ok then. Let's try the simple tutorial then. Sorry if too simple, but I don't know your exact level.
PHP has mechanism called sessions. In reality they are just bytes stored on server. Server knows which session is for each client by reading session cookie from client browser.
Not every page uses sessions (not every page needs it, and session uses server space, even if only temporarily), session is not enabled by default. To turn on session you use command
<?php session_start(); ?>

In most cases this is either run by PHP framework you use, or put near the top of your site. Session is definitely needed if you want to authenticate user somehow. Or in your case :)
To access session you can use superglobal $_SESSION variable (superglobal means that you can access it anywhere). It's an array, so session element will be e.g. $_SESSION['search'] etc.
As example, let's assume that your page looks like that
<html>
...
<form action="search.php" method="post">
Search: <input type="text" name="searchQuery" />
<input type="submit" value="Search" />
</form>
...
</html>

this very form will send user search to file named search.php. It can be the same file where the form resides - in simplest case when you put both your code and HTML in one file. Beginners often use this schema, although it's not advisable as result is a mess and hard to further change.
In search.php then, you'll use similar code:
<?php
if (!empty($_POST['searchQuery'])) //we have a new search
{
  $result = do_search($_POST['searchQuery']);
}
?>

Then, somewhere below you'll display your search result ($result variable). do_search() function is your search mechanism, I guess you have it somewhere. You may have it not 'wrapped' in a function, then I advise to create it like that, it's much more useful.
function do_search($searchQuery)
{
  ...
  return $result;
}

mind it, the above code doesn't use sessions yet. Let's add saving previous search results in session. The code may then look like that:
<?php
session_start(); //Starting session

//let's create session variable used to store results
if (!isset($_SESSION['searches']))
  $_SESSION['searches'] = array();

if (!empty($_POST['searchQuery'])) //we have a new search
{
  if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value, delete previous result from sesion
  {
    unset($_SESSION['searches'][$_POST['searchQuery']]);
  }
  $result = do_search($_POST['searchQuery']);
  //Let's add new search on the begining of session array to make iterations easier.
  $result = array($_POST['searchQuery'] => $result); //convert result to same format as session table
  $_SESSION['searches'] = array_merge($result, $_SESSION['searches']);
}
?>

In display you'll now not iterate on $result variable as before, but instead you will do something like
foreach ($_SESSION['searches'] as $query => $result)
{
  ...//display of single result
}

I haven't tested following code and it's not a full program. Parts to display result and to do actual search are not described but I guess you have them already prepared. Also, this is only one possible approach of countless possibilities. But I hope this helps :)
Possible modification - now I always perform search, even if user already searched on this term. You may want to receive the result from cache without second search. Then the code will look like
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value
{
  $result = $_SESSION['searches'][$_POST['searchQuery']];
  unset($_SESSION['searches'][$_POST['searchQuery']]);
}
else
{
  $result = do_search($_POST['searchQuery']);
}

For more in-depth information about sessions and some other constructs used in my example I suggest PHP manual
http://pl.php.net/manual/en/book.session.php
and various tutorials over the network. Or you can add a comment here :)

A: Put this code near the beginning of your script(s):
if (!isset($_SESSION['previous_searches']) || !is_array($_SESSION['previous_searches'])) {
  $_SESSION['previous_searches'] = array();
}

[edit]
This code snippet checks if if there is already an array with prevous searches and if not it will be created.
[/edit]
Then when the user hits the search page put this code in the receiving script of the search:
$_SESSION['previous_searches'][] = $_GET['what_ever_your_search_value_might_be'];

[edit]
This code snippet adds the current search value to the and of the array with previous search values
[/edit]
Now you have all previous search values in $_SESSION['previous_searches']

A: If your website is a web application where you never reload the page nor change the page, you can keep it JavaScript in a global store (declare at top level something like var StoredSearch = []; and use it). If not, then use $_SESSION to store this and AJAX to save/load searches from JavaScript to PHP.


text:
Q: how to get 10 lines below from a line in text file in c# I am reading a huge text file as shown below.What now wants is if i reach a particular word say test: here ,i will push values in to database from that line and out of which one value comes by concatenating values from 10 succeeding line.So  i want to get 10 succeeding lines and store it in to memory by using File. Readalllines or any other mechanism.How would i achieve it.As of now i am loading entire text file in to File.Readalllines which makes application very slow.
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
    string s = String.Empty;
    while ((s = sr.ReadLine()) != null)
    {
        if (s.Contains("test:"))
        {
            //
        }
    }
}

EDIT
i was studying spender answer,here one twist is suppose i have 10000 lines begins with test: and each line has ID and i am inserting lines based one ID like if ID==ID stored in dictionary ,then i have to store succeeding 10 lines not the very first 10 lines always,so how to do it?
EDIT
@spender i did it like SkipWhile(line => (!line.Contains("ADD GTRX:") && !line.Contains(dict.CellId.ToString()))).Take(10); but no luck at all
EDIT
@spender Finally i did it i have to move the brackets so full code what i did as shown below, i removed blank lines also
var linesOfInterest = File.ReadLines(filename)
                                                              .SkipWhile(line => !line.Contains("test:")).SkipWhile(line => !line.Contains(dictId.ToString())).Take(10);
                                    var output = string.Join(Environment.NewLine, linesOfInterest).Trim().Split(';').Where(arg => !string.IsNullOrWhiteSpace(arg)).ToArray();

You are great ,have a nice day

A: File.ReadLines is your friend here. It gives you an IEnumerable<string> that lazily hands back lines from a text file (i.e. the file is never fully loaded into memory). From there you can LINQ it up nicely.
var linesOfInterest = File.ReadLines(filePath)
                          .SkipWhile(line => !line.Contains(searchTerm))
                          .Take(10);
var output = string.Join(Environment.NewLine, linesOfInterest);


text:
Q: JQuery Interview Online (15 Minutes) TestDome function createProductCodeForm(parent) {
  var form = $("<form/>");

  form.append($("").text('Product Code:'));
  form.append($("<input>").attr('name', 'productCode').attr('type', 'text'));
  form.append($("").attr('name', 'hint').text('The product code can be found on the label.'));

  form.append('
');

  form.append($("<input>").attr('type', 'submit'));

  parent.append(form);
}

The createProductCodeForm function is used to create a new form that accepts a product code from a user.
The current version of the form contains the hint: 'The product code can be found on the label'. This hint is currently always visible to the user.
Improve the form so that the hint is only rendered when the input element is the focused element.
Im having a problem getting this question done since I have little experience with jquery and most of this test has been with javascript / php.

A: You can just bind the right attributes to get this all done:
function createProductCodeForm(parent) {
  var form = $("<form/>");

  form.append($("").text('Product Code:'));
  form.append($("<input>").attr('name', 'productCode').attr('type', 'text').attr('onfocus','$("label[name]").show()').attr('onblur','$("label[name]").hide()'));
  form.append($("").attr('name', 'hint').text('The product code can be found on the label.').attr('style','display:none'));

  form.append('
');

  form.append($("<input>").attr('type', 'submit'));

  parent.append(form);
}

Codepen: https://codepen.io/YasirKamdar/pen/xYJdNy

A: You will have to create event handlers for the focus/blur events:

function createProductCodeForm(parent) {
  var form = $("<form/>");
  var input = $("<input>")
                .attr('name', 'productCode')
                .attr('type', 'text');

  var label = $("")
                .attr('name', 'hint')
                .text('The product code can be found on the label.')
                .hide();

  form.append($("").text('Product Code:'));
  form.append(input);
  form.append(label);

  input.focus(label.show.bind(label));
  input.blur(label.hide.bind(label));

  form.append('
');
  form.append($("<input>").attr('type', 'submit'));
  parent.append(form);
}

createProductCodeForm($('#formContainer'))

A: You can use the Bootstrap plugin to do the task.

function createProductCodeForm(parent) {
  var form = $("<form/>");

  form.append($("").text('Product Code:'));
  var $productCode = $('<input />');
  $productCode.attr({'name' : 'productCode', 'type': 'text'});
  // use Bootstrap tooltip plugin:
  $productCode.tooltip({'trigger':'focus', 'title': 'The product code can be found on the label.', 'placement':'right'});
  form.append($productCode);
  form.append('
');

  form.append($("<input>").attr('type', 'submit'));

  parent.append(form);
}

createProductCodeForm($('body'))
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

A: I think for the element in html should set the class or id to confirm the correct object(ex input:txtInput ,label :lblHint). So I think the code should look like this:
function createProductCodeForm(parent) {
  var form = $("<form></form>");

  form.append($("").text('Product Code:'));
  form.append($("<input>").attr('name', 'productCode').attr('type', 'text').attr('id', 'txtInput'));
  form.append($("").attr('name', 'hint').css("display", "none").attr('id', 'lblHint').text('The product code can be found on the label.'));
  form.append('
');
  form.append($("<input>").attr('type', 'submit'));
  parent.append(form);
  $("#txtInput").focusin(function() {
    $("#lblHint").show();
  });
  $("#txtInput").focusout(function() {
    $("#lblHint").hide();
  });
}


text:
Q: Implementing Non Content Sites Can we use ClouldScribe for non-content scenarios like Classifieds Posting?
Planning to develop a Classifieds Posting web application. Here I want to use cloudscribe's engine and another part (like add posting, listing, search) I will write on my own.Is it possible with cloudscribe or its overkill of cloudscribe ?

A: You can use cloudscribe Core for management of users, roles, claims etc and then build custom features for anything you need.
The idea is for cloudscribe to provide some things so you don't have to build them yourself, ie user management and role and claim management, so you can focus on what you want to build, ie classified posting application.
cloudscribe puts no limits or constraints on your development approach. You could also use cloudscribe SimpleContent for marketing/information pages of your site if you need that, but you can use cloudscribe Core without using SimpleContent if you don't need that.


text:
Q: Lua how can i get all keys in a Table I am currently learning LUA and trying to make a script for a game.
So far everything works fine, but i stuck at a problem and i cant figure out how to do this.
For example i have a LUA file with this content:
DATA["1234"] = {"Admin", 0, 0}
DATA["2793"] = {"Supporter", 0, 0}
DATA["1599"] = {"VIP", 0, 0}
DATA["6473"] = {"User", 0, 0}

*

*DATA = Tablename

*["1234"] = Player IDs

*{"",0,0} = 3 Values for each DATA

What i want is something that give me the number of DATAs i have.
In this example i have 4 DATAs.
When a new Player comes i have 5 DATAs but how can i get the number of "Keys" or "DATAs" i have?
I need this for a Player-Save function.
EDIT:
I forgot something important, sorry..
I need the Keynames as well, its very important!
This works fine:
function tableLength(T)
    local count = 0
    for _ in pairs(T) do count = count + 1 end
    return count
end

But how can i get the keynames of all DATAs?
Btw: The playerId is the SteamID
Something like:
for k, v in pairs(DATA[playerId]) do
    --Code here
end
-- Results:
1234
2793
1599
6473

A: The code below prints the keys in DATA:
for k, v in pairs(DATA) do
    print(k)
end

A: My suggestion for tables like yours is to installing metamethods that handles exactly your table.
I am using it also for tables, like _G or _ENV where no sequence of numbered keys exists.
Than its easy to count the keys also with #
Example
Lua 5.4.0  Copyright (C) 1994-2020 Lua.org, PUC-Rio
> print(code.len)
-- len() for tables having named keys or keys not in sequence
return function(len)
local incr=0
for _ in pairs(len) do
  incr=incr+1
end
return incr
end
> #_G
0
> setmetatable(_G,{__len=load(code.len)(),__index={}})
table: 0x56616700
> #_G
36
-- Now the dump() function that show all keys/values
> print(code.dump)
-- dump(table)
return function(...)
local args={...}
local test,dump=pcall(assert,args[1])
if test then
for key,value in pairs(dump) do
  io.write(string.format("%s=%s\n",key,value))
end
  return true
else
  return test,dump
end
end
> getmetatable(_G).__index.dump=load(code.dump)()
> _G:dump()
assert=function: 0x565aa300
error=function: 0x565a9be0
ipairs=function: 0x565a9a10
tostring=function: 0x565a9300
next=function: 0x565a9a60
select=function: 0x565a9340
package=table: 0x565d2ee0
os=table: 0x565d3e70
rawlen=function: 0x565a97c0
xpcall=function: 0x565a9e30
print=function: 0x565a9920
string=table: 0x565d45a0
pcall=function: 0x565aa3e0
coroutine=table: 0x565d30e0
arg=table: 0x565d6310
rawset=function: 0x565a9710
dofile=function: 0x565aa280
io=table: 0x565d3750
-- cuted off here


text:
Q: How to Update All Rows of Table SQL Below is my code:
@{

    Layout = "/_SiteLayout.cshtml";
    var db = Database.Open("MyDatabase");

    var query = "SELECT * FROM Team";
    var Teams = db.Query(query);
 }

    <form>

            Team Name
            Played
            Points

  @{  foreach(var Team in Teams){

            @Team.TeamName
            <input type="text" value="@Team.Played" name="Played"/>
            <input type="text" value="@Team.Points" name="Points"/>

    }
   }

    </form>

This is the result:

So what I want to do is update my whole table.
What is the SQL query to do this? I want to update Points and Games Played in my database for all teams once the form is posted.

A: I don't actually understand what exactly you are trying to achieve (update your whole table with what?), but here is some information you might find useful:
SQL Update Tutorial, SQL Update, Update from Select

A: Following is My Solution. Anyone have an efficient Solution?
@{
var db = Database.Open("MYDATABSE");

var query = "SELECT * FROM Team";
var Teams = db.Query(query);
var InsertQuery = "";
if(IsPost){

   foreach(var Team in Teams){
       var Points = Request[Team.TeamName];
       var TeamId = Team.TeamId.ToString();
       var Played = Request[TeamId];

       var executeQueryString="UPDATE Team Set Points=@0, Played=@1 WHERE TeamId=@2";
       db.Execute(executeQueryString, Points, Played, Team.TeamId);

   }
   Response.Redirect("~/UpdateTable.cshtml");

}

}

 <form  action="" method="post">

Team Name

Played

Points

  @{  foreach(var Team in Teams){

            @Team.TeamName
            <input type="text" value="@Team.Played" name="@Team.TeamId"/>
            <input type="text" value="@Team.Points" name="@Team.TeamName"/>

    }
   }


text:
Q: Integral by parts in Green\s identity and Uniqueness I am looking at PDE 2nd version written by Evans.On page 42,the theorem uses integral by parts:
$ 0=-\int_{U} w\Delta w \,dx = \int_{U} |Dw|^2\,dx $.
But when I check Green's identity,I see that one term is missing or equals zero probably:$ \int_{\partial U}w\dfrac{\partial w}{\partial n}\,ds $.Does anyone know why this guy is not here,or maybe show it's $\leq 0$?

A: Since in the paragraph just before this line, you are told that $w = u - \tilde u$, and from the preceeding page, they both solve
$$ v|_{\partial \Omega} = g, $$
then $u-\tilde u$ vanishes on the boundary.


text:
Q: Tholins color and scattering One of the prevailing explanations for the reddish color of certain asteroids surfaces and planetary atmospheres, such as Jupiter's and Titan's, is the presence of complex polymeric molecules called tholins.
I understand that particles such as nitrogen molecules in Earth's atmosphere are small enough to interact with blue visible light and scatter it throughout the atmosphere. It also seems like some compounds of carbon appear green (diatomic carbon) and purple (C60 fullerenes) however I think that is mostly due to absorption instead of scattering.
Are tholins big enough to interact with red visible light and that causes their color? Can a subset of tholins be able to scatter different wavelength and produce more greenish hues?

A: Tholins don't create color by (freqyency-selective) scattering.
They are selective in absorbing light.
This is how they look like and work:
https://en.m.wikipedia.org/wiki/Polymethine_dyes
Of course, tholins are much more diverse. They are made by uv light indiscriminately cracking chemical bonds and letting the resulting ions and radicals interact with each other as they please. Most of them are colorless, but those that do have color are in general polymethine dyes.
p.s. neither the absorbtion nor scattering are directly related to molecule sizes.


text:
Q: NATS error: 'Unresponsive client detected, connection dropped' After deploying approximately 70/100 apps at the same time, everything seemed to stop and I stopped the last 30 deployments. However, some time after, all the apps stopped working and I found the following log entry in my dea.log:
[2012-11-06 14:35:14.295386] dea - pid=1390 tid=7e88 fid=592d  ERROR -- EXITING! NATS error: 'Unresponsive client detected, connection dropped'
[2012-11-06 14:35:14.295478] dea exception pid=1390 tid=7e88 fid=592d  ERROR -- NATS::ServerError<<'Unresponsive client detected, connection dropped':>>

All other components of CF seems to work perfectly, but the two DEA servers now won't start any applications. Any idea what could be wrong? Let me know if you need more information, I would love to provide more - but I'm not sure what is relevant.
Edit:
I don't experience this issue, when enforce_ulimit: false in dea.yml
Edit2:
I get this new error, after setting enforce_ulimit: true in dea.yml
[2012-11-06 16:32:32.905127] dea - pid=2143 tid=967a fid=d902  ERROR -- EXITING! NATS error: Unknown protocol: {"droplet":490,"limits":{"mem":64,"disk":2048,"fds":256},"name":"gurodari","runtime_info":{"version":"2.6.5","description":"Python 2.6.5","executable":"python","version_output":"2.[5-7]","version_flag":"--version","environment":{"PATH":"/usr/bin:$PATH"},"nameINFO {"server_id":"a746ae3260317c8fa8c0a0dd57","host":"<ip removed>","port":4222,"version":"0.4.26","auth_required":true,"ssl_required":false,"max_payload":1048576}
[2012-11-06 16:32:32.905936] dea exception pid=2143 tid=967a fid=d902  ERROR -- NATS::ServerError<<Unknown protocol: {"droplet":490,"limits":{"mem":64,"disk":2048,"fds":256},"name":"gurodari","runtime_info":{"version":"2.6.5","description":"Python 2.6.5","executable":"python","version_output":"2.[5-7]","version_flag":"--version","environment":{"PATH":"/usr/bin:$PATH"},"nameINFO {"server_id":"a746ae3260317c8fa8c0a0dd57","host":"<ip removed>","port":4222,"version":"0.4.26","auth_required":true,"ssl_required":false,"max_payload":1048576}:>>

A: Most of the discussion around the Cloud Foundry OSS project (vcap) is happening on the google group: https://groups.google.com/a/cloudfoundry.org/forum/?fromgroups#!forum/vcap-dev
I'd suggest posting over there.


text:
Q: go ignoring vendor directory Everything I read about the vendor directory gives me the understanding that if I have a directory:
$GOPATH/src/vendor

And put my dependencies in there (I am using godeps), when doing go run, go should check in that directory first.
If I run my code in a Docker image I have, this works fine. However now that I try to run the same code on my Windows machine, go simply ignores the vendor/ directory, and fails to find the dependencies.
What am I doing wrong?
main.go:7:2: cannot find package "gopkg.in/alecthomas/kingpin.v2" in any of:
        C:\Go\src\gopkg.in\alecthomas\kingpin.v2 (from $GOROOT)
        C:\Users\js\dev\my_project\rest\src\gopkg.in\alecthomas\kingpin.v2 (from $GOPATH)
        C:\Users\js\dev\go\src\gopkg.in\alecthomas\kingpin.v2

Is the output when I try to do:
go run main.go

A directory vendor/ exists in this directory.
go version go1.7 windows/amd64

The exact commands I run (in windows cmd.exe)
> cd C:\Users\js\dev\my_project\rest\
> set GOPATH=C:\Users\js\dev\my_project\rest\;c:\Users\js\dev\go

> cd src
> dir
...
2016-09-01  23:20             2 923 main.go
...
2016-09-03  01:27    <DIR>          vendor

> go run main.go

A: The reason this did not work is because you are not supposed to put any code directly into the $GOPATH/src/ directory.
The solution is to put your project into a sub-directory like so:
$GOPATH/src/app/*.go

A: Seems your GOPATH is incorrect?
The GOPATH should specify the location of your workspace i.e. directory containing src, pkg and bin directories at its root.
Try doing

set GOPATH=C:\Users\js\dev\my_project\rest\;c:\Users\js\dev\go

More details at: https://golang.org/doc/code.html

A: The first thing to understand is that godep save is simply copying dependencies from your $GOPATH to a vendor directory inside your project.
You will have to go get your dependencies first. After you have them in $GOPATH, you can do a godep save to copy the current version to your project, and be assured that even if the version in $GOPATH changes, you will have a fixed version in your project until you explicitly change it  via godep.
So, if I have a $GOPATH of /home/me/go_workspace, and a project called $GOPATH/src/github.com/project_x with a dependency of github.com/you/xyz, then I would do go get github.com/you/xyz, and godep save from within my project directory.  This would create a vendor folder with the dependency at its current commit inside.


text:
Q: PHP code for showing information depending on selected language? How to put information depending on selected language?
My language code [common.php] is almost same as here: How to write code for multilingual in php?
    <?php
    session_start();
    header('Cache-control: private'); // IE 6 FIX

    if(isSet($_GET['lang']))
    {
        $lang = preg_replace('/[^a-zA-Z]/', '', $_GET['lang']);

    // register the session and set the cookie
        $_SESSION['lang'] = $lang;

        setcookie('lang', $lang, time() + (3600 * 24 * 30));
    }
    else if(isSet($_SESSION['lang']))
    {
        $lang = $_SESSION['lang'];
    }
    else if(isSet($_COOKIE['lang']))
    {
        $lang = $_COOKIE['lang'];
    }
    else
    {
        $lang = 'en';
    }

    switch ($lang) {
        case 'en':
            $lang_file = 'en.php';
            break;

        case 'de':
            $lang_file = 'de.php';
            break;

        case 'ru':
            $lang_file = 'ru.php';
            break;

        case 'chi':
            $lang_file = 'chi.php';
            break;

        case 'arm':
            $lang_file = 'arm.php';
            break;

        default:
            $lang_file = 'en.php';

    }

    include_once 'languages/'.$lang_file;
    ?>

I am using this code for choose  which information must be shown depending on user selected language:
<?php
  function getLang()
{
return $_GET['lang'];
}
//which file will be used
if (getLang() == 'en') {
    include("e.php");
}
else if (getLang() == 'de') {
    include("d.php");
}
?>

It works great if I open my site with adding "localhost/?lang=en" or "localhost/?lang=de".
.  But when I'm just  open Localhost/
it gives an error (twice)
Notice: Undefined index: lang

I'm also tried this code for choosing the file, this code just shows nothing on index.php without adding "/?lang=XX"
<?php
if (@$_GET['lang'] == 'en') include('e.php');
?>
<?php
if (@$_GET['lang'] == 'de') include('d.php');
?>

A: Without adding /?lang=XX you are not passing any argument, and that means
you are not  assigning any value to the parameter lang (that's why you get the notice Notice: Undefined index: lang)
so when you try to  $_GET['lang'] the value will be null.
Use isSet() to check if a variable has been set a value.
So if you want the default language (the language for localhost without /?lang=XX) to be english, add in this line:
if (!isSet($_GET['lang'])){ $lang = 'en'; }

A: try below , now sure working or not..put in commom.php
$lang = (!empty($_GET['lang'])) ? $_GET['lang'] : 'en';


text:
Q: Syncing 2 local SQL Server databases over WCF service in between I am trying to sync 2 SQL Server databases. The scenario is that I have 2 PCs which have identical SQL Server database (both databases have the same structure and schema) and connected to the internet.
Now, I want to have a simple Windows application developed in C# and installed on both PC that may have a 'Sync' command button and clicking on that it calls a WCF service hosted on a web server which then sync data in both databases.
Please suggest the solution.

A: Try looking at merge replications or maybe better Sync Framework 2.1.  Using WCF is not the way you want to go.


text:
Q: Detecting closest element in array I'm having issues detecting the closest element in an array of blocks to the player (using circles).
What I have so far is:
public static int closestBarrier(GameObject object, GameObject[] barriers) {
    int closest = -1;
    float minDistSq = Float.MAX_VALUE;// ridiculously large value to start
    for (int i = 0; i < barriers.length; i++) {

        float barrierRadius = barriers[i].getWidth() / 2;
        float objectRadius = object.getWidth() / 2;

        GameObject curr = barriers[i];// current
        float dx = (object.getX()) - ((curr.getX()));
        float dy = (object.getY()) - ((curr.getY()));
        float distSq = (((dx * dx + dy * dy) - objectRadius) - barrierRadius)  ;// use the squared distance
        if (distSq < minDistSq) {// find the smallest and remember the id
            minDistSq = distSq;
            closest = i;
        }
    }

    return closest;
}

It passes most of the tests but on the final one the returned index of the closest one is 2 instead of the expected 3. Here are the tests (it is failing 'closest to fourth' :
    public final void testClosestBarrier() {
    // Closest to first
    GameObject player = new GameObject(0,1);
    player.setWidth(2);
    GameObject[] barriers = new GameObject[4];
    barriers[0] = new GameObject(8,9);
    barriers[0].setWidth(3);
    barriers[1] = new GameObject(10,15);
    barriers[1].setWidth(2);
    barriers[2] = new GameObject(15,20);
    barriers[2].setWidth(5);
    barriers[3] = new GameObject(100,210);
    barriers[3].setWidth(10);
    assertEquals("Player closest to first barrier",0,
            Submission.closestBarrier(player,barriers));

    // Closest to second
    player.setX(12);
    player.setY(12);
    assertEquals("Player closest to second barrier",1,
            Submission.closestBarrier(player,barriers));

    // Closest to third
    player.setX(12);
    player.setY(20);
    assertEquals("Player closest to third barrier",2,
            Submission.closestBarrier(player,barriers));

    // Closest to fourth
    player.setX(90);
    player.setY(100);
    assertEquals("Player closest to fourth barrier",3,
            Submission.closestBarrier(player,barriers));

}

A: Your code is correct and the test you have written is wrong - barrier 2 is closer to 90,100 than barrier 3.
barrier 2:
(90-15)^2 + (100-20)^2
12025
barrier 3:
(100-90)^2 + (210-100)^2
12200
12025 < 12200 -> barrier 2 is closer
EDIT: In your edited answer, you forgot to square objectRadius and barrierRadius. e.g.
float distSq = (((dx * dx + dy * dy) - objectRadius) - barrierRadius)
In this line, you have dx^2, dy^2 but only non-squared objectRadius and barrierRadius.


text:
Q: IntelliJ Static Web Project to Tomcat or Angular CORs I have a static web angular project in IntelliJ IDEA. The static page gets deployed to http://localhost:63342/Calculator/app/index.html. I have run into a problem where I try to post some data to a server to get a response back but when I try to post I get this error:
XMLHttpRequest cannot load <url>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 401.

Here is my post angular code:
WebIdServer.prototype.getId = function(id) {
    var _this = this;
    var request = {
        method: 'POST',
        url: 'https://<url>,
        headers: {
            'Authorization':'Bearer QWE234J234JNSDFMNNKWENSN2M3',
            'Content-Type':'application/json',
        },
        data: {
            id:id
        }
    };
    _this.$log.debug(request);
    return _this.$http(request)
        .success(function(data, status, headers, config){
            _this.$log.debug("Successfull request.");
            /*called for result & error because 200 status*/
            _this.uid = data.id;
            _this.$log.debug(_this.uid);
        })
        .error(function(data, status, headers, config){
            _this.$log.debug("Something went wrong with the request.");
            _this.$log.debug(data);
            /*handle non 200 statuses*/
        });
};

I know for a fact that post works because I tried it on a local url of my application that I had running on a different port.
So my question is, since I can't post from localhost I was wondering if maybe deploying this to a tomcat server would fix things. If so, how do you deploy this static web project to a tomcat server? If that's not necessary, then how do I get around this problem I'm having?

A: There's a few things regarding CORS. It's a web browser telling you you cannot make a particular call. This is only a front end problem, a script running on a server can call any api regardless of the location. Three different options:
without config; same hosts
Without any configuration on your server, your front end's AJAX requests need to match both the domain and the port of the service you're calling. In your case, your angular app at http://localhost:63342 should be calling a service also hosted on http://localhost:63342 and then you're sweet. No CORS issues.
with server side config; different hosts
If the API is hosted elsewhere, you'll have to configure the API host. Most servers will let you configure access controls, to allow a particular domain to bypass the CORS block. If you have access to the server you're trying to call, see if you can set it up. The enable CORS website has examples for most servers. Usually this is pretty simple.
Create a proxy
This is your Tomcat idea. CORS is only a problem if your front end calls another service. A server script can call anything it likes. So, you could use Tomcat (or Apache, or NGINX, or NodeJS...) to host a script that'll pass on the request. Essentially, all it needs to do is add Access-Control-Allow-Origin: * to the response of the API.
I have never used Tomcat myself, but here's a blog post that might have some useful info on how to do that. Combine it with the info on enable CORS and you should be able to route anything to anywhere.
This process is common. Just look at the popularity of a node package like CORS anywhere, which is what your tomcat does.
As a disclaimer, how good of an idea this is depends on how you can pass along the credentials and tokens. You don't really want to create a service that'll just blindly call someone else's API with your credentials.


text:
Q: UnboundLocalError: local variable 'print' referenced before assignment? I am trying to make a text based rpg styled game. The problem I am having is that it is coming up with:

UnboundLocalError: local variable 'print' referenced before assignment

and I don't know why. I have searched online and found that normally it is from global variables being used locally, but I don't understand why this is done with print. Also it keeps looping back to the start without reading out the print for def option_statue. I am using Python 3.7.3:
import time
import random

answer_A = ["A", "a"]
answer_B = ["B", "b"]
answer_C = ["C", "c"]
yes = ["Y", "y", "yes"]
no = ["N", "n", "no"]
required = ("\nUse only A, B, or C\n")

hp = 30
sword = 0
flower = 0

goblin_damage = random.randint(1,5)

def intro():
    print("You wake with a start, cold mountain air fills your lungs as a bird cry shatters the serenity of the early morning.")
    print("You rise to your feet and observe your surroundings,it is clear that you are in a forest of some sort, the tall oaken arms of nearby trees strech into the sky")
    print(",they cast a soft shadow on you, and combined with the damp grass beneath your feet, results in a brisk morning awakening")
    time.sleep(1)
    print("How or why you are here remains unknown")
    time.sleep(1)
    print("What will you do now?")
    time.sleep(1)
    print("""A. Look around
B. Sit back down""")

    choice = input (">>> ")
    if choice in answer_A:
        option_lookaround()
    elif choice in answer_B:
        print("\nYou sit back down.\nWell that was fun")
        time.sleep(3)
        print("After lying down for a while, chewing grass and contemplating why you are here, you eventually decide to do something")
        time.sleep(1)
        option_lookaround()
    else:print (required)
    intro()

def option_lookaround():
    print("As you blink the sleep from your eyes, you realize that you are in a grove, in the centre, lies the broken remains of a statue")
    print("to your left you see a small stream and to your right appears to be the glow of a campfire. Will you:")
    print("""A. Explore the statue
B. Walk towards the stream
C. Investigate the campfire""")

    choice = input (">>> ")
    if choice in answer_A:
        option_statue()
    elif choice in answer_B:
        option_stream()
    elif choice in answer_C:
        option_campfire()
    else:
        print (required)
        option_lookaround()

def option_statue():
    global hp
    print:("""The statue appears before you, a grand monument to its era, now faded into obscurity,
it appeared to have been a humanoid of some sort, yet the eons of weather have worn the features to a near unrecognizable state""")
    hp = (hp- goblin_damage)
    print("You now have" ,hp, "health points")

intro()

Errors:
Traceback (most recent call last):
  File "/home/pi/Python/Text story adventure.py", line 79, in <module>
    intro()
  File "/home/pi/Python/Text story adventure.py", line 39, in intro
    option_lookaround()
  File "/home/pi/Python/Text story adventure.py", line 61, in option_lookaround
    option_statue()
  File "/home/pi/Python/Text story adventure.py", line 76, in option_statue
    print("You now have" ,hp, "health points")
UnboundLocalError: local variable 'print' referenced before assignment

A: Your problem lies in this line:
print:("""The statue appears before you, ...""")
#    ^
#    Specifically here.

Have a look at the following transcript, which shows your problem in a smaller code snippet:
>>> def fn():
...     print:("Hello there.")
...     print(42)
...
>>> fn()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in fn
UnboundLocalError: local variable 'print' referenced before assignment

The print:("Hello") is actually a form of the Python type hinting (annotations) and it looks like this is simply marking print as a local variable (without assigning anything to it), which is why you're seeing the "referenced before assignment" error.
The solution is simply to get rid of the colon:
print("""The statue appears before you, ...""")

As added fun information (well, for some weird definition of "fun"), there's nothing really special about print, you can do all sorts of wonderful things by assigning to it:
>>> print(7)
7
>>> print = 42
>>> print(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Or coercing it into doing something other than intended, such as outputting 42 despite what you give it (please don't do stuff like this in real code):
def newprint(*args):
    global oldprint, print
    try:
        oldprint
    except:
        oldprint = print
        print = newprint
    oldprint(42)

print(7)                         # 7
newprint(7)                      # 42
print(7)                         # 42
print("Hello", "from", "pax")    # 42


text:
Q: gThumb Browser and Viewer should have black background, how to do? I really like gThumb but I hate that gThumb is using my standard ambiance theme when viewing images. The result is that I have a lightgrey background for images but in my opinion images look the best with a black background.
Here is the area I want to have black (look at the red arrow):

Is there a way that I can configure gThumb or let gThumb use another theme than the rest of my programs?

A: Paolo Bacchilega from gThumb Mailing list helped me on this:
open
dconf-editor

browse to org -> gnome -> gthumb -> image-viewer and check the black-background option.


text:
Q: Child Fragment's setUserVisibleHint and onResume not called I am trying to call a function when user switch the page to my child fragment. But, when I try to use setUserVisibleHint and onResume, both functions are called from my parent fragment.

First, I set up a view pager in Activity
Then in A1, A3 and B1, I have setUserVisibleHint and onResume functions.
setUserVisibleHint and onResume functions
@Override
public void setUserVisibleHint(boolean visible) {
    super.setUserVisibleHint(visible);
    Log.d("A1", "setUserVisibleHint"); // A3 for Fragment A3 and B1 for Fragment B1
    if (visible && isResumed())
        onResume();
}
@Override
public void onResume() {
    super.onResume();
    Log.d("A1", "onResume"); // A3 for Fragment A3 and B1 for Fragment B1
    if (!getUserVisibleHint())
        return;
}

Issues:
When I click page B from page A and the view is Fragment B1, I get (This is OK)
D/A1: setUserVisibleHint
D/B1: setUserVisibleHint
D/B1: onResume

When I click page A from page B and the view is Fragment A1, I get (This is OK)
D/B1: setUserVisibleHint
D/A1: setUserVisibleHint
D/A1: onResume

When I click page A from page B and the view is Fragment A3, I get (ISSUE)
D/B1: setUserVisibleHint
D/A1: setUserVisibleHint
D/A1: onResume

I assume that the printout should be like below but I am not sure why the functions called by parent fragment.
D/B1: setUserVisibleHint
D/A3: setUserVisibleHint
D/A3: onResume

Reference
From fragment A1 -> A2,
A2 a2 = new A2();
getFragmentManager().beginTransaction().add(R.id.A1_frameChildFragment, a2)
    .addToBackStack(null)
    .commit();

From fragment A2 -> A3,
A3 a3 = new A3();
getFragmentManager().beginTransaction().add(R.id.A2_frameChildFragment, a3)
    .addToBackStack(null)
    .commit();

A: onResume will not called when you switch between tab in ViewPager.
setUserVisibleHint will called in the parent fragment of each tab when you switch between in ViewPager and will not called in child fragment.
This is the default behavior so I think we can not change it.
However, there is a workaround solution. It is sending the visible hint from parent fragment to child fragment
// visible hint in parent fragment
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (!isAdded()) {
        return;
    }
    Fragment fragment = getChildFragmentManager().findFragmentById(R.id.A1_frameChildFragment); // find current child fragment
    if (fragment != null) {
        fragment.setUserVisibleHint(isVisibleToUser); // send visible from parent to this child fragment
    }
}

A: setOnPageChangeListener method is now deprecated, use addOnPageChangeListener instead
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
        // do your work
    }
});

A: For this, you have to call your fragment when you load / when you click on the tab bar/tab view.
Like in your case all fragments are load at the same time so when you change the fragment it not provide any event in class.
For my application, I got the same issue so I load the fragment when I click on the tab then after the fragment called and will provide the event.

A: First of all always start or create a fragment from Activity. Because Fragment is basically a instance or a part of your Activity. That's why, always start or create fragment from Activity context instead of Fragment for better control over fragment lifecycle.
For example to start FragmentA from FragmentB create a method in your Activity as,
public void startFragmentB(){
   FragmentManager manager = getSupportFragmentManager();
   FragmentB fragment = new FragmentB();
   FragmentTransaction transaction = manager.beginTransaction();
   transaction.replace(R.id.container, fragment).addToBackStack("tag");
   transaction.commit();
}

Now where you want to start or create FragmentB in your FragmentA just call above method from your activity as,
((YourActivity) getActivity()).startFragmentB();


text:
Q: How to make loops multithread in ruby? How can I make these loops parallel with multithreading capability of ruby?
1.
from = 'a' * 1
to = 'z' * 3

("#{from}".."#{to}").each do |combination|

    # ...

end

2.
@@alphabetSet_tr.length.times do |i|
    @@alphabetSet_tr.length.times do |j|
        @@alphabetSet_tr.length.times do |k|
            combination = @@alphabetSet_tr[i] + @@alphabetSet_tr[j] + @@alphabetSet_tr[k]
        end
    end
end

Note: @@alphabetSet_tr is an array which has 29 items

A: If you want to utilize your cores, you can use a Queue to divide the workload between a constant number of threads:
require 'thread'

queue = Queue.new

number_of_cores = 32

threads = (0..number_of_cores).map do
  Thread.new do
    combination = queue.pop
    while combination
      # do stuff with combination...

      # take the next combination from the queue
      combination = queue.pop
    end
  end
end

# fill the queue:
("#{from}".."#{to}").each do |combination|
  queue << combination
end

# drain the threads
number_of_cores.times { queue << nil }

threads.each { |t| t.join }

If you fear that the size of the queue itself would be an issue - you can use SizedQueue which will block push operations if it gets larger than a certain size - capping its memory usage -
queue = SizedQueue.new(10000)

A: from = 'a' * 1
to = 'z' * 3

threads = ("#{from}".."#{to}").map do |combination|
  Thread.new do
      # ...
  end
end

# In case you want the main thread waits all the child threads.
threads.each(&:join)


text:
Q: Solaris 10 keyboard problem Im runing Solaris 10 - but im having problems with the keyboard.
Instead of - i get /, and instead of y i get z, etc. I tried changing every option in the menu "Keyboard Behaviour". I also tried changing kmdconfig from xorg to xsun, but then the graphics goes all wild and ugly - although the keyboard works fine then. Also cant change resolution in xsun mode.
By the way, im runing Solaris from Vmware, but i doubt this has anything to do with this.

A: Leave the graphic environment to the console:
dtconfig -d
dtconfig -reset

Select the correct keyboard layout you use:
kbd -s

Load it:
loadkeys

Check the keys are working properly. If okay, enable the graphical environment again:
dtconfig -e

If that still works, make that choice persistent after a reboot by updating your eeprom. eg:
eeprom kbd-type=Spanish

A: *

*This should be migrated to superuser.com

*It seems that you are expecting a german keyboard layout but are getting a US layout - at least the differences you are seeing are differences between those layouts. I don't know where to change that in openSolaris, but maybe it helps you find the correct place to look. Whatever desktop environment that you are using, it should have a tool to change the keyboard layout, probably somewhere with the other internationalization settings.


text:
Q: Single data from the relation m2m field - Django In my signal (post_save), I would like to send a single email to a single person who has been assigned using the m2m relationship. One-to-many, the message goes to the user, but m2m nothing happens.
specials = models.ManyToManyField(User, related_name='special_users')

I've tried everything, searched the topics, but still nothing happens. I have included the pseudocode to illustrate the situation.
all_users_from_m2m = instance.specials.all()

    for single_user in all_users_from_m2m:

        message = ('Subject', 'Here is message', 'from@example.com', [single_user.email])
        send_mass_mail(message, fail_silently=False)

A: I'm not totally sure if I understand your test case but there is a signal called m2m_changed. You could use it like so for instance:
from django.db.models.signals import m2m_changed

def on_some_model_specials_m2m_changed(sender, instance, *args, **kwargs):
    # some actions here
    pass

m2m_changed.connect(
    on_some_model_specials_m2m_changed, sender=models.YourModel.specials.through)


text:
Q: Prove: $\frac{1}{11\sqrt{2}} \leq \int_0^1 \frac{x^{10}}{\sqrt{1+x}}dx \leq \frac{1}{11}$ Prove: $\frac{1}{11\sqrt{2}} \leq \int_0^1 \frac{x^{10}}{\sqrt{1+x}}dx \leq \frac{1}{11}$
Hint: Use the (weighted) Mean Value Theorem for Integrals.
The MVT for Integrals:
Suppose that $u$ is continuous and $v$ is integrable and nonnegative on $[a,b]$
Then $\int_a^b u(x)v(x)dx=u(c)\int_b^a v(x)dx$
for some $c$ in $[a,b]$.
I plan on using $u(x)$ as $x^{10}$ as it is continuous and $v(x)$ as $\frac{1}{\sqrt{1+x}}$ as it is integrable on [0,1]. I'm not sure how to go from there and find $c$.

A: Hint. One has, by a direct approach,
$$
\frac{x^{10}}{\sqrt{1+1}}\le \frac{x^{10}}{\sqrt{x+1}}\leq \frac{x^{10}}{\sqrt{0+1}}, \qquad 0\le x\le1.
$$

A: Choosing $v(x) = \frac{1}{\sqrt{x+1}}$ doesn't work, I think:
I didn't use MVT directly. I used something from the proof of MVT:

$$m \int_0^1 \frac{1}{\sqrt{x+1}} dx \le \int_0^1 \frac{x^{10}}{\sqrt{x+1}} \le M \int_0^1 \frac{1}{\sqrt{x+1}} dx$$
The best $m$ and $M$ I got are $0$ and $1$ resp as $0 \le x^{10} \le 1$ for $0 \le x \le 1$

So let's try
$u(x) = \frac{1}{\sqrt{x+1}}$
Now $\frac{1}{\sqrt{2}} \le \frac{1}{\sqrt{x+1}} \le 1$ for $0 \le x \le 1$
So we have
$$\frac{1}{\sqrt{2}} \int_0^1 x^{10} dx \le \int_0^1 \frac{x^{10}}{\sqrt{x+1}} \le 1 \int_0^1 x^{10} dx$$

Remark: I think the 11's in the denominator may be a hint to use $u(x) = \frac{1}{\sqrt{x+1}}$

A: By the Cauchy-Schwarz inequality
$$ I=\int_{0}^{1}\frac{x^{10}}{\sqrt{1+x}}\,dx\leq \sqrt{\int_{0}^{1}x^{10}\,dx\int_{0}^{1}\frac{x^{10}\,dx}{1+x}}=\sqrt{\frac{1}{11}\left(\log2-\frac{1627}{2520}\right)}$$
and by integration by parts
$$ I = \frac{1}{11 \sqrt{2}}+\frac{1}{22}\int_{0}^{1}\frac{x^{11}\,dx}{\sqrt{(1+x)^3}}\geq\frac{1}{11\sqrt{2}}+\frac{1}{528\sqrt{2}}$$
so we have the much better inequality
$$ \color{red}{0.065}621652\leq   I \leq \color{red}{0.065}721354.$$


text:
Q: Can I set up 2 SignalR connections? I have a basic chat app set up like so:
$(function () {
// Set up references for other functions to call
   chatConnection = $.connection.chatHub;
   // Set up callbacks before starting server connection
   chatConnection.client.addNewMessageToPage = function (name, message) {
      var prettyMessage = name + ':' + message;
      $('#chatHistory').append(prettyMessage);
      $("#chatHistory").animate({ scrollTop: $('#chatHistory').prop("scrollHeight") }, 10);
   };
   // Start up connection to server, set up events
   $.connection.hub.start().done(function () {
      $('#sendChatButton').click(function () {
        // Call the Send method on the hub.
        chatConnection.server.sendMessage($('#displayName').val(), $('#chatBox').val());
        // Clear text box and reset focus for next comment.
        $('#chatBox').val('').focus();
      });
   });
});

This calls into my ChatHub.cs server side and I am getting and passing back messages as you would expect.
public void SendMessage(string name, string message)
{
    Clients.All.addNewMessageToPage(name, message);
}

Now I want to add functionality. I Have a new class almost identical to my ChatHub called "GameHub" and it's job is to process moves instead of processing chat. So far I have something like this:
$(function () {
// Set up references for other functions to call
   chatConnection = $.connection.chatHub;
   gameConnection = $.connection.gameHub;
   // Set up callbacks before starting server connection
   chatConnection.client.addNewMessageToPage = function (name, message) {
      var prettyMessage = name + ':' + message;
      $('#chatHistory').append(prettyMessage);
      $("#chatHistory").animate({ scrollTop: $('#chatHistory').prop("scrollHeight") }, 10);
   };
   gameConnection.client.receiveMove = function (name, move){
      alert(name + ' played ' + move);
   };
   // Start up connection to server, set up events
   $.connection.hub.start().done(function () {
      $('#sendChatButton').click(function () {
        // Call the Send method on the hub.
        chatConnection.server.sendMessage($('#displayName').val(), $('#chatBox').val());
        // Clear text box and reset focus for next comment.
        $('#chatBox').val('').focus();
      });
      $('#sendMoveButton').click(function () {
        gameConnection.server.sendMove(getMove());
      });
   });
});

but nothing is making it to the server. Is this because I don't have it set up correct? Can signalR even support 2 hubs or should it be a single hub and "spoke" out from there to my 2 different functional areas?

A: You can but given that there is no performance difference it's simpler to have those functions in one hub. All data will hit all hubs as they all share the same connection.
As documented here.
You can check, since it's not provided, your game hub and method to ensure you have them named and cased properly on the server side. Possible issues...


text:
Q: Find the area between curve and straight line
My first step is to let y of the first equation equal the second:
$2x -1 = x^2 + 6x + 2$
= $x^2 + 4x +3 = 0$
= $(x + 3)(x + 1)$
To find the area, I find the integral of the top most equation and subtract it from the integral of the bottom query, I believe that the top equation is the line so:
$\int_{-3}^{-1}2x-1 dx$
=> $x^2 - x$
=> $(1 -- 1) - (9 -- 3) = -12$
I now find the integral of the curve:
$\int_{-3}^{-1}x^2 + 6x + 2 dx$
=> $\frac{x^3}3 + 3x^2 + 2x$
=> ${(\frac{-1}{3} + 3 - 2}) - (-9 + 27 -6)$
=> $12\frac{1}{3}$
Then I subtract the first integral from the second:
$-12 - 12\frac{1}{3}$
This leads me to a minus number.  Where have I gone wrong?

A: Firstly,
$$[x^2-x]_{-3}^{-1}=(1-(-1))-(9-(-3))=2-12=-10$$
And,
$$(-\frac13-2)-(-9+27-6)=\frac23-12=-\frac{34}{3}$$
So, the result is
$$-10+\frac{34}{3}=\frac43$$


text:
Q: Do any common email clients pre-fetch links rather than images? Although I know a lot of email clients will pre-fetch or otherwise cache images. I am unaware of any that pre-fetch regular links like some link
Is this a practice done by some emails? If it is, is there a sort of no-follow type of rel attribute that can be added to the link to help prevent this?

A: As of Feb 2017 Outlook (https://outlook.live.com/) scans emails arriving in your inbox and it sends all found URLs to Bing, to be indexed by Bing crawler.
This effectively makes all one-time use links like login/pass-reset/etc useless.
(Users of my service were complaining that one-time login links don't work for some of them and it appeared that BingPreview/1.0b is hitting the URL before the user even opens the inbox)
Drupal seems to be experiencing the same problem: https://www.drupal.org/node/2828034

A:
Although I know a lot of email clients will pre-fetch or otherwise cache images.

That is not even a given already.
Many email clients – be they web-based, or standalone applications – have privacy controls that prevent images from being automatically loaded, to prevent tracking of who read a (specific) email.
On the other hand, there's clients like f.e. gmail's web interface, that tries to establish the standard of downloading all referenced external images, presumably to mitigate/invalidate such attempts at user tracking – if a large majority of gmail users have those images downloaded automatically, whether they actually opened the email or not, the data that can be gained for analytical purposes becomes watered down.

I am unaware of any that pre-fetch regular links like some link

Let's stay on gmail for example purposes, but others will behave similarly: Since Google is always interested in "what's out there on the web", it is highly likely that their crawlers will follow that link to see what it contains/leads to – for their own indexing purposes.

If it is, is there a sort of no-follow type of rel attribute that can be added to the link to help prevent this?

rel=no-follow concerns ranking rather than crawling, and a no-index (either in robots.txt or via meta element/rel attribute) also won't keep nosy bots from at least requesting the URL.
Plus, other clients involved – such as a firewall/anti-virus/anti-madware – might also request it for analytical purposes without any user actively triggering it.

If you want to be (relatively) sure that any action is triggered only by a (specific) human user, then use URLs in emails or other kind of messages over the internet only to lead them to a website where they confirm an action to be taken via a form, using method=POST; whether some kind of authentication or CSRF protection might also be needed, might go a little beyond the context of this question.

A: All Common email clients do not have crawlers to search or pre-build  tag related documents if that is what you're asking, as trying to pre-build and cache a web location could be an immense task if the page is dynamic or of large enough size.
Images are stored locally to reduce load time of the email which is a convenience factor and network load reduction, but when you open an email hyperlink it will load it in your web browser rather than email client.
I just ran a test using analytics to report any server traffic, and an email containing just
linktomysite
did not throw any resulting crawls to the site from outlook07, outlook10, thunderbird, or apple mail(yosemite). You could try using a wireshark scan to check for network traffic from the client to specific outgoing IP's if you're really interested

A: You won't find any native email clients that do that, but you could come across some "web accelerators" that, when using a web-based email, could try to pre-fetch links. I've never seen anything to prevent it.
Links (GETs) aren't supposed to "do" anything, only a POST is. For example, your "unsubscribe me" link in your email should not directly unsubscribe th subscriber. It should "GET" a page the subscriber can then post from.
W3 does a good job of how you should expect a GET to work (caching, etc.)
http://www.w3schools.com/tags/ref_httpmethods.asp


text:
Q: How to treat java package as a File folder? I want to be able to iterate through a package of files as if the package were a folder.
Something like the below (scripts being the java package):
        File scriptFolder = new File("scripts").getAbsoluteFile();

The packages appear are not being treated like folders. If I hardcode the path C:\Users\...\project_folder\...\scripts the File.isFile() method returns false for the package. If I do  new File (C:\Users\...\project_folder\...\scripts\script).isFile() I get true.
I want to get a File of the folder so I can get a list of the files in the folder and iterate through it.

A: The .isFile() method returns true only if you are referencing a plain jane normal file. If you're referencing a directory, it'd return false. Try .isDirectory() or possibly .exists().
Or don't; there's no real need:
File[] filesInDir = new File("C:\\Users\\....\\scripts").listFiles();
if (filesInDir == null) {
    // this means it wasn't a directory or didn't exist or isn't readable
} else {
    for (File child : filesInDir) {
        // called for each file in dir
    }
}

A: The official javadocs say this about File#isFile():

Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.

You can check if it is a directory with File#isDirectory(), then if it is, you can list its contents with File#listFiles().

A: Unless I'm missing something in your question C:\Users...\project_folder...\scripts is a directory so isFile() will return false because it is not a file.


text:
Q: Blurring an image in Android I am using the following code to blur an image in android, but it does not work. The final image that I get is with very distorted color and not a blur which I want. What am I doing wrong?
public Bitmap blurBitmap(Bitmap bmpOriginal)
{
    int width, height;
    height = bmpOriginal.getHeight();
    width = bmpOriginal.getWidth();

    Bitmap bmpBlurred = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    for (int i = 1; i < width - 1; i++) {
        for (int j = 1; j < height - 1; j++) {
            int color = (int) getAverageOfPixel(bmpOriginal, i, j);
            bmpBlurred.setPixel(i, j, Color.argb(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color)));
        }
    }
    return bmpBlurred;
}

private double getAverageOfPixel(Bitmap bitmap, int i, int j) {
     return (
    bitmap.getPixel(i-1, j-1) + bitmap.getPixel(i-1, j) + bitmap.getPixel(i-1, j+1) +
    bitmap.getPixel(i, j-1) + bitmap.getPixel(i, j) + bitmap.getPixel(i, j+1) +
    bitmap.getPixel(i+1, j-1) + bitmap.getPixel(i+1, j) + bitmap.getPixel(i+1, j+1)) / 9;
}

A: Your problem is that you are combining all the colour channels at once and they all spill into each other. You should apply your blur function to the red, green, and blue channels separately.
Might it be easier to create a SurfaceView and use the FX_SURFACE_BLUR flag?