text:
Q: Logs files suddenly stopped to be filled I have just installed a setup a new SP 2010 server.
I don't know why, but suddenly, logs files stopped to be filled (and so ULS viewer remains empty).
At the time of the last log entry, I was setting up the UPSA, but I don't think it matters.
How can I check if my log settings are correct ? I just want the default logging behavior, so I can accept to reset something if required.
thx

A: Can you restart the  SharePoint 2010 Tracing Service and the SharePoint 2010 Administration  Services  to see whether the logs are generating again. You can check the configuration in Central Administration Link

A: Make sure that your farm account is a member of the local group "Performance Log Users"

A: In my case (SP 2013) the ULS logs were not genereated and I had no entries in Windows Event Log as well, because the SharePoint Tracing Service (SPTraceV4) was accidentally stopped:
Tracing service is not running
Symptoms: No trace output is being recorded in the trace logs and no errors are being logged to the Windows log.

See source here.

A: In my case. I installed June 2013 CU about a week ago. Today I had a need to go to log and notice it has not been generating since the day I applied CU.
I went to each SharePoint server and noticed "SharePoint Tracing Service" logon changed to domain account. It should be "Local Service". I changed the login to Local Service and restarted "SharePoint 2010 Tracing" and boom it started working again.

A: Have you checked the log folder (typically C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS) for newer files? A new log file is created every 30 minutes.
Have you checked logging settings on central administration via Monitoring / Configure diagnostic logging? Try to select 'All Categories' and then set 'Least critical event to report to the trace log' to 'Verbose' and make sure that the logging path is as expected.
I suppose you have already checked the disk space...

A: Check disk space, if it's too low, it may stop overall. Also, check your timer job service, make sure it's running and no errors are being reported (check ULS logs). I've run into issues with logging with both of these items.


text:
Q: Trying to read a text file in javascript but keep getting status =0 and no text I'm trying to use JavaScript to read the contents of a text file.  The text file is in the root c drive folder.  XMLHttpRequest.status is returning 0 and no text.  What am I doing wrong?
<!DOCTYPE html>

Hello World!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I shift the  layout to the bottom of the view I am trying to push my included view to the bottom of the layout, however I am not having any luck.Currently it's placed at the top of the layout.The code for the same is as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/altercolor2"
    android:clickable="true"
    android:orientation="vertical" >

    <include
        layout="@layout/layout_grid_details_header_view"
        android:visibility="gone" />

     <include layout="@layout/last_updated_time" />

    <RelativeLayout
        android:id="@+id/markets_column_names"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/black"
        android:paddingBottom="3dp" >

        <TextView
            android:id="@+id/markets_column_name1"
            android:layout_width="75dp"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/markets_column_name2"
            android:textSize="12sp"
            android:gravity="right" />

        <TextView
            android:id="@+id/markets_column_name2"
            android:layout_width="75dp"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/markets_column_name3"
            android:textSize="12sp"
            android:gravity="right" />

        <TextView
            android:id="@+id/markets_column_name3"
            android:layout_width="85dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:textSize="12sp"
            android:paddingRight="6dp"
            android:gravity="right" />
    </RelativeLayout>

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/markets_grid_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

       <include layout="@layout/loading_no_results" />

</LinearLayout>

The main thing I am looking to switch at the bottom of the list is :          <include layout="@layout/last_updated_time" />
so, I tried           I also tried setting paddingbottom andlayout_below: relavitive layout id, and tried setting layout_gravity = bottom and gravity = botttom, still no luck.Any clue how to push this at the bottom of the view such that it still remains visible even if the list is long, but at the bottom of the view, like overlapping the list view at the bottom.
Thanks!Justin

A: Give layout_width and layout_height attribute to 'include tag', then you can give it any of it's parent tag attribute

A: Since the root layout is a LinearLayout with a vertical orientation, it is going to be drawn in the order you have them. Simply putting it as the last View in the xml would draw it below the previous View then you could play with margin, padding, whatever to get it to be where you want.
A better option would be to change the root layout to a RelativeLayout and give the View in question the property
     android:layout_alignParentBottom="true

You may have to adjust some properties of other Views to get exactly what you want but its hard to say without seeing an image of how it should look. Also, android:layout_below="" wouldn't work with its parent layout being a LinearLayout...that is only a property for RelativeLayout.
Edit with code example
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/altercolor2"
    android:clickable="true" >

    <include
        layout="@layout/layout_grid_details_header_view"
        android:visibility="gone" />

     <include layout="@layout/last_updated_time"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true" />

    <RelativeLayout
        android:id="@+id/markets_column_names"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/black"
        android:paddingBottom="3dp" >

        <TextView
            android:id="@+id/markets_column_name1"
            android:layout_width="75dp"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/markets_column_name2"
            android:textSize="12sp"
            android:gravity="right" />

        <TextView
            android:id="@+id/markets_column_name2"
            android:layout_width="75dp"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@+id/markets_column_name3"
            android:textSize="12sp"
            android:gravity="right" />

        <TextView
            android:id="@+id/markets_column_name3"
            android:layout_width="85dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:textSize="12sp"
            android:paddingRight="6dp"
            android:gravity="right" />
    </RelativeLayout>

    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/markets_grid_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

       <include layout="@layout/loading_no_results" />

</RelativeLayout >

A: Try using frame layout : make your current linearlayout as first child (removing the include  view that u want to move to bottom). Make the include view as second view and set its layout_gravity to bottom.


text:
Q: How to insert data from multiple sql queries into 1 row in a table? I have a visual studio report that runs every weeknight and it generates a PDF with different sales info. For example: total sales amount, total orders, total inventory breakdown, etc. All these numbers are pulled from different tables using different queries. What I want to do is have all the queries run every night, and have the data stored in a new line for each date in a table.
Here is an example of how I'd like it to look.
Date       Sales     Orders     Inventory Value
1/1/2017   5,000     50         10,000
1/2/2017   6,000     60         9000
1/3/2017   5,500     55         8500

So each line would be a day, and there would be columns for each of my values that my queries pull. I'm not sure how to go about this. I attempted a union all but all my data was being put into new lines instead of all of the data from that given day on that line together.
Any ideas how to achieve something like this?

A: Use several cte, one for each function
WITH [Sales] as (
       SELECT date, sales
       .... <your query>

), [Orders]  as (
       SELECT date, Orders
       .... <your query>

), [Inventory Value]  as (
       SELECT date, Inventory
       .... <your query>
)
SELECT S.[date], S.[Sales], O.[Orders], I.[Inventory]
FROM [Sales] S
JOIN [Orders] O ON S.[date] = O.[date]
JOIN [Inventory Value] I ON S.[date] = I.[date]


text:
Q: Objective-C: Multidimensional array as a parameter i try to pass a multidimensional array as a parameter to a method. in this method the reference to the array should be stored in another variable. this all seems to work, but when i try to access the array through my new variable there is a error.
this is my code:
-(void)renderMap:(char[MAP_HEIGHT][MAP_WIDTH])mapData {
        char* data;
        data = *mapData;
        NSLog(@"%c", data[1][1]); // Subscripted value is not an array, pointer, or vector
}

A: Try to refer directly via mapData, without data = *mapData.

A: You can try this
char (*data)[MAP_WIDTH] = mapData
NSLog(@"%c", data[1][1]);

A: mapData is not a bidimensional array, so you can't use the double brackets. You have to access to every element by calculating the offset of each element's row:
NSLog(@"%c",data[1*MAP_HEIGHT+1]);
// Generic way:
NSLog(@"%c",data[row*MAP_HEIGHT+column]);


text:
Q: Ember get hasMany I have Model
EmberApp.Card = DS.Model.extend({
  balance: DS.attr('number'),
  operations: DS.hasMany('operation', { async: true })
});

Than I make
self.store.find('card', 'me')

response
{
  "card": {
    "id": "53620486168e3e581cb5851a",
    "balance": 20
  }
}

getting card Model but without operations and setting it to controller prop "currentCard"
Then I want to find operations throw url /cards/me/operations
response
{"operation": [{ "id": 1, "type": 1 }] }

How can I do it from this.controllerFor('*').get('currentCard')... ?

A: You actually need to return your operations as a list of ID's in your card response like this:
{
  "card": {
    "id": "53620486168e3e581cb5851a",
    "balance": 20,
    "operations": [1, 2, 3]
  }
}

This will enable you to do this in another route:
this.modelFor('card').get('operations');

or this in your cards controller:
this.get('content.operations');

This will execute the following call to your API:
/api/operations?ids[]=1&ids[]=2&ids[]=3

A: First of all you should add links to response from cards/me
EmberApp.ApplicationSerializer = DS.RESTSerializer.extend({
  normalizePayload: function(type, payload) {
    if (type.toString() === 'EmberApp.Card') {
      payload.links = { 'operations': '/cards/me/operations' };
      return { card: payload };
    } else if (type.toString() === 'EmberApp.Operation') {
      return { operations: payload };
    }
 }

});
Then in route
EmberApp.CardOperationsRoute = Ember.Route.extend({
  model: function() {
    return this.controllerFor('sessions.new')
      .get('currentCard')
      .get('operations');
  }
});


text:
Q: UPS turning off by itself every morning I have a UPS and a server connected to it.
It works well all day long, but something after midnight its leds start flashing and it does doing some noises, like "tec, tec" as a relay. And it continues increasing the speed between this until it completly turns off. It just can't support the server. After this I need to wait a few hours to make it work again, or it will turn off again.
What means this?
thank you.

A: Well, either your UPS is failing or you're putting a high enough load on it that it's needing to supplement from its battery, which eventually gets depleted.
Connect up to its management port and see what the logs say.
Oh, and the noises you're hearing? Those are the various relays in the UPS opening and closing.


text:
Q: OpenLayers: Open popup when hovering vector, without closing it when mouse is over popup itself I have a map with a vector layer showing features from GeoJSON. When I hover the feature, a pop-up shows up at the beginning of the linestring. But it is flickering, it appears and disappears. I guess the feature somehow gets deselected. Maybe popup gets in the middle between mouse and the feature so the condition of feature being hovered is no more fulfilled. How can I solve it? I want the pop up to be displayed when the mouse is over the feature, no matter if the popup is in the way.
I think it can be replicated even with example code: http://openlayers.org/dev/examples/light-basic.html .
It happens even if my mouse is not directly over the white part of the popup.
It seems to me the problem is more severe in chrome than in firefox. Maybe this is not the problem of my code, but bug. If so, sorry for posting here.

I am using foollowing code :
    layer = new OpenLayers.Layer.Vector("JOSM", {
                eventListeners: {
                    'featureselected': function(evt) {

                        var feature = evt.feature;
                        var detailsTextHtml = "";
                        var lines = feature.attributes.evaluations.split("\n");
                        for (var i = 0; i < lines.length; i++) {
                            if (lines[i] !== "") {
                                detailsTextHtml += "
 " + lines[i];
                            }
                        }
                        popup = new OpenLayers.Popup.FramedCloud("popup",
                                OpenLayers.LonLat.fromString(feature.geometry.getVertices()[0].toShortString()),
                                null,
                                "
Coefficient: " + feature.attributes.coefficient + "
Color:" + feature.attributes.color + "
Details: " + detailsTextHtml + "
",
                                null,
                                true
                                );
                        feature.popup = popup;
                        map.addPopup(popup);
                    },
                    'featureunselected': function(evt) {
                        var feature = evt.feature;
                        map.removePopup(feature.popup);
                        feature.popup.destroy();
                        feature.popup = null;

                    }
                },
                styleMap: styleMap,
                strategies: [new OpenLayers.Strategy.Fixed()],
                projection: geographic,
                protocol: new OpenLayers.Protocol.HTTP({
                    url: "webresources/getJosmAspectsDetailed?startLon=" + document.getElementById('startLon').value +
                            "&startLat=" + document.getElementById('startLat').value +
                            "&endLon=" + document.getElementById('endLon').value +
                            "&endLat=" + document.getElementById('endLat').value + "&speed=17&comfort=0&quietness=0",
                    format: new OpenLayers.Format.GeoJSON()
                })
            });


text:
Q: Peticiones a Swagger Buenos días, estoy haciendo una web que realice conexiones a una base de datos Velneo, haciendo uso de Swagger.
He conseguido realizar consultar a la base de datos del siguiente modo:
var xmlhttp = new XMLHttpRequest();

xmlhttp.open("GET", $urlEnvio, false);

xmlhttp.setRequestHeader("accept" ,"application/json");
xmlhttp.setRequestHeader("content-type" ,"application/json");

xmlhttp.send( JSON.stringify($datos) );

alert(xmlhttp.response);

donde $urlEnvio es la url que conecta con Swagger, y la variable datos contiene los datos provenientes de un formulario.
El problema es que no se como aplicarle filtros a la búsqueda, por ejemplo que me saque los usuarios cuyo nombre sea uno.
Alguien me puede orientar? Muchas gracias por adelantado.


text:
Q: C#, TreeView, adding nodes to node but count = zero I have this peculiar problem, where I am adding nodes to nodes in a treeview.
It is something about making a explorer-like directory tree from my HD, and instead of loading all directories at once, I only do one 'level'. When clicked to expand, the next 'level' of that particulary folder is loaded.
        DirectoryInfo di = new DirectoryInfo(par_path);
        foreach (DirectoryInfo d in di.GetDirectories())
        {
            tn_work = new TreeNode();
            tn_work.Text = d.Name;
            tn_work.ImageIndex = 0;
            tn_work.SelectedImageIndex = 0;
            par_treenode.Nodes.Add(tn_work);
            if (par_treenode.Text == "Visual Studio")
                in_test = par_treenode.Nodes.Count;
         }

I call this for each 'step' in making the tree for i.e. this path: "G:\Visual Studio\Projects\Project1\Work".
Meaning, first I call for "G:\Visual Studio", and this procedure loads up all folders in "Visual Studio" folder. Then I call for "G:\Visual Studio\Projects\" and it loads up all folders in the 'Projects'-folder, etc.
The 'par_treenode' is the treenode which is expanding as I go down the path. The nodes should look like this:
C:
--Visual Studio
----Projects
------Project1
--------Work
However, it does not! The folder 'Visual Studio' is added fine, but it has no nodes under it.
The problem is, that if I stop to debug this program at the 'if (par_treenode.Text == "Visual Studio")'-sentence, the node 'Visual Studio' says clearly it has 14 nodes under it. And the program works: Unfolds the entire path as it should.
But if I run it without stopping it, it has none. And the test-field I added to confirm this ('in_test = par_treenode.Nodes.Count;'), is zero.
Since stopping the program in debug-mode makes it work, it is obvious that something is going too fast. It has somehow not finished making the nodes before I ask for the count.
I have tried a wait-procedure, i have tried                     treeview1.EndUpdate(), treeview1.Refresh(); nothing.
What can I do?


text:
Q: How to solve StackOverflowError I have this nextInt method that is giving me a stackoverflow error:
public int nextInt(int a){
        int n = rand.nextInt(a);
        return n;
    }

And is called by this line of code:
int index = rnd.nextInt(Words.size());

I understand why it's giving the error but I don't know how to fix it. I have a similar method in a different program that doesn't give me the error:
public int nextInt(int l, int h){
    int n = rand.nextInt(h - l + 1) + l;
    return n;
}

Which is being called by this line of code:
System.out.println(rand.nextInt(10,20)); //prints random num between 10 and 20 inclusive

Any helpful pointers would be great!

A: first you need to define the random object on that scope also or if you are defining random object else  then declare it global
you need to do like htis
public int nextInt(int a){

 // create random object
  Random rand = new Random();

 // check next int value
  int n = rand.nextInt(a);
  return n;
}

A: According to me recursion is not happening(infact, it seems to be the case of method overloading) in the below scenario:
public int nextInt(int l, int h){
    int n = rand.nextInt(h - l + 1) + l;
    return n;
}

because the nextInt method has two parameters while at int n = rand.nextInt(h - l + 1) + l; you are invoking nextInt with one parameter only.
Whereas in first scenario, nextInt method has only one parameter and within this method , you are doing recursive calls to the same nextInt method with single parameter.


text:
Q: Pass 2 tables as parameters inside cursor I'm basically trying to execute the same procedure on multiple columns of some tables. I have the procedure, and the cursor statements that access each column, but I cannot pass my tables to the cursor as variables:
Code:
DECLARE @columnName varchar(200),
 @Table1 TABLE(
        [Code] [nvarchar](50) NOT NULL,
        [Name] [nvarchar](255) NOT NULL,
        [Value1] [nvarchar](50) NOT NULL,
        [Value2] [nvarchar](50) NOT NULL,
        [Value3] [nvarchar](50) NOT NULL
    ),
 @Table2 TABLE(
        [Code] [nvarchar](50) NOT NULL,
        [Name] [nvarchar](255) NOT NULL,
        [Value1] [nvarchar](50) NOT NULL
        [Value2] [nvarchar](50) NOT NULL,
        [Value3] [nvarchar](50) NOT NULL
    )
INSERT @Table1 EXEC ProcedureThatAddsData;
INSERT @Table2 EXEC ProcedureThatAddsData;
DECLARE col_cursor CURSOR FOR

select c.name from sys.tables t inner join sys.columns c on t.object_id = c.object_id where t.name = 'MySpecificTable'

OPEN col_cursor

FETCH NEXT FROM col_cursor
INTO @columnName

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @columnName
    --BEGIN BODY
    DECLARE @sql nvarchar(4000)

    set @sql = '
    INSERT INTO MySavedDifferencesTable
    select t1.Code, t1.Name, t1.'+ @columnName +' as OldValue, t2.'+ @columnName +' as NewValue
    from '+@Table1+' t1
    join '+@Table2+' t2
        on  t1.Code = t2.Code
        and t1.Name = t2.Name
        WHERE ISNULL(t1.' + @columnName +','') != ISNULL(t2.' + @columnName +','')
    ';
    exec (@sql)

    --end BODY
    FETCH NEXT FROM col_cursor
    INTO @columnName
END
CLOSE col_cursor;
DEALLOCATE col_cursor;

How can I make this procedure to work. The column selection in cursor is working, so @columnName will iterate through all the columns present in MySpecificTable, but I'm having trouble passing the 2 table variables inside the cursor(for loop?).
Edit:
This is the part that I'm trying to add to my cursor:
@Table1 TABLE(
            [Code] [nvarchar](50) NOT NULL,
            [Name] [nvarchar](255) NOT NULL,
            [Value1] [nvarchar](50) NOT NULL,
            [Value2] [nvarchar](50) NOT NULL,
            [Value3] [nvarchar](50) NOT NULL
        ),
     @Table2 TABLE(
            [Code] [nvarchar](50) NOT NULL,
            [Name] [nvarchar](255) NOT NULL,
            [Value1] [nvarchar](50) NOT NULL
            [Value2] [nvarchar](50) NOT NULL,
            [Value3] [nvarchar](50) NOT NULL
        )
    INSERT @Table1 EXEC ProcedureThatAddsData;
    INSERT @Table2 EXEC ProcedureThatAddsData;

Either declare temporary table variables and insert data into them inside the cursor, or somehow pass outside already full of data temporary tables inside the cursor.

A: What I ended up doing was to create a temporary table
-- check if temporary table already exists
    -- if not create it
    IF OBJECT_ID('tempdb..#MyTempTable') IS NULL
    begin
    --table with same columns as snapshot table to insert current data
    --MyTempTable
        CREATE TABLE #MyTempTable(
        [Code] [nvarchar](50) NOT NULL,..
    )
    end

    --remove old data if it exists from the temporary MyTempTable table
    delete from #MyTempTable;
    --insert the current data into the temporary MyTempTable table
    INSERT #SSDEStudySpecific EXEC procThatinsertsData;

And now I updated the sql that gets executed inside of my cursor like:
set @sql = '
    INSERT INTO MySavedDifferencesTable
    select t1.Code, t1.Name, t1.'+ @columnName +' as OldValue, t2.'+ @columnName +' as NewValue
    from '+#MyTempTable1+' t1
    join SomeSystemTable t2
        on  t1.Code = t2.Code
        and t1.Name = t2.Name
        WHERE ISNULL(t1.' + @columnName +','') != ISNULL(t2.' + @columnName +','')
    ';


text:
Q: Invalid URI when Connecting Visual Studo to Source Control When connecting to Source Control (Azure Devops) for a pull requesgt in Visual Studio (16.4.3), several of us are receiving the error "Invalid URI: The URI scheme is not valid."
enter image description here
This started after our company switched us from one domain to another domain. For example:
from \Company1\myuser
to \COMP2\myuser
To date, we've tried restoring the Windows 10 computers (which uninstalled most software) and deleting our own profiles.
We are using the GIT integration.
I'm including the stack trace.
System.UriFormatException: Invalid URI: The URI scheme is not valid.
   at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
   at System.Uri..ctor(String uriString)
   at Microsoft.TeamFoundation.Git.Provider.PullRequestCreation.PullRequestCreatePageViewModel.Initialize(Object sender, PageInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.TeamExplorerPageBase.InitializeViewModel(PageInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.TeamExplorerPageBase.Initialize(Object sender, PageInitializeEventArgs e)
   at Microsoft.TeamFoundation.Git.Controls.GitTeamExplorerPageBase.Initialize(Object sender, PageInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.Framework.TeamExplorerPageHost.Initialize(TeamExplorerPageContext context)

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.TeamFoundation.Git.Provider.PullRequestReview.ReviewDescriptionSectionViewModel.Initialize(Object sender, SectionInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.TeamExplorerSectionBase.InitializeViewModel(SectionInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.TeamExplorerSectionBase.Initialize(Object sender, SectionInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.Framework.TeamExplorerSectionHost.Initialize(Object context)

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.TeamFoundation.Git.Provider.PullRequestCreation.PullRequestCommitsSectionViewModel.Initialize(Object sender, SectionInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.TeamExplorerSectionBase.InitializeViewModel(SectionInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.TeamExplorerSectionBase.Initialize(Object sender, SectionInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.Framework.TeamExplorerSectionHost.Initialize(Object context)

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.TeamFoundation.Git.Provider.PullRequestShared.PullRequestChangesSectionViewModel.Initialize(Object sender, SectionInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.TeamExplorerSectionBase.InitializeViewModel(SectionInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.TeamExplorerSectionBase.Initialize(Object sender, SectionInitializeEventArgs e)
   at Microsoft.TeamFoundation.Git.Provider.PullRequestShared.PullRequestChangesSection.Initialize(Object sender, SectionInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.Framework.TeamExplorerSectionHost.Initialize(Object context)

A: It's not able to clear server cache if you are using cloud Azure DevOps Service which url should be https://dev.azure.com/xxx or https://xxx.visualstudiaoonline.com.
However, since you have mentioned there is domain changed for your user account. You could give a try with clear local credentials in Visual Studio. Make sure you are using the latest account to connect Visual Studio to Azure DevOps Service.
Some steps may help to clear stored Azure DevOps credentials in Visual Studio 2019:

*

*Remove the Azure DevOps related credentials from Credential Manager

*In Credential Manager add the new updated Generic Credentials for the Azure DevOps account.
Generally, this would overwrite the cached credentials.

*Close all Visual Studio instances, delete
%LOCALAPPDATA%\.IdentityService

*Clear all the browser caches especially for the stored password

*Restart Visual Studio  > Team Explorer > Manage Connections to check
if the Enter credential dialog popup. Just try this several times.
Based on my test the dialog will popup the first time, but if you cancel
it, then you have to restart VS to popup it again.

*Run Visual Studio as another user:
cd C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE
runas /netonly /user:<account> devenv.exe
Enter the user possword, then Team Explorer > Manage Connections


text:
Q: How to setting up the custom size thumbnail for wp_get_attachment_thumb_url()? I made a line of code to display a product category thumbnail on WordPress. The problem is, the size of my thumbnail is 150x150. I need to set in higher dimension. Try to apply thumbnail size but have no result, the thumbnail still 150x150 pixel.
Here my code:
$cat_thumb_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$cat_thumb_url = wp_get_attachment_thumb_url( $cat_thumb_id );

?><img src="<?php if ( $cat_thumb_url ) {
       echo $cat_thumb_url ;
    } else {
       echo mytheme_catch_that_image();
    }
?>" alt="<?php echo $cat->name; ?>"/>

A: I meant you should use wp_get_attachment_image_src() with your $cat_thumb_id. Try this:
$cat_thumb_id  = get_woocommerce_term_meta($cat->term_id, 'thumbnail_id', true);
$cat_thumb     = wp_get_attachment_image_src($cat_thumb_id, 'medium_large');
$cat_thumb_src = $cat_thumb[0] ? esc_url($cat_thumb[0]) : mytheme_catch_that_image();

?><img src="<?php echo $cat_thumb_src; ?>" alt="<?php echo $cat->name; ?>"/>


text:
Q: How can I release the lock file on a DBF after removing its join to a FeatureLayer using ArcObjects? I found another post with two different answers on how to remove the join between a feature layer and a standalone table, but neither method successfully removes the lock file (filename.dbf.COMPUTERNAME.####.####.sr.lock) as viewed in Windows explorer. I'm testing this by creating the join in ArcMap via right-clicking on a feature layer and creating a join through the Joins and Relates context menu item. The join is between a feature class in a personal and/or file geodatabase and a DBF table (not a shapefile). The DBF table is not loaded in the TOC.
Actually, Kirk's method may work but as it's written it produces an exception, and when "fixed" it (RemoveJoins1 below) the code runs but the join remains (and consequently the lock also remains). The other answer (RemoveJoins2 below) that uses IDisplayRelationshipClass successfully removes the join, but the lock file still remains.
Additional info: if I remove the join using the Joins and Relates context menu item and don't remove it using ArcObjects, then the lock file is released. So something in the code sample is causing ArcMap to keep the lock file even though the join is removed.
Any ideas how the lock file can be removed/released?
Public Sub RemoveJoins1(ByVal joinedLayer As IFeatureLayer)
    Dim dTable As IDisplayTable = CType(joinedLayer, IDisplayTable)
    Dim rqTable As IRelQueryTable = TryCast(dTable.DisplayTable, IRelQueryTable)
    If Not rqTable Is Nothing Then
        Debug.Print("source: {0}", CType(rqTable.SourceTable, IDataset).Name)
        Debug.Print("dest: {0}", CType(rqTable.DestinationTable, IDataset).Name)
        joinedLayer.FeatureClass = CType(rqTable.SourceTable, IFeatureClass)
    Else
        Debug.Print("there are no joins")
    End If
End Sub

Public Sub RemoveJoins2(ByVal joinedLayer As IFeatureLayer)
    Dim dTable As IDisplayTable = CType(joinedLayer, IDisplayTable)
    Dim rqTable As IRelQueryTable = TryCast(dTable.DisplayTable, IRelQueryTable)
    If Not rqTable Is Nothing Then
        Debug.Print("source: {0}", CType(rqTable.SourceTable, IDataset).Name)
        Debug.Print("dest: {0}", CType(rqTable.DestinationTable, IDataset).Name)

        Dim drClass As IDisplayRelationshipClass = CType(joinedLayer, IDisplayRelationshipClass)
        Dim rqTableInfo As IRelQueryTableInfo = CType(rqTable, IRelQueryTableInfo)
        drClass.DisplayRelationshipClass(Nothing, esriJoinType.esriLeftInnerJoin)
    Else
        Debug.Print("there are no joins")
    End If
End Sub

A: Thanks to the comment from Hornbydd, I tried using the Geoprocessor to remove the join and the lock file did disappear (see RemoveJoins3). I would still like to understand why the lock file isn't being released using the other methods (and get some input from Kirk Kuykendall on why his method I linked to doesn't work for me). I would also like a solution that doesn't use the Geoprocessor because it's notably slower then the RemoveJoins2 method.
Public Sub RemoveJoins3(ByVal joinedLayer As IFeatureLayer)
    Dim GP As ESRI.ArcGIS.Geoprocessor.Geoprocessor = New ESRI.ArcGIS.Geoprocessor.Geoprocessor()
    Dim removeJoinTool As New ESRI.ArcGIS.DataManagementTools.RemoveJoin
    removeJoinTool.in_layer_or_view = joinedLayer
    GP.Execute(removeJoinTool, Nothing)
End Sub


text:
Q: get separate image of each detected letter I have written this matlab code (given below) for detecting text from an image. This code is detecting the text from the image, but now I want to create an output image for each detected letter from the image. Please tell how can I do that?
Code:
i = imread('text.png');
i1 = i;
imshow(i1);

i2 = edge(i1,'canny',0.3);
imshow(i2);

se = strel('square',2);
i3 = imdilate(i2,se);
imshow(i3);

i4 = imfill(i3,'holes');
imshow(i4);

[Ilabel num] = bwlabel(i4);
disp(num);
Iprops = regionprops(Ilabel);
Ibox = [Iprops.BoundingBox];
Ibox = reshape(Ibox,[4 92]);
imshow(i);

hold on;
for cnt = 1:92
    rectangle('position',Ibox(:,cnt),'edgecolor','r');
end

A: You might want to look at the 'Image' property of regionprops:
Ipops = regionprops(Ilabel, 'Image');

PS,
when calling regionprops it is better to explicitly define the requested properties, otherwise you waste resources computing all properties - includeing those you don't even need.
For instance, your code should look like
Iprops = regionprops(Ilabel, 'BoundingBox');
Ibox = vertcat(Iprops.BoundingBox);  % no need for "reshape" here...


text:
Q: How to pass a Javascript variable into a HTML file I'm new to Javascript and HTML. I have a little problem that I've been trying to fix but don't know how.
I'm trying to pass a variable from a method in a Javascript file into a HTML file, and use its value as if it were HTML code.
I know that the Javascript file is passed correctly into the HTML, the problem is just getting the variable from it.
Here is the relevant Javascript method:
function getCode()  {
    var myCode ="Hello World";
    document.getElementById("myCode").innerHTML = "" + myCode + "";
}

And here is the relevant HTML code:

     myCode

I don't know if I am doing it correct. I simply need the variable myCode to be turned into just HTML code, in other words myCode in the HTML should be turned to "Hello World" at this point:
 myCode

A: When clicking the link, the browser will change the address bar to myCode, because that's what the anchor's href attribute points to.
I'm guessing this is not what you wanted, so you can change the value of the href attribute to something like # to prevent this from happening.

A: Should work just fine, but setting a href value means the anchor redirects when clicking it.
click
 myCode

FIDDLE

A: Here's a JSFiddle that works: http://jsfiddle.net/bGQy5/

    Click me

     Text
        Test

window.getCode = function () {
   var myCode = "Hello World";
   document.getElementById("myCode").innerHTML = "" + myCode + "";
 }

Please note a few issues though:

*

*you are not closing your first  tag, this is not good

*you should be setting a "HREF" tag on your link to make it clickable.

*you need to have the reference to a function (e.g. by attaching it to window or similar)

*you'd be better off using a javascript library, like jquery


text:
Q: Bibliography .bib encoding utf8 (french) accents I am trying to use a bibliography for a my latex report. I am using a .bib file named bibli with articles written in french (so the titles have accents like é or ô). At the beginning of my .tex file I have
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

in order to write accents without using
{'\{e}}

for é in my file. It works just fine for the text in my .tex file. However in my bibliography (bibli.bib) it  doesn't work because it returns "?" instead of any accented letters. Is there a way to corect this without using {'{e}} for each bibliography reference ? I already checked the preferences of my editor (TeXMaker) and the encoding is already UTF-8
Thanks in advance

A: You should use the modern replacement for bibtex: biblatex with its biber backend.
It is fully unicode capable.
If you want to take it one more step further, you might also want to switch to a native unicode-enginge: xelatex or lualatex. You just have to change a few packages in the preamble. The combination of \usepackage[utf8]{inputenc} and \usepackage[T1]{fontenc} has to be replaced by \usepackage{fontspec}.
This package takes care of font and input encoding. All you need are utf8 encoded source files. You can also use every truetype or opentype font.
For language support polyglossia should be preferred to babel.
Here is an example that works both with lualatex and xelatex:
\documentclass{scrartcl}

\begin{filecontents}{references.bib}
   @ARTICLE{test,
     TITLE = {à è ê á é},
     JOURNAL = {des accents},
     YEAR = {2015},
   }
\end{filecontents}

\usepackage{fontspec}
\usepackage{polyglossia}
\setmainlanguage{french}

\usepackage[backend=biber]{biblatex}
\addbibresource{build/references.bib}

\begin{document}
  \cite{test}
  \printbibliography
\end{document}

Compile e.g. with lualatex test.tex, biber test.bcf, lualatex test.tex, lualatex test.tex.
If you want to still use pdflatex, it would look like this:
\documentclass{scrartcl}

\begin{filecontents}{references.bib}
   @ARTICLE{test,
     TITLE = {à è ê á é},
     JOURNAL = {des accents},
     YEAR = {2015},
   }
\end{filecontents}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}

\usepackage[backend=biber]{biblatex}
\addbibresource{build/references.bib}

\begin{document}
  \cite{test}
  \printbibliography
\end{document}

Compile with pdflatex test.tex, biber test.bcf, pdflatex test.tex, pdflatex test.tex

A: It seems a problem that has been around for a while. Particularly I couldn't make both UTF-8 or latin1 to work in my document with Bibtex or Biblatex, either the characters or the bibliography, one or the other, never both. My work around was to keep the bibliography and replace the Latin characters by the Latex equivalent, for example á = \'{a}, however it is quite a lot of work to use the replace command for each accentuation. THE solution was Notepad++, which gratefully allows multiple replacement targeting the specific string:
Find:(good)|(great)|(fine)
Replace: (?1bad)(?2worse)(?3not)
Notepad++ replaces each one with the targeted word!!!
For Brazilian Portuguese in the "Replace" dialog box:
Find:(á)|(Á)|(à)|(À)|(ã)|(Ã)|(â)|(Â)|(é)|(É)|(ê)|(Ê)|(í)|(Í)|(ó)|(Ó)|(ô)|(Ô)|(õ)|(Õ)|(ú)|(Ú)|(ç)|(Ç)
Replace:(?1\'{a})(?2\'{A})(?3\`{a})(?4\`{A})(?5\~{a})(?6\~{A})(?7\^{a})(?8\^{A})(?9\'{e})(?10\'{E})(?11\^{e})(?12\^{E})(?13\'{i})(?14\'{I})(?15\'{o})(?16\'{O})(?17\^{o})(?18\^{O})(?19\~{o})(?20\~{O})(?21\'{u})(?22\'{U})(?23\c{c})(?24\c{C})
Any other language just use the specific characters.
Some details:

*

*In the 'Replace' dialog box check differentiate upper and lower case;

*Select regular expressions;

*For the 'Replace' option, if you change line before the first character, (?1\'{a})..., the replaced characters may also change lines in the text, so copy and paste the options with no line changed;

*Linux users can use Wine to install Notepad++ (it is not working at this time for Notepadqq, the Linux clone).
I hope it helps those that need multiple substitutions for non-English texts, once Notepad++ allows this simultaneously(!!!).
More info in
https://notepad-plus-plus.org/
https://superuser.com/questions/211011/find-and-replace-several-several-different-values-all-at-once
https://stackoverflow.com/questions/11389466/multiple-word-search-and-replace-in-notepad/16104946#16104946


text:
Q: How to get GPS back to show another process? I'm going on with GPS enable and disable service I just got it by the following code
Here is the code:
public class gps extends Activity {
    /** Called when the activity is first created. */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
        }else{
            showGPSDisabledAlertToUser();
        }
    }

    private void showGPSDisabledAlertToUser(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?"
        .setCancelable(false)
        .setPositiveButton("Goto Settings Page To Enable GPS",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent callGPSSettingIntent = new Intent(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(callGPSSettingIntent);
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                dialog.cancel();
            }
        });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
}

I used this process for my google maps activity to enable and disable GPS if i goes to setting page after switch on GPS it call backs on onResume method.
Once it come to map it should show another alertdialog message if I call the method on onResume the app chrases.
Here is another alert mess code:
public class gps extends Activity {
    /** Called when the activity is first created. */
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
showAlert();
        }else{
            showGPSDisabledAlertToUser();
        }
    }

Public void showAlert()
{
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
Map.this);

// set title
alertDialogBuilder.setTitle(R.string.app_name);

// set dialog message
alertDialogBuilder.setTitle("Maps"
.setMessage("Can we use your location "
.setCancelable(false)
.setPositiveButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// MY CONTENT
}
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// MY CONTENT
}

For this a lot with internet to fix but I can't if some have any idea about this please help me friend.
Here is the logcat
java.lang.NullPointerException
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2826)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2859)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2274)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.app.ActivityThread.access$800(ActivityThread.java:139)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.os.Handler.dispatchMessage(Handler.java:102)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.os.Looper.loop(Looper.java:136)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.app.ActivityThread.main(ActivityThread.java:5102)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at java.lang.reflect.Method.invokeNative(Native Method)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at java.lang.reflect.Method.invoke(Method.java:515)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at dalvik.system.NativeStart.main(Native Method)
07-11 16:35:41.978: E/AndroidRuntime(3841): Caused by: java.lang.NullPointerException
07-11 16:35:41.978: E/AndroidRuntime(3841):     at com.hubino..Map.onResume(Map.java:392)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1215)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.app.Activity.performResume(Activity.java:5327)
07-11 16:35:41.978: E/AndroidRuntime(3841):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2811)
07-11 16:35:41.978: E/AndroidRuntime(3841):     ... 12 more


text:
Q: Google Sheet Script conditionally set value of blank cells to today's date but leave existing data the same I am stumped with what is probably a simple problem.
I have a column of data, J, that has a date in some of the cells, but not all.  If the cell is blank, I need to write today's date in that cell.
Here is what I have so far:
var event=[];
var date= new Date();

for (event=1; event< destSheet.length; event ++){
    if (destSheet[event][10]<1){
        [event][10]=date;
  }
  }

No errors are returned, it simply does not write in a date (I will worry about format later). What have I done wrong?

A: You probably need something like the following code.  The code builds a 2 dimensional array to overwrite existing data with the same data, and put a new date in cells that are blank.
function xyz() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = ss.getSheetByName("Sheet1");

  //getRange(start row, start column, numRows, number of Columns)
  var rangeData = sourceSheet.getRange(2,1, sourceSheet.getLastRow()-1, 1);

  var dataFromSheet = rangeData.getValues();
  var date= new Date();

  var i=0,
      thisCellValue,
      innnerArray = [],
      outerArray = [];

  for (i=0; i< dataFromSheet.length; i+=1){
    thisCellValue = dataFromSheet[i];

    if (thisCellValue === ""){
      innnerArray.push(date);
      outerArray.push(innnerArray);
    } else {
      innnerArray.push(thisCellValue); //To overwrite original data with the same data
      outerArray.push(innnerArray);
    };
  };

  sourceSheet.getRange(2,1, outerArray.length, innerArray[0].length).setValues(outerArray);
};


text:
Q: How can I remove my bios password? I need to install windows 10 from bios with usb stick, i tried many ways to crack bios password but it didn't work.
My computer: Casper Nirvana NB
note: I have a laptop

A: You can google for a some kind of master password, but there's a way that works for 100% which is a bit harder to do on a laptop:
Theres a small battery on the mainboard that makes it possible to store all settings and configurations.
Remove it and wait some seconds, so it completely resets the mainboard settings (including the set up password). Then insert the battery again and you can Install Windows.


text:
Q: Post are not showing up The site I am working on is skinnnybantonmusic.com
The Lastest News page is suppost to show the blog posts but for some reason none are showing up. (http://www.skinnybantonmusic.com/latest-news/)
<?php get_header(); ?>

    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

        <div <?php post_class() ?> id="post-<?php the_ID(); ?>">

        <?php if ( has_post_thumbnail() ) : ?>
            <a href="<?php the_permalink(); ?>">
                <?php the_post_thumbnail(); ?>

        <?php endif; ?>

    <?php endwhile; ?>

    <?php include (TEMPLATEPATH . '/inc/nav.php' ); ?>

    <?php else : ?>

Not Found

    <?php endif; ?>

<?php get_footer(); ?>

A: The reason is that its not showing up
 <?php if ( has_post_thumbnail() ) : ?>
        <a href="<?php the_permalink(); ?>">
            <?php the_post_thumbnail(); ?>

 <?php endif; ?>

You are displaying just a link with check that is featured image exists or not
It seems, your post doesn't have featured image, select any featured image or just remove that check from it, as i can't see any need of it.
So your code will be :
<?php get_header(); ?>

    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
            <a href="<?php the_permalink(); ?>">
                <?php the_post_thumbnail(); ?>

    <?php endwhile; ?>
    <?php include (TEMPLATEPATH . '/inc/nav.php' ); ?>
    <?php else : ?>

Not Found

    <?php endif; ?>

<?php get_footer(); ?>

A: Yes if you want to show thumbnail in that case you need to change this code and remove if condition and use the_post_thumbnail(); directly.


text:
Q: How can I only redirect to USA App store via iTunes URL address? Let's say there is an app called, Mega Jump.
This one is available on All country App Store.
here is the iTunes address for USA store.
http://itunes.apple.com/us/app/mega-jump/id370398167?mt=8
If a Canadian clicks this address on iPhone, it redirects to Canadian App Store.
I am sure that Canadians have USA store account too.
Therefore, I would like to force them to USA store via iTunes url link to increase USA sales.
Is there a way to do this?
Thank you.

A: You cannot link to and open a specific storefront for a user.  A user only has one storefront per account.  If the user has more than one account, as you may or may not have assumed correctly, whichever storefront the user has last used is the store a link will attempt to open the content in.

A: the URL of iTunes normally has the country code in this way:
https://itunes.apple.com/be/album/

Thus it's sufficeint to preform the URL on that way and you are safe.
You can also use the URL without the country code after the domain, and adding it  as argument by writing &cc=it for italy or &cc=gb for UK etc, for instance
https://itunes.apple.com/be/album/...../id......&cc=it

on purpose I put the dots instead of the title of the song and the figures of th song ID to avoid advertising


text:
Q: Python interpreter completely skips function asking for user input? At first I had Choice = input("Do you " + colored("run ", 'blue')+"or " + colored("attack? ", 'blue') + "") and everything worked fine, user could do input and code continued as normal. However, I wanted to change this to a function so I now have
def func(Choice):
  input("Do you " + colored("run ", 'blue')+"or " + colored("attack? ", 'blue') + "") and the python interpreter completely skips over the function and doesn't ask for input. I'm relatively new to python so I apologize if I did something stupid but I couldn't find any answers online. The version is 3.5.2 by the way.

A: You seem to be a bit confused.  You need to call the function in order for it to be executed.  When the interpreter encounters the def statement it makes a function according to the definition.  It will never be executed unless you call it.  You want something like:
def func():
    choice = input("Do you " + colored("run ", 'blue')+"or " +
       colored("attack? ", 'blue') + "")
    return choice

Whenever you want the user's input, you write
choice = func()

or something similar.  The variable doesn't need to have the same name in both places.


text:
Q: Fastest way to trim a string and convert it to lower case I've written a class for processing strings and I have the following problem: the string passed in can come with spaces at the beginning and at the end of the string.
I need to trim the spaces from the strings and convert them to lower case letters. My code so far:
var searchStr = wordToSearchReplacemntsFor.ToLower();
        searchStr = searchStr.Trim();

I couldn't find any function to help me in StringBuilder. The problem is that this class is supposed to process a lot of strings as quickly as possible.  So I don't want to be creating 2 new strings for each string the class processes.
If this isn't possible, I'll go deeper into the processing algorithm.

A: Cyberdrew has the right idea.  With string being immutable, you'll be allocating  memory during both of those calls regardless.  One thing I'd like to suggest, if you're going to call string.Trim().ToLower() in many locations in your code, is to simplify your calls with extension methods.  For example:
public static class MyExtensions
{
    public static string TrimAndLower(this String str)
    {
        return str.Trim().ToLower();
    }
}

A: Here's my attempt.  But before I would check this in, I would ask two very important questions.

*

*Are sequential "String.Trim" and "String.ToLower" calls really impacting the performance of my app? Would anyone notice if this algorithm was twice as slow or twice as fast? The only way to know is to measure the performance of my code and compare against pre-set performance goals.  Otherwise, micro-optimizations will generate micro-performance gains.

*Just because I wrote an implementation that appears faster, doesn't mean that it really is.  The compiler and run-time may have optimizations around common operations that I don't know about. I should compare the running time of my code to what already exists.
static public string TrimAndLower(string str)
{

    if (str == null)
    {
        return null;
    }

    int i = 0;
    int j = str.Length - 1;
    StringBuilder sb;

    while (i < str.Length)
    {
        if (Char.IsWhiteSpace(str[i])) // or say "if (str[i] == ' ')" if you only care about spaces
        {
            i++;
        }
        else
        {
            break;
        }
    }

    while (j > i)
    {
        if (Char.IsWhiteSpace(str[j])) // or say "if (str[j] == ' ')" if you only care about spaces
        {
            j--;
        }
        else
        {
            break;
        }
    }

    if (i > j)
    {
        return "";
    }

    sb = new StringBuilder(j - i + 1);

    while (i <= j)
    {
        // I was originally check for IsUpper before calling ToLower, probably not needed
        sb.Append(Char.ToLower(str[i]));
        i++;
    }

    return sb.ToString();
}

A: Try method chaining.
Ex:
var s = " YoUr StRiNg".Trim().ToLower();

A: If the strings use only ASCII characters, you can look at the C# ToLower Optimization.  You could also try a lookup table if you know the character set ahead of time

A: So first of all, trim first and replace second, so you have to iterate over a smaller string with your ToLower()
other than that, i think your best algorithm would look like this:

*

*Iterate over the string once, and check

*

*whether there's any upper case characters

*whether there's whitespace in beginning and end (and count how many chars you're talking about)

*if none of the above, return the original string

*if upper case but no whitespace: do ToLower and return

*if whitespace:

*

*allocate a new string with the right size (original length - number of white chars)

*fill it in while doing the ToLower

A: You can try this:
  public static void Main (string[] args) {
    var str = "fr, En, gB";
    Console.WriteLine(str.Replace(" ","").ToLower());
  }


text:
Q: How to get the Message headers in a consumer Using the new function based programming model of Spring Cloud Stream I need to have access to some of the headers of the message I consume. I figured I would consume Message<MyDto> instead of only MyDto, but if I do this MyDto properties are all null.
This is in broad strokes what I want to do :
@ToString
@Getter
@Setter
public class MyDto {
   private OtherDto otherDto;
}

@Bean
public Consumer<Message<MyDto>> onRawImport() {
    message -> logger.info("Received {}", message.getPayload());  // <-- prints "Received MyDto(otherDto=OtherDto(...))"
}

whereas the following works perfectly in my configuration
@Bean
public Consumer<MyDto> onRawImport() {
    myDto -> logger.info("Received {}", myDto);  // <-- "Received MyDto(otherDto=null)"
}

Is there a simple way to consume Message directly ?

Addendum :
If I turn DEBUG on for org.springframework.cloud.function.context.catalog i see this with Consumer<MyDto> :
BeanFactoryAwareFunctionRegistry : Applying function: onRawImport
BeanFactoryAwareFunctionRegistry : Applying type conversion on input value GenericMessage [payload=byte[288], headers=...snip...]
BeanFactoryAwareFunctionRegistry : Function type: java.util.function.Consumer<MyDto>
BeanFactoryAwareFunctionRegistry : Raw type of value: GenericMessage [payload=byte[288], ...snip...}] is class MyDto
BeanFactoryAwareFunctionRegistry : Converted from Message: MyDto(otherDto=OtherDto(...))
BeanFactoryAwareFunctionRegistry : Converted input value MyDto(otherDto=OtherDto(...))
MyOwnListener : Received MyDto(id=5, message=test)

and this with Consumer<Message<MyDto>>
BeanFactoryAwareFunctionRegistry : Applying function: onRawImport
BeanFactoryAwareFunctionRegistry : Applying type conversion on input value GenericMessage [payload=byte[288], headers=...snip...]
BeanFactoryAwareFunctionRegistry : Function type: Function type: java.util.function.Consumer<org.springframework.messaging.Message<MyDto>>
BeanFactoryAwareFunctionRegistry : Raw type of value: GenericMessage [payload=byte[288], ...snip...}] is class MyDto
BeanFactoryAwareFunctionRegistry : Converted from Message: MyDto(otherDto
=null)
BeanFactoryAwareFunctionRegistry : Converted input value MyDto(otherDto
=null)
MyOwnListener : Received MyDto(otherDto
=null)

A: Which version are you using? I just tested it with Boot 2.4.4, cloud 2020.0.2 and it works fine...
@SpringBootApplication
public class So66990612Application {

    public static void main(String[] args) {
        SpringApplication.run(So66990612Application.class, args);
    }

    @Bean
    Consumer<Message<Foo>> input() {
        return System.out::println;
    }

    @Bean
    public ApplicationRunner runner(RabbitTemplate template) {
        return args -> {
            template.convertAndSend("input-in-0", "x", "{\"bar\":\"baz\"}",
                    msg -> {
                        msg.getMessageProperties().setContentType("application/json");
                        return msg;
                    });
        };
    }

    public static class Foo {

        private String bar;

        public String getBar() {
            return this.bar;
        }

        public void setBar(String bar) {
            this.bar = bar;
        }

        @Override
        public String toString() {
            return "Foo [bar=" + this.bar + "]";
        }

    }

}

GenericMessage [payload=Foo [bar=baz], headers={amqp_receivedDeliveryMode=PERSISTENT, amqp_receivedExchange=input-in-0, amqp_deliveryTag=1, deliveryAttempt=1, amqp_consumerQueue=input-in-0.anonymous.Uh_s89lKRnKeJ3ls991pXA, amqp_redelivered=false, amqp_receivedRoutingKey=x, amqp_contentEncoding=UTF-8, id=1a848cf6-3f85-c017-fa70-d52f43c0fc67, amqp_consumerTag=amq.ctag-w6ZyXBGOtC-q7rCY8Jy-gA, sourceData=(Body:'{"bar":"baz"}' MessageProperties [headers={}, contentType=application/json, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=input-in-0, receivedRoutingKey=x, deliveryTag=1, consumerTag=amq.ctag-w6ZyXBGOtC-q7rCY8Jy-gA, consumerQueue=input-in-0.anonymous.Uh_s89lKRnKeJ3ls991pXA]), contentType=application/json, timestamp=1617888626028}]


text:
Q: Historical Hurricane data I am searching for a data source on past hurricanes that includes the coordinates of the path at different times including wind speed pressure and category. Any other added data would also be helpful.

A: http://weather.unisys.com/hurricanes
It has got data from 1851 to 2017 it has:

*

*time

*lat-long

*wind

*pressure

or https://www.data.gov/disasters/hurricanes/
it has storm surges, heavy rainfall, high winds, tornadoes, rip currents, and flooding.
or https://www.wunderground.com/hurricane/hurrarchive.asp
or https://www.climate.gov/maps-data/dataset/historical-hurricane-tracks-gis-map-viewer
https://toolkit.climate.gov/tool/historical-hurricane-tracks

A: I would suggest the NOAA GIS data portal.  There are lots of resources and links on the page.

A: You can find such data at the "International Best Track Archive for Climate Stewardship (IBTrACS)" https://www.ncdc.noaa.gov/ibtracs/index.php?name=ibtracs-data
This includes much more than just hurricanes.


text:
Q: Configure Cake 2.x to use a different database for Sessions Cake 1.x had a configuration option which allowed for Session.database so that a completely different machine/database could be used for the session table. In Cake 2.0 the default core.php configuration file appears to no longer have that option.
Is this still possible without writing a custom session handler?
/**
 * Session configuration.
 *
 * Contains an array of settings to use for session configuration. The defaults key is
 * used to define a default preset to use for sessions, any settings declared here will override
 * the settings of the default config.
 *
 * ## Options
 *
 * - `Session.cookie` - The name of the cookie to use. Defaults to 'CAKEPHP'
 * - `Session.timeout` - The number of minutes you want sessions to live for. This timeout is handled by CakePHP
 * - `Session.cookieTimeout` - The number of minutes you want session cookies to live for.
 * - `Session.checkAgent` - Do you want the user agent to be checked when starting sessions? You might want to set the
 *    value to false, when dealing with older versions of IE, Chrome Frame or certain web-browsing devices and AJAX
 * - `Session.defaults` - The default configuration set to use as a basis for your session.
 *    There are four builtins: php, cake, cache, database.
 * - `Session.handler` - Can be used to enable a custom session handler.  Expects an array of of callables,
 *    that can be used with `session_save_handler`.  Using this option will automatically add `session.save_handler`
 *    to the ini array.
 * - `Session.autoRegenerate` - Enabling this setting, turns on automatic renewal of sessions, and
 *    sessionids that change frequently. See CakeSession::$requestCountdown.
 * - `Session.ini` - An associative array of additional ini values to set.
 *
 * The built in defaults are:
 *
 * - 'php' - Uses settings defined in your php.ini.
 * - 'cake' - Saves session files in CakePHP's /tmp directory.
 * - 'database' - Uses CakePHP's database sessions.
 * - 'cache' - Use the Cache class to save sessions.
 *
 * To define a custom session handler, save it at /app/Model/Datasource/Session/<name>.php.
 * Make sure the class implements `CakeSessionHandlerInterface` and set Session.handler to <name>
 *
 * To use database sessions, run the app/Config/Schema/sessions.php schema using
 * the cake shell command: cake schema create Sessions
 *
 */

A: From my own staff:
"
Ok, so the way seems to be to create a custom "session handler" model. Use the setting like this:
Configure::write('Session.handler.model', 'CustomSession');

where the CustomSession.php model file has the configs. 'sessions' is a config I added to my config/database.php file:
<?php
class CustomSession extends AppModel {
    var $useDbConfig = 'sessions';
    var $useTable = 'cake_sessions';
}

"Unfortunately, the Cake documentation on this feature is terrible. The cake Session.handler, which actually defines the behavior of Session, is different than the Cake Session.handler.model. By default, the handler.model is AppModel (In Cake internals, see lib/Cake/Model/Session/DatabaseSession.php line 48 __construct() function - where it instantiates $this->_model. If you don't set a custom model, it will instantiate to AppModel. Try putting in a debug to see it in action.) The sparse documentation I linked to explains it as
The above will tell CakeSession to use the built in 'database' defaults, and specify that a model called CustomSession will be the delegate for saving session information to the database.
Also, see http://api20.cakephp.org/class/database-session _model property: "Reference to the model handling the session data"
So that's how/why it works....
-AWD"


text:
Q: Perform traceroute with specific outgoing IP My server has multiple /24 subnets added via network-script files ifcfg-eth0-range0
Now one /24 subnet has connection issues and I need to perform a traceroute to see what's wrong.
How can I have my server using one of those IPs as outgoing IP address when doing a traceroute?

A: I imagine your subnets are assigned to (virtual) interfaces and that you want the trace to go through one of these.
The traceroute has an option for this. Check out the man page - you just do this to force the trace to proceed through a specific interface:
traceroute -i <interface> <host>

If this doesn't work, out can add a specific route to the host you want to trace via the gateway you want. Do:
route add -host <host> gw <gw>

Then do the traceroute - and don't forget to delete the route (if you don't need it anymore):
route del -host <host> gw <gw>

Hope it helps.

A: I know this is very old but you can accomplish what you need by using:
traceroute -s source_IP (the ip on that specific interface) destination


text:
Q: SQLException when Canceling Async Query Using the new .Net 4.5 Async/Await functionality with a CancellationToken, I get a SQLException when I cancel a ExecuteNonQueryAsync call, instead of a OperationCanceledException (or some other exception that is specific to canceling an operation).  The SQLException does say Operation cancelled by user at the end of the message.  I expected a more specific exception to be thrown when canceling the operation.  Additionally, how would I create the appropriate Try/Catch handlers to deal with this expected scenario?  I normally would have the SQLException as more general failure block, but now I would have to tease out the text of the message to see if this just the user clicking the Cancel button!?  I must be missing something.
Here's a simple VB WinForm app that has two buttons, one to do the Async call, and the other to cancel.  The Try/Catch in the 1st button shows the SQLException that is hit when the 2nd button calls the Cancel method.
Dim _cts As CancellationTokenSource
Private Async Sub btnLocalTest_Click(sender As Object, e As EventArgs) Handles btnLocalTest.Click
    _cts = New CancellationTokenSource()
    Dim CancelToken As CancellationToken = _cts.Token
    Using sconn As New SqlConnection("server=(local);database=MyDB;user id=MyUser;password=MyPassword")
        sconn.Open()
        Dim SQL As String = some long running SELECT or INSERT statement
        Try
            Using scmd As New SqlCommand(SQL, sconn)
                scmd.CommandTimeout = 300
                Dim i As Integer = Await scmd.ExecuteNonQueryAsync(CancelToken)
            End Using
        Catch exCancel As OperationCanceledException
            LogEvent("Query canceled Exception.") ' This error is *not* thrown on Cancel.
        Catch ex As SqlClient.SqlException
            LogEvent("Error with query. " & ex.Message)  ' This error *is* thrown on Cancel.  Message includes text 'Canceled by user.'
        End Try
        sconn.Close()
        _cts = Nothing
    End Using
End Sub

Private Sub btnLocalTestCancel_Click(sender As Object, e As EventArgs) Handles btnLocalTestCancel.Click
    If _cts IsNot Nothing Then
        _cts.Cancel()
    End If
End Sub

UPDATE: I created a different Async test with the HttpClient.GetAsync method that supports cancellation.  When you cancel that task, you can the OperationCanceledException exception that I originally expected above.  So the question remains: what exception should you get when you cancel an Async task?  Or is that dependent upon each method and it's implementation?

A: I "solved" this issue by checking CancelToken.IsCancellationRequested in the Catch ex As SqlClient.SqlException block.

A: It is not always as simple as catching an SqlException. If you use Task.Wait() on the asynchronous task then the SqlException will be wrapped inside an AggregateException.
A code example that demonstrates this can be found in the ADO.NET section on MSDN, in the article Asynchronous Programming (section "Cancelling an Asynchronous Operation").
Documentation for a similar behaviour that is general for the Task class is buried in the MSDN article Task Cancellation (part of the "Task Parallel Library" documentation), although here the AggregateException wraps a TaskCanceledException (which is derived from OperationCanceledException).
Here is a somewhat simplified piece of C# code that shows how I am currently handling cancellation requests with SqlClient:
class MyDataProcessor
{
    void ReadSomething(CancellationToken cancellationToken)
    {
        try
        {
            // Get the command from somewhere
            DbCommand dbCommand = [...]

            // We don't use await, we manage the Task ourselves
            Task<DbDataReader> task = dbCommand.ExecuteReaderAsync(cancellationToken)
            // If cancellation is requested this throws an AggregateException
            task.Wait();

            // Task status should probably be checked here,
            // but this is just sample code
            DbDataReader dbDataReader = task.Result;

            // If cancellation is requested, this throws a straight SqlException
            while (dbDataReader.Read())
            {
                // do something with the data

                // Be nice and check the token. ADO.NET data providers
                // other than SqlClient might not check the token.
                cancellationToken.ThrowIfCancellationRequested();
            }
        }
        catch (System.Exception exception)
        {
            // If it's a cancellation request, transform the SqlException
            // into an OperationCanceledException
            ThrowIfSqlClientCancellationRequested(
                cancellationToken, exception);

            // Re-throw if it's a genuine error
            throw;
        }
    }

    void ThrowIfSqlClientCancellationRequested(
        CancellationToken cancellationToken,
        Exception exception)
    {
        // Check the CancellationToken, as suggested by Anton S in his answer
        if (!cancellationToken.IsCancellationRequested)
            return;
        System.Data.SqlClient.SqlException sqlException =
            exception as System.Data.SqlClient.SqlException;
        if (null == sqlException)
        {
            AggregateException aggregateException = exception as AggregateException;
            if (null != aggregateException)
                sqlException = aggregateException.InnerException as System.Data.SqlClient.SqlException;
            if (null == sqlException)
                return;
        }
        // Assume that if it's a "real" problem (e.g. the query is malformed),
        // then this will be a number != 0, typically from the "sysmessages"
        // system table
        if (sqlException.Number != 0)
            return;
        throw new OperationCanceledException();
    }
}

I am not very happy with this, it looks brittle, but lacking any official documentation it's the best I could come up with at the moment. The big questions are:

*

*Will future versions of SqlClient change their cancellation behaviour?

*Are there additional behaviours not covered by the code above?


text:
Q: any feature or webpart in sharepoint 2007 that can show such filter results in sharepoint i have two lists
one list is authors
other list is books
the authors list has one of the fields called authorname. in books list one column is authors . which creating an item in books the authors column is filled by selecting the authorname field of list authors ( lookup )
is there any webpart of feature available in sharepoint server 2007 in which if we select any authorname and do a filter the items in author list with that author name appear and the items in books with that author appear as results.
or a way in which something like this can be developed using sharepoint designer ?
Any help at all will be much appreciated.

A: I may have misundestood your question but this can be done out of the box (OOTB) in all versions of SharePoint using web part connections.
This gives an example (the screenshots are from 2003, but its basically the same in 2007)

*

*Web Part Connections
This example has a list of Building Projects (like your Books list) and a list of Contractors (like your Authors list). Building Projects has a lookup column to the Contractors list.
When you connect the web parts together you are setting up a filter provider (Contractors) and a filter consumer (Building Projects).
So when you click on a particular contractor only the building projects assigned to them are displayed.
Microsoft have a guide to web part Connections - but its a bit of a hard read I think.


text:
Q: Is there a method to set background color and border of annotations text? I need to set background color and border of annotations used for a Google line chart. Is there a solution to do this?

A: Check out HTML tooltips documents on this page: https://developers.google.com/chart/interactive/docs/customizing_tooltip_content

A: No, you can't customize the background color or border of the annotations.  You can make a feature request to add support for it.


text:
Q: JMeter - How to handle Long polling transport request method In my Jmeter script request which contains the 'LongPolling' transport method and it takes a high load time or response time
Also, the response message content value is used for the next consecutive request. How can I handle that scenario?
I don't want this my wait time for the server response

A: JMeter thread model assumes that a thread (virtual user) always waits for the previous sampler to fully complete before starting the new one.

*

*The easiest solution is moving your "long-polling" requests into a separate thread group and if you need to pass data between thread groups either use __setProperty() and __P() functions combination or go for Inter-Thread Communication Plugin

*If you need to have everything within the single Thread Group - you can consider using Parallel Controller, however it might not be fully suitable for your needs as it is still a Sampler hence it waits for all its children completion prior to proceeding

*Depending on your use case you can find jmeter-asynchronous-http plugin useful, see How to Load Test Async Requests with JMeter article for more details if needed.


text:
Q: Prevent state reset I have an application that allows the user to upload photos, to edit them (crop, zoom and rotate) and to download.
I'm trying to add a preview mode, so the user can see how the file he's downloading will look like.
What I did works fine except for one thing - when the user clicks on the Clear Preview button the photos go back to their original state (the state is being reset on Clear Preview button click),
without keeping the changes the user made to them.
Any idea what am I missing and how to prevent the state reset?
export default function ImagesGrid() {
  const classes = useStyles({})
  const {
    photos,
    preparePhotos,
    checkUnusedSuppliedTags,
    usedTagsList,
    suppliedTags
  } = useContext(SitePhotosContext)

  const taggedPhotos = photos.filter(photo => photo.tags.length)
  const pages = Math.ceil(taggedPhotos.length / 6)
  const [isPreviewMode, setIsPreviewMode] = useState(false)
  const [preparedPhotos, setPreparedPhotos] = useState([])
  const renderedPhotos = isPreviewMode ? preparedPhotos : photos
  let countColor: TypographyProps['color'] = 'initial'

  const tags = usedTagsList.concat(
    checkUnusedSuppliedTags(usedTagsList, suppliedTags)
  )

  useEffect(() => {
    preparePhotos(photos).then(photos => setPreparedPhotos(photos))
  }, [photos])

  return (

      <AppBar position="sticky" color="default">
        <Toolbar>
          {!isPreviewMode ? (

              <Typography
                variant="h6"
                color={countColor}
                className={classes.pageCount}
              >
                {`${taggedPhotos.length} Tagged Photos / ${pages} Pages`}
              </Typography>
              {taggedPhotos.length === 0 && (
                <Typography
                  variant="body2"
                  color={countColor}
                  className={classes.instructions}
                >
                  Tag some photos to generate a report
                </Typography>
              )}

          ) : (
            <DownloadPreflightModal
              photos={preparedPhotos}
              usedTagsList={usedTagsList}
            />
          )}
          <DownloadAndPreview
            isPreviewMode={isPreviewMode}
            setIsPreviewMode={setIsPreviewMode}
            tags={tags}
          />
        </Toolbar>
      </AppBar>
      <Grid
        container
        justify="flex-start"
        spacing={2}
        className={classes.imageGrid}
      >

        {renderedPhotos.map(photo => (
          <Grid
            item
            xs={12}
            sm={6}
            md={isPreviewMode ? 6 : 4}
            key={photo.id}
            className={isPreviewMode ? classes.imageInternalGrid : ''}
          >
            <Image photo={photo} mode={isPreviewMode ? 'preview' : 'editor'} />
          </Grid>
        ))}
      </Grid>

  )
}

DownloadAndPreview component:
export default function DownloadAndPreview({
  isPreviewMode,
  setIsPreviewMode,
  tags
}) {
  const classes = useStyles({})
  const generatorRef = useRef()
  const {photos} = useContext(SitePhotosContext)

  return (
    <>
      {!isPreviewMode ? (
        <Button color="inherit" onClick={() => setIsPreviewMode(true)}>
          Preview
          <VisibilityIcon />
        </Button>
      ) : (

          <Button
            color="inherit"
            onClick={() => setIsPreviewMode(false)}
            className={classes.previewModeBtn}
          >
            Clear Preview
            <ClearIcon />
          </Button>
          <Button
            color="inherit"
            onClick={() => {
              downloadDoc(generatorRef, photos, tags)
            }}
          >
            Download
          </Button>

      )}
    </>
  )
}

<Image /> component:
export default function Image({photo, mode}: {photo: ImageItem; mode: string}) {
  const classes = useStyles({})
  const {
    setImageEditData
  } = useContext(SitePhotosContext)

  return mode === 'editor' ? (
    <Paper>
      {!photo.src && (

Loading {photo.data?.name}...

      )}

        <ImageEditor
          photo={photo}
          onEditComplete={editData => {
            setImageEditData(photo.id, editData)
          }}
        />

    </Paper>
  ) : (

      {photo.tags.join(' / ')}

  )
}

<ImageEditor /> component:
export default function ImageEditor({
  photo,
  onEditComplete,
  showControls
}: editorProps) {
  const classes = useStyles({})
  const [crop, setCrop] = useState({x: 0, y: 0})

  const [rotation, setRotation] = useState(0)
  const [zoom, setZoom] = useState(1)

  const onCropComplete = useCallback(
    (croppedArea, croppedAreaPixels) => {
      const editSettings: editData = {crop: croppedAreaPixels, rotate: rotation}
      onEditComplete(editSettings)
    },
    [rotation, onEditComplete]
  )

  return (
    <>
      <Box className={classes.cropContainer}>
        <Cropper
          image={photo.src}
          aspect={maxImageWidth / maxImageHeight}
          crop={crop}
          rotation={rotation}
          zoom={zoom}
          zoomWithScroll={false}
          onCropChange={setCrop}
          onRotationChange={setRotation}
          onCropComplete={onCropComplete}
          onZoomChange={setZoom}
        />
      </Box>
      {showControls && (
        <Box display="flex" className={classes.controls}>
          <IconButton
            color="primary"
            onClick={() => setRotation(rotation => rotation - 90)}
          >
            <RotateLeftIcon />
          </IconButton>
          <Box display="inline-flex" width="100%">
            <ImageIcon
              fontSize="small"
              color="action"
              className={classes.imageIcon}
            />
            <Slider
              className={classes.slider}
              value={zoom}
              min={1}
              max={3}
              step={0.1}
              onChange={(e, zoom) => setZoom(zoom)}
            />
            <ImageIcon
              fontSize="large"
              color="action"
              className={classes.imageIcon}
            />
          </Box>
          <IconButton
            color="primary"
            onClick={() => setRotation(rotation => rotation + 90)}
          >
            <RotateRightIcon />
          </IconButton>
        </Box>
      )}
    </>
  )
}

context functions:
  const preparePhotos = async (photos: PhotoList) => {
    const res = photos
      .filter(photo => photo.tags.length)
      .sort(sortByPriority)

    if (res.length % 2) res.pop()

    const edittedPhotos = await Promise.all(res.map(editImage))
    return edittedPhotos
  }

  const setImageEditData = (id, editData) => {
    setPhotos(photos =>
      photos.map(photo => {
        if (photo.id === id) {
          return {...photo, editData}
        }
        return photo
      })
    )
  }

  const editImage = async (image: ImageItem) => {
    if (!image.editData) return image
    const {crop, rotate} = image.editData
    const edittedImage = await cropAndRotateImage(image.src, crop, rotate)
    return {
      ...image,
      src: edittedImage,
      dimensions: {width: crop.width, height: crop.height}
    }
  }

Expected behavior is similar to this:
https://codesandbox.io/s/react-easy-crop-custom-image-demo-y09komm059?from-embed=&file=/src/index.js:3141-3151
After the user closes the preview modal the photo stay in the same position it was - before clicking on the preview button. (What by me - it doesn't)

A: Your question still lacks some vital information. But let me guess...

*

*Let's assume that you're using https://github.com/ricardo-ch/react-easy-crop (It's just the first library I came across, but even if you're using another library, I suppose, they mostly work the same way).

*If so, then on every rerender <Cropper> calls onCropComplete. And it rerenders every time you switch into editor-mode.

*On image load react-easy-crop sets crop, rotation and zoom to respective values passed to <Cropper> which you hold in <ImageEditor> component's state.

*But here
function Image(...) {
  ...
  return mode === 'editor' ? ( ... <ImageEditor ... /> ... ) : ( ... )
}

you loose <ImageEditor> component's state on every mode switch.

*As a result: when you switch from preview-mode into editor-mode <Cropper> receives default values for crop, rotation and zoom, calls onCropComplete and your implementation of onCropComplete sets editData to these default values.

There are several ways to fix this. But the main issue, as I see it, is that you don't have a single source of truth for photo's editData. So I think you should get rid of <ImageEditor> component's state and instead pass editData to the <Cropper>. Like so:
<Cropper
  image    = {photo.src}
  crop     = {photo.editData.crop}
  rotation = {photo.editData.rotation}
  zoom     = {photo.editData.zoom}
  ...
/>

You don't have a minimal reproducible example, so I can't test it. For this to works you should probably at least add some default values for photo.editData

A: Ciao, I think you could blob your image modified, then save it to localStorage and, when user exit from preview mode, show image blobbed instead of original photo.
I try to explain better: lets say you have this image in preview mode and user zooms it. So now original image is modified. Then, user clicks Clear Preview button. Just before call setIsPreviewMode(false) you could store modified image using, for example, dom-to-image. Something like:
domtoimage.toBlob(document.getElementById("ImageModifiedId"))
        .then(function (blob) {
            // here you have the image modified blobbed into blob item
            // then localStorage.setItem("ImageKey", blob);
            // and finally setIsPreviewMode(false)
        });

Ok now the last step, instead of passing to <Image> always the same photo, you could verify if there is a modifed photo in your localStorage and, if there is, load localStorage.getItem("ImageKey") into <Image>.


text:
Q: {React Native} Resetting Formik form after submit I am stuck at resetting my form after it has been submitted.
Here is what I have
  const PostEvent = () =>{

        //Omitted code for brevity.

return(
    <Formik
         initialValues ={{user: userName.currentUser.displayName, description: '',datePosted: new Date(), location: '', eventDate: '', title: ''}}
         onSubmit ={(values, {resetForm}) =>{
                 firebase.firestore().collection('PostedFunEvents').add({
                     datePosted: values.datePosted.toDateString(),
                     description: values.description,
                     eventDate: date.toDateString(),
                     eventTime: date.toTimeString(),
                     location: values.location,
                     title: values.title,
                     user: firebase.auth().currentUser.displayName,
                     userId : firebase.auth().currentUser.uid
                     });
                 resetForm({values:''})
                 }}>
         {props =>(

         <ScrollView keyboardShouldPersistTaps='always'>
         <DismissKeyBoard>
         <View style={{flex:1}}>
             <View  style={styles.form}><Text  style={styles.text}>Pick a place for the event</Text></View>
             <View style= {{paddingTop:20}}>
                 <GoogleAutocomplete
                     placeholder = 'Insert place to post about '
                     onPress={(data, details = null) => {
                             {props.values.location = data.description}
                         }}>
                 </GoogleAutocomplete>
             </View >

                <View style={styles.form}>

                 <Text style={styles.text}>{userName.currentUser.displayName}</Text>
                 <TextInput
                     placeholder= 'Title of the event'
                     onChangeText = {props.handleChange('title')}
                     style={styles.text}/>
                 <TextInput
                     placeholder= 'Description (e.g This is located...)'
                     multiline={true}
                     onChangeText = {props.handleChange('description')}
                     values = {props.values.description}
                     style={styles.textBox}/>

                 <Text  style={styles.text} >Click on the below icons to pick a time and a date for the event</Text>

                 <DateTimeImage onPress={showTimepicker} name = 'alarm'>Time?</DateTimeImage>
                 <DateTimeImage onPress={showDatepicker} name = 'calendar'>Date?</DateTimeImage>

                  {show && (<DateTimePicker onChange={onChange} value = {date} mode = {mode}></DateTimePicker>)}

                 <Button onPress={props.handleSubmit}>Submit</Button>

                 </View>

         </View>
         </DismissKeyBoard>
         </ScrollView>
         )}
     </Formik>
 )
}

This task should be pretty trivial, but I cannot seem to have it work. I have looked at many tutorials and SO posts, and they all seem to have the same idea, which is to pass a callback reset function to the onSubmit prop of the <Formik> component.
Anyone has any idea of what I could try?
Thanks in advance.

A: When you reset the form the values should be of the format of initialValues. You can take out the initalValues as an object and pass it on to reset form
const initialValues = {
      user: userName.currentUser.displayName,
      description: '',
      datePosted: new Date(),
      location: '',
      eventDate: '',
      title: ''
}

..
<Formik
     initialValues ={initialValues}
     onSubmit ={(values, {resetForm}) =>{
             firebase.firestore().collection('PostedFunEvents').add({
                 datePosted: values.datePosted.toDateString(),
                 description: values.description,
                 eventDate: date.toDateString(),
                 eventTime: date.toTimeString(),
                 location: values.location,
                 title: values.title,
                 user: firebase.auth().currentUser.displayName,
                 userId : firebase.auth().currentUser.uid
                 });
             resetForm({values: initialValues})
             }}>

Linked github issue


text:
Q: Azure Basic Small App cost I've had to switch from the Shared tier to Basic, to avail of SSL support and with that I knew there would be a price hike. But for me it has gone up exponentially -  this is going to cost me an extra £50+/month.
I have turned off the "Always On" setting and from analytics I can see that there is no traffic between 11pm and 5am most nights yet im averaging a bill of 22 hours per night service for the last 23 days...that's effectively "Always On".
Anyone know if I need to tweak something else to reduce the costs? Is there a setting that determines how long before the service goes to sleep?

A: The cost that you pay for the instances in App Service runs all the time, traffic does not matter.
If you have 1 instance in the plan, you pay for that 1 instance all the time. Always On just prevents an app from idling. It won't reduce billing if you turn it off.
At minimum on Basic tier and up you pay for 1 instance + outbound data traffic.

A: As juunas stated that Always On could not help you to save the cost, it just be put to sleep and free up resources for other web apps on the same service plan.

Anyone know if I need to tweak something else to reduce the costs? Is there a setting that determines how long before the service goes to sleep?

Even if you stop your app, the App Service plan charges still apply, and the service plan could not be stopped. For a workaround, you could schedule a task and invoke Azure Management SDK to switch the App Service Plan (Shared, Basic).
Use Microsoft.WindowsAzure.Management.WebSites with the authentication using a management certificate. Here is the core code, you could refer to it:
Change pricing tier from Basic to Shared
using (WebSiteManagementClient webappClient = new WebSiteManagementClient(credential))
{
    //you could leverage webappClient.WebSpaces.List() to retrieve your webspace
    //the format of your web space would be: "{resource-group-name}-{location-of-your-appserviceplan}webspace"
    var webSpace="{your-web-space}";
    webappClient.WebHostingPlans.Update(
        webSpace,
        "{The name of the web hosting plan}",
        new Microsoft.WindowsAzure.Management.WebSites.Models.WebHostingPlanUpdateParameters()
        {
            NumberOfWorkers = 1,
            SKU = Microsoft.WindowsAzure.Management.WebSites.Models.SkuOptions.Shared
        });
}

Note: After change the pricing tier to Shared, your configured SSL certificates would be reserved and until you change it back to Basic, you could retrieve and modify it and it could take effort. Moreover, if you scale out your app into multiple instances, you need to specify the property NumberOfWorkers when you changing pricing tier to Basic. For more detailed steps, you could refer to this similar issue.


text:
Q: How do I get the character from a read() I am trying to copy a file to print it backwards using only open(), read(), and write().
However I was wondering if there is a way to get the char pointer from the read which returns the number of bytes read. If so how do I go about doing that I have tried once but I ended up with an error
error: invalid type argument of 'unary *' (have 'ssize_t')

This was the code snippet i was using
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main (int argc, char *argv[])
{
 if(argc != 3)/*argc should be 2 for correct execution*/
 {
  printf("usage: %s filename",argv[0]);
 }
 else
 {
  int file1 = open(argv[1], O_RDWR);
  if(file1 == -1){
    printf("\nfailed to open file.");
    return 1;
  }
  int reversefile = open(argv[2], O_WRONLY, O_CREAT);
  int size =(int)lseek(file1, 0, SEEK_END)+1;
  char file2[size];
  int count=size;
  int i = 0;

  while(read(file1, &file2[count], 1) != 0)
  {
   *file2[i]=*read(file1, file[count], 1);
   write(reversefile, file2[i], size+1);
   count--;
   i++;
   lseek(reversefile, i, SEEK_SET);
   }
}

A: read returns a size_t value indicating how many bytes are successfully read, it doesn't return a pointer.
For your purpose, you first need to call read with
read(file1, &file2[count], 1)

then you can access the value read from file by
file2[i] = file[count];

and I don't think you need to call read twice.
Further, if you only want one single char, they using getc is better.
char c;
while((c=getc(file1)) != EOF){
  // use c
}

A: *

*You need to read all lines from your file and save them to array of strings.
This is an array of 100 strings and each string can have up to 999 characters + 1('\0')
char myfile[100][1000]

*You need to reverse strings. This can be done with very easy algorithm. For example: if you string is "ABCDE" you swap 'A' and 'E', 'B' and 'D'. Every time you get with your for loot to strlen(myfile[i])/2 and you swap character on i-th position and (strlen(myfile[i]) - 1 - i-th)-th position.

*Now you can write in your output.txt file all strings but in reverse order.
#include <stdio.h>
#include <string.h>

char myfile[100][1000];
int n;

void readmyfile(void)
{
    int i;
    FILE *input = fopen("input.txt", "r");
    printf("This is in your file:\n");
    for(i = 0; fscanf(input, "%[^\n] ", myfile[i]) != EOF; i++)
        printf("%s\n", myfile[i]);
    n = i;
    fclose(input);
}

void reverseall(void)
{
    int i, j, len;
    char swap;
    for(i = 0; i < n; i++)
    {
        len = strlen(myfile[i]);
        for(j = 0; j < len / 2; j++)
        {
            swap = myfile[i][j];
            myfile[i][j] = myfile[i][len - 1 - j];
            myfile[i][len - 1 - j] = swap;
        }
    }
}

void writetooutput(void)
{
    int i;
    FILE *output = fopen("output.txt", "w");
    printf("This is your output file:\n");
    for(i = n - 1; i >= 0; i--)
    {
        fprintf(output, "%s\n", myfile[i]);
        printf("%s\n", myfile[i]);
    }
    fclose(output);
}

int main()
{
    readmyfile();
    reverseall();
    writetooutput();
    return 0;
}

A: Reverse? For fun, a recursive solution.  No need for stat() or seek().
Notice ssize_t len = read(inf, buf, N);.  len, if >= 0 is the number of bytes read,  else an error occurred.  len as 0 usually indicates end-of-file.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int read_R(int inf, size_t N) {  // return 0 is good, else error
  int result = 0;
  char *buf = malloc(N);
  if (buf == NULL) {
    return -1;  // Out of memory
  }
  ssize_t len = read(inf, buf, N);
  if (len > 0) {
    // read & print remainder of file
    result = read_R(inf, N*2);
    // print this buffer in reverse
    while (len > 0) {
      putchar(buf[--len]);
    }
  }
  free(buf);
  if (len < 0) { // Some I/O error, see errno
    return 1;
  }
  return result;
}

// Usage
int inf = open(...);
if (read_R(inf, 4096)) {
  ; // error
}
else {
  ; // OK, every thing read and printed in reverse, memory free'd
}
close(inf);


text:
Q: Unable to create or delete Excel service application due to timeout On my server Excel Calculation Service is "started".
I tried to create new Excel Service Application but after some time I get following error.

And this is how it looks like after that.

If I try to delete, it takes even longer time (probably a few hours) and then show same request time out message.
From logs, I found two entries but none give any clue as to what the issue is.

System.Web.HttpException: Request timed out.

AND

SPTimerJobAsyncResult '9e0cc344-ae13-47f8-8b43-a0535e885651': An error
  occurred while waiting for completion:
  System.Threading.ThreadAbortException: Thread was being aborted.
      at System.Threading.Thread.SleepInternal(Int32 millisecondsTimeout)
      at System.Threading.Thread.Sleep(Int32 millisecondsTimeout)
      at Microsoft.SharePoint.Administration.SPJobDefinition.WaitForCompletion(TimeSpan
  timeout)
      at Microsoft.SharePoint.Administration.SPTimerJobAsyncResult.WaitForCompletion(Object
  state)

Could this be happening because Distributed Cache service is also not running on server and I tried to fix it but no luck?

A: Today I noticed that Excel Service Application that I created yesterday has magically started working. I am not sure how it happened and the only thing I remember is that I disabled anti virus on server and tried creating it again yesterday.