text:
Q: Shift data of one li & ul tag from one div class tag to another div id tag without any li & ul tags just only data This is my code below:

      Title

Name: XXXX

Dept: Editing

Role: YYYY

Original Output
Title

*

*Name: XXXX

*Dept: Editing

*Role: YYYY

Expected Output & Code
Title
Dept: Editing

*

*Name: XXXX

*Role: YYYY

   Title

         Dept: Editing

Name: XXXX

Role: YYYY

I want to extract or just remove li & ul tags of "cp_dept" i.e Dept: Editing data from div class="data" & wan't to shift data into div id="title" tag without li & ul tags i.e just only data as shown in Expected Output & Code that too with immediate effect on page loading.

A: Demo
Try this code..
var li=$('.data>ul>li').eq(1).remove();
var id=li.attr('id');
var html=li.html();
var div1=$('

').attr('id',id).append(html);
$('#title').append(div1);

A: var dept = $(".data ul li#cp_dept").html();
dept = "
" + dept + "
";
$("#title").append(dept);
$(".data ul li#cp_dept").remove();

A: Use insertAfter jQuery function : (remove and append)
$(function() {
    $('#cp_dept').insertAfter('#title span');
});

A: Try
$('#cp_dept').detach().wrapInner('
').contents().unwrap().appendTo('#title');

Demo: Fiddle

A: Check out this javascript only answer
JS
(function() {
     var dpt = document.getElementById('cp_dept');
     dpt.outerHTML=""
     var tit = document.getElementById('title');
     tit.innerHTML = tit.innerHTML +"
"+dpt.textContent;
  })();

Working Fiddle
Just added or edited a line in the Javascript. Instead of removing or editing cp_dept, I assign the CSS to display:none. It does the same function but this way I'm not erasing the contents of the cp_dept tag and hence the HTML markup remains intact.
(function() {
     var dpt = document.getElementById('cp_dept');
    // dpt.outerHTML=""
     dpt.style.display="none";
     var tit = document.getElementById('title');
     tit.innerHTML = tit.innerHTML +"
"+dpt.textContent;
  })();

A: Try this
var htm = $("#cp_dept").text();
$("#data ul #cp_dept").remove();
$("#title").append('
'+htm+'
');

A: Here is the code
$(document).ready(function() {
    var getli = $('.data #cp_dept');
    $('.data #cp_dept').remove();
    $creDiv = $('
').attr('id',getli.attr('id'))
                          .html(getli.html());
    $("#title").append($creDiv);
});

DEMO
But you may be looking for more, please comment on it

A: You can create a new element to append the "cp_dept" target, then add the new element to "#title".
var title = document.getElementById('title');
var dept = document.getElementById('cp_dept');

var newDept = document.createElement('div');
newDept.innerHTML = dept.innerHTML;

// remove the old cp_dept
dept.parentNode.removeChild(dept);

title.appendChild(newDept);

A: $("li#cp_dept").each(function(){

var div = $("
");

div.html($(this).html());

div.appendTo("div#title");

$(this).remove();

});


text:
Q: How can I track scrolling with a ScrollView linked to a Custom PageControl - SwiftUI I want to create a Carousel with SwiftUI(without using TabView)
with a matching/linked Page Control in SwiftUI
So far I have both views and can update the pageControl view with a
@State var pagecontrolTracker  updated with a DragGesture() .onChanged but it doesn't update the PageControl if I scroll fast, or sometimes doesn't update at all .
If I Scroll slow tho, the Page Control does update sometimes as expected.
Is there a better way to update this faster and smoother?
I saw .updating modifier for DragGesture() but this doesn't work either
Full View:
struct ContentView: View {

    @State var pagecontrolTracker: Int  = 0

    var body: some View {
        VStack {
            ScrollView(.horizontal) {
                HStack {
                    ForEach(0...3, id: \.self) { index in
                       PagingRow()
                            .gesture(DragGesture().onChanged({ _ in
                                pagecontrolTracker = index
                            }))
                    }
                }
            }

            PagingControls(pagecontrolTracker: $pagecontrolTracker)

        }
        .padding()
    }
}

Inside Custom SwiftUI Row View
struct PagingRow: View {

    var body: some View {
        VStack {
            HStack {
                Image(systemName: "globe")

                Text("Test Title")

            }
            .padding()

            Button {
                print("Test action")
            } label: {
                Text("Tap Me")
            }
            .buttonStyle(.borderedProminent)
            .padding()
        }
        .background(Color.orange)
        .frame(width: 200)
        .cornerRadius(8)
    }
}

Custom PageControl in SwiftUI
struct PagingControls: View {

    @Binding var pagecontrolTracker: Int

    var body: some View {
        HStack {
            ForEach(0...3, id: \.self) { pagingIndex in
                Circle()
                    .fill(pagecontrolTracker == pagingIndex ? .orange : .black)
                    .frame(width: 8, height: 8)
            }
        }
    }
}

Note: I don't want to use TabView since I want to be able to show the next upcoming card in the scrollView
A TabView would only show one card per page

redpajama_set_name: RedPajamaStackExchange


text:
Q: Height of system of equations in terms of height of a variety Say $X\subset \mathbb{P}^{n}$ be a $\mathbb{Q}$ variety of degree $\beta$.
It is well known and not hard to show that if $X=Z(f_1,...,f_{k})$ where $f\in\mathbb Z[x_0,...,x_n]$ are polynomials of height $h$ and degree $\beta$ then $h(X)\leq poly_{n}(\beta,h)$, where $h(X)$ is the logarithmic height of $X$.
(See for instance http://www.maia.ub.edu/~sombra/talks/mega2003/mega2003.pdf)
It will be useful for me to have an opposite direction. That is, if $h(X)$ is known, to have an estimate for the height of $f_{i}$ that will suffice to form $X$.
Unfortunately I don't really have a good idea. I think the best approach is to define $h'(X)$ to be the minimal height of a system of equations giving $X$ (where the height of the system is the maximum among the height of the equations) and to show that $h,h'$ are equivalent in the sense that :
$h'=\Theta_{n}(h)$
or at the very least $h'\leq poly_{n}(h),\;h\leq poly_{n}(h') $.
Does anyone have an idea or a reference for these kinds of definitions?
Thank you very much!


text:
Q: Distributed Deep recommended System- Tensorflow: failed: Session bundle or SavedModel bundle not found at specified export location After executing the distributed tensor flow as mentioned in the following link:
https://github.com/tobegit3hub/deep_recommend_system/tree/master/distributed
I got the following in ./checkpoint folder;
checkpoint
graph.pbtxt
model.ckpt-269.data-00000-of-00001
model.ckpt-269.index
model.ckpt-269.meta

I wanted to run tensorFlow serving on the above model provided in TensorFlow Serving. But I do get the below error when doing so:
 ./tensorflow_model_server --port="9000" --model_base_path=./model/

2017-07-14 15:32:32.791636: I tensorflow_serving/model_servers/main.cc:151] Building single TensorFlow model file config:  model_name: default model_base_path: ./model/ model_version_policy: 0

2017-07-14 15:32:32.792156: I tensorflow_serving/model_servers/server_core.cc:375] Adding/updating models.
2017-07-14 15:32:32.792188: I tensorflow_serving/model_servers/server_core.cc:421]  (Re-)adding model: default
2017-07-14 15:32:32.893072: I tensorflow_serving/core/basic_manager.cc:698] Successfully reserved resources to load servable {name: default version: 1}
2017-07-14 15:32:32.893143: I tensorflow_serving/core/loader_harness.cc:66] Approving load for servable version {name: default version: 1}
2017-07-14 15:32:32.893165: I tensorflow_serving/core/loader_harness.cc:74] Loading servable version {name: default version: 1}
2017-07-14 15:32:32.893252: E tensorflow_serving/util/retrier.cc:38] Loading servable: {name: default version: 1} failed: Not found: Session bundle or SavedModel bundle not found at specified export location

Any suggestion on this ?


text:
Q: sign the elements of a ugly matrix I have a matrix defined as $A=(I-aT)^{-1}F$, where I is identity matrix, a is a positive constant smaller than 1, T is a stochastic (transition matrix) and F is a matrix with positive diagonal elements and negative elements elsewhere. All matrix are $n*n$. I want to sign the elements in A. I got stuck somewhere by the inverse matrix. I am wondering are there some clear theorem related to show that? Or what else conditions do I need to show that? Thank.

A: $(I-aT)^{-1}=\sum_{k=0}^{+\infty}a^kT^k....$


text:
Q: Conducting and non-conducting infinite sheets of charge have same $E$? ($E$= electric field intensity)? From my textbook the description is given below to the image.

A: The answer is that the change in the component of the electric field that is perpendicular to the sheet of charge is: $$\hat{n}\cdot \Delta \mathbf{E} = \frac{\sigma}{\epsilon_0}.$$ Specifically, $\hat{n}$ is the unit vector perpendicular to the sheet of surface charge. This is true no matter where the sheet is as long as it is smooth enough to be flat if you zoom in enough. In the case of the conductor you have a condition that the electric field inside of it is $\mathbf{0}$, so the electric field outside will be $\sigma / \epsilon_0$. With an isolated infinite sheet that is the only source of electric fields in the universe you have a symmetry that the field on either side has to have the same magnitude, even if the directions are opposite, giving $|\mathbf{E}| = \frac{\sigma}{2\epsilon_0}$.

A: For Gauss' Law, which is derived from Poisson's equation, only the charge density matters irrespective where it resides. Therefore, the electric fields are equal for the conducting or non-conducting infinite sheets with equal total areal charge densities . It should be noted that in the case of the conducting infinite sheet, equal sheet charge densities exist at both conductor/vacuum interfaces whose sum represent the total areal charge density  of the conductor sheet.

A: Actually, the electric field intensity remains same
i) in case of non-conducting sheet the charge lies on one side of the sheet so charge density is charge divided by surface area (one side of the sheet) electric field intensity = charge density/2*epsilon
ii) in case of conducting sheet the charge lies on both side of the sheet so charge density is charge divided by surface area of both side of the sheet. So, charge density gets halved. Now electric field intensity = charge density/epsilon, as charge density gets halved so again electric field intensity remains same.


text:
Q: Lyft Universal Links: Is it possible to set destination location without pickup location? Lyft developers documentation states that

Note that you must set the pickup location if you're setting the destination location.

But it's rather common use case: I know where a user wants to go, but I'd like Lyft to use user's current location as pickup location or ask him to select pickup location itself.
So, is it possible in Lyft Universal Links to set destination location without explicitly setting pickup location?
BTW, Uber has pickup=my_location parameter in its Universal Links to handle such situations.

A: If you omit the "&pickup[latitude]=&pickup[longitude]=" query parameters then lyft will use the user's location detected when the app (lyft) enters the foreground.  So, yes you can create the link without the pickup location and lyft will grab the location.


text:
Q: Getting forest area (km2) of a region after the classification by RF considering the >10% tree cover and 0.5Ha? I am trying to make a yearly image collection using Landsat images, then trying to make a classification using Random forest for the image of the years 1990, 1995, 2000, 2005, 2010, 2015 and 2020.
I would like to know if it is possible to compute the area class (forest class) of each of them considering the forest definition  >10% of tree cover and 0.5Ha. I have tried to write the script but I got 0 km2 for all of them as a result (see script below).
I am still a beginner in GEE.
Here is the code: https://code.earthengine.google.com/?scriptPath=users%2Frorohambi%2FRo20%3AManakara_sorona

A: It is impossible because yearly images in Image Collections that you made did not preserve  original scale of Landsat images (they have 111,319.49 m, 1.0 arc degree, instead of 30 m as you expected). So, expected 0.5 ha is not about 6 pixels. In these images, as Forest0, one pixel is corresponding to 1,239,202.88 ha; not 0.09 ha.
On the other hand, all images that you use for determining area (in ha because you divide by 10,000; not by 1,000,000 for obtaining km2) are empty because your conditions in these binary images do not work (they have not sense).
Following code snippet corroborates the obtaining of a scale different of 30 for Forest0 image (.gte(cc) condition in this image has not sense because unmasked value is 1 and cc is equal 10 so, obvious result is false and an empty image). However, in Forest0 image it can be obtained an area value; it is exemplified as follows.
var Forest0 = classified_1990
  .select('classification').eq(0)
  .selfMask().rename('Forest0'); //forest id: 0 /Nonforest id: 1

print('Forest0',Forest0);
print('scale Forest0', Forest0.projection().nominalScale());
.
.
.
Map.addLayer(Forest0, imageVisParam2, 'Forest0');

var Forest0_area = Forest0
    .select('Forest0')
    .multiply(ee.Image.pixelArea().divide(10000))
    .reduceRegion({
      reducer: ee.Reducer.sum(),
      geometry: aoi,  // a geometry
      scale: 30,   // scale = 30 for landsat 8; this is not true scale
      maxPixels: 1e9
    });

print("Forest0_area in ha", Forest0_area.get('Forest0'));

As your aoi area was not adequately retrieved in your script, I assumed one rounded your points. Complete code is here. Following image has some relevant results of running the script in GEE console editor. However, you have to find an approach where scale is preserved.


text:
Q: Lock Pages in Memory for SQL Server What is a recommendataion regarding turning on Lock Pages in Memory for 64 bit SQL Servers.
Is there any implication on turning on lock pages in memory setting?

A: Microsoft recoomends as an option if you are experiencing buffer pool paging (http://support.microsoft.com/kb/918483).


text:
Q: gulp error : Error: Cannot find module '@microsoft/sp-build-web' issue I am facing to create the share point web part. To create the web part following libraries should be installed :
call npm install -g chalk
call npm install -g loadash
call npm install -g tar-fs
call npm install -g update-notifier
call npm install -g yeoman-generator
call npm install -g yosay

call npm install -g yo
call npm install -g gulp

call npm install -g @microsoft/generator-sharepoint

After installing above libraries web part created correctly. But after few days when I am creating new webpart again following error occurred:
gulp error :

Error: Cannot find module '@microsoft/sp-build-web'

When I install this this library then another library missing error occurred.
When I again install above libraries then every these libraries then everything  works  fine.
So the issue is Should I need to install above libraries again when I create the web part?

A: Have you tried the following :-
npm -g install npm@next
npm install --global --production windows-build-tools

then try your command again.

A: While trying to create a webpart with Sharepoint Framework I got the same error message.
I have gulp 3.9.1 version and I solved uninstalling my version of NodeJS and installing the 10.13.0 version.
Then I've done:
npm install --save-dev @microsoft/sp-build-web.

and everything worked for me :)


text:
Q: Error while parsing, when loading the data from snowflake having array datatype I am trying to read data from snowflake and load it to other storage location. I am using snowflake jdbc driver 3.12.9 to read the data and jackson library(2.10) to deserialize it.
In one of the usecase, I am using column with array datatype. Here is the create table statement : create table test_table (array1 ARRAY). I am loading the data into table by following command. insert into test_table (array1) select array_construct(1,2,3,null). When we run the select query on above data null value in the array is getting converted as undefined. e.g. select array1 from test_table, we are getting output as "[1, 2, 3, undefined]"
While deserializeing the data with jackson, I am getting error : Unrecognized token 'undefined': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'), as undefined is not a valid json token.
Conversion of null to undefined is happening only when one of the array element is null and not happening in case of entire array is null.
One of the solution is to write custom function at snowflake side and use it while querying the data but then we have to add this function at all our customers end and we don't want add this to be a blocker.
Is there any better way to solve this problem. Any suggestions, help will be very helpful.

A: I couldn't find an easy answer for this. So, I had to replace null using COALESCE when constructing the array, like:
select to_json(array_construct(coalesce(col1, '"null"'), coalesce(col2, '"null"')))


text:
Q: sort object by key by using lodash but key has lost after sorted I want to sort some Object look likes this
data = {
        "imH3i4igFNxM3GL": {
            "name": "Nacky",
            "age": 12
        },
        "vuzPuZUmyT8Z5nE": {
            "name": "Emmy",
            "age": 20
        },
        "OkIPDY1nGjxlq3W": {
            "name": "Nat",
            "age": 20
        }
}

I want to sort it by "name".
I tried to use Lodash for this problem.
_.sortBy(data, [function(o) { return o.name; }]);

but, it return me an array of objects without the keys
[
    {
      "name": "Emmy",
      "age": 20
    },
    {
      "name": "Nacky",
      "age": 12
    },
    {
      "name": "Nat",
      "age": 20
    }
]

I want it return me sorted object with key like the same
{
    "vuzPuZUmyT8Z5nE": {
        "name": "Emmy",
        "age": 20
    },
    "imH3i4igFNxM3GL": {
        "name": "Nacky",
        "age": 12
    },
    "OkIPDY1nGjxlq3W": {
        "name": "Nat",
        "age": 20
    }
}

what should I do? thanks

A: Objects in JS can't be sorted, and the order of the properties is not reliable, ie it depends on browsers' implementations. That's why _.sortBy() is converting your object into a sorted array.
I can think of 2 options to work with that.
Add the key to the objects in the array
If you just need an ordered array with the keys in the objects, so you can render a list.

var data = {
        "imH3i4igFNxM3GL": {
            "name": "Nacky",
            "age": 12
        },
        "vuzPuZUmyT8Z5nE": {
            "name": "Emmy",
            "age": 20
        },
        "OkIPDY1nGjxlq3W": {
            "name": "Nat",
            "age": 20
        }
};

var result = _(data)
  .map(function(v, k) { // insert the key into the object
    return _.merge({}, v, { key: k });
  })
  .sortBy('name') // sort by name
  .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Create an order array
Create an array of ordered keys, and use them when you wish to render the objects in order.

var data = {
        "imH3i4igFNxM3GL": {
            "name": "Nacky",
            "age": 12
        },
        "vuzPuZUmyT8Z5nE": {
            "name": "Emmy",
            "age": 20
        },
        "OkIPDY1nGjxlq3W": {
            "name": "Nat",
            "age": 20
        }
};

var orderArray = _(data)
  .keys() // create an array of keys
  .sortBy(function(key) { // sort the array using the original names
    return data[key].name;
  }) // sort by name
  .value();

console.log('The order array', orderArray);

console.log(orderArray.map(function(k) {
  return data[k];
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

A: I use something like this.

    let data = {
    'g34ghgj3kj': {
        YOUR_KEY: 'g34ghgj3kj',
        'key1': false,
        'key2': false,
    },
    'hh334h664': {
        YOUR_KEY: 'hh334h664',
        'key1': true,
        'key2': false,
    },
    //{...}
};

_.orderBy(data, ['key1', 'key2'], ['desc', 'desc']).reduce((result, value) => {
    result[value.YOUR_KEY] = value;
    return result;
}, {});


text:
Q: How to render a form on a Django HTML template using a Viewset's filter_fields in django rest framwork?
*

*I have a Viewset with a custom filterset_class:

class CommunityViewset(LoginRequiredMixin, viewsets.ModelViewSet):

    queryset = ...
    serializer_class = CommunitySerializer
    filterset_class = CommunityFilter
    template_name = ...
    filter_fields = ('groups',
                     'person__first_name',
                     ...)

    def list(self, request, *args, **kwargs):
        # getting serializer output
        response = super(CommunityViewset, self).list(request, *args, **kwargs)

    # default format is html, returning serializer data if json is requested
    if request.accepted_renderer.format == 'json':
            return response

        # if HTML
        return Response({'data': response.data,
                         'filter': get_filter_context(self) #!!!! GOING TO REFERENCE THIS BELOW
                          })

*

*I want to display a form on the HTML template to make a filtered GET request (e.g. localhost/community?groups=group1)
I have a custom function called get_filter_context() that get the filterest class's fields and renders it in html:

def get_filter_context(viewset):
    ''' create filters dictionary for list views
    @param {obj} viewset: rest_framework.viewsets.ModelViewSet subclass instance
    @returns {dic} filters: filters template dictionary
    '''
    f = viewset.filterset_class(viewset.request.GET, viewset.queryset)
    dic = {'form': f.form} #!!!!! REFERENCING THIS BELOW
    return dic

f.form returns a full django form which isn't serializable. Is there a to render the form without passing it to context?


text:
Q: DateTime inserted in SqlServer changes value When I insert these values
09/30/2013 05:04:56.599
09/30/2013 05:04:56.599
09/30/2013 05:04:56.599
09/30/2013 05:04:57.082

in SqlServer database, the millisecond value changes in a weird way
2013-09-30 05:04:56.600
2013-09-30 05:04:56.600
2013-09-30 05:04:56.600
2013-09-30 05:04:57.083

What's wrong ?
Edit:
Relevant code:
        com = new SqlCommand();
        com.Connection = con;
        com.CommandText = @"INSERT INTO [AuthSourceTimings]
                                   ([FileName]
                                   ,[JobID]
                                   ,[JobCreationTime]
                                   ,[JobSendTime]
                                   ,[JobAckTime]
                                   ,[JobDoneTime])
                             VALUES
                                   (@FileName
                                   ,@JobID
                                   ,@JobCreationTime
                                   ,@JobSendTime
                                   ,@JobAckTime
                                   ,@JobDoneTime)
                            ";

        com.Parameters.AddWithValue("@FileName", fileName);
        com.Parameters.AddWithValue("@JobID", t.JobID);

        com.Parameters.AddWithValue("@JobCreationTime", t.JobCreationTime == DateTime.MinValue ? (object)DBNull.Value : (object)t.JobCreationTime);
        com.Parameters.AddWithValue("@JobSendTime", t.JobSendTime == DateTime.MinValue ? (object)DBNull.Value : (object)t.JobSendTime);
        com.Parameters.AddWithValue("@JobAckTime", t.JobAcknowledgementTime == DateTime.MinValue ? (object)DBNull.Value : (object)t.JobAcknowledgementTime);
        com.Parameters.AddWithValue("@JobDoneTime", t.JobCompletionTime == DateTime.MinValue ? (object)DBNull.Value : (object)t.JobCompletionTime);

        com.ExecuteNonQuery();

A: Milliseconds are stored only with precision of about 1/300th of a second in datetime format so that's where the inaccuracy comes from.
You can check this answer: Why is SQL Server losing a millisecond?
To get higher precision (100 nanoseconds), you can use DATETIME2 which was introduced in SQL Server 2008. You can get more information here:

*

*http://msdn.microsoft.com/en-us/library/bb677335.aspx

*http://www.mssqltips.com/sqlservertip/1616/sql-server-2008-date-and-time-data-types/

A: You are probably using the SQL Server type DATETIME, which the documentation states:
Rounded to increments of .000, .003, or .007 seconds.

The DATETIME2 type should be used if you want full compatibility with .NET DateTime. Both of these have an accuracy of 100 nanoseconds.
There aren't many good reasons to use DATETIME anymore. A DATETIME2(7) takes up 8 bytes which is the same as a DATETIME, but has a far greater accuracy and range. A DATETIME2(3) takes up 6 bytes and still has better accuracy (3 decimals without the weird rounding behavior detailed above).

A: Its alll about precision. If you are using datetime type in database, try datetime2 type.

A: You should check your table's structure. In the create table part, it should be like this:
CREATE TABLE t1 (dt DATETIME(6) NOT NULL);

To get the Output as it is.

A: Pretty Clear that it is not the .NET or code issue
DECLARE @TestDateFrom  DATETIME='2010-06-29 05:04:56.599'
SELECT @TestDateFrom

Result
2010-06-29 05:04:56.600
And Satisfied with Szymon answer "Milliseconds are stored only with precision of about 1/300th of a second in datetime format so that's where the inaccuracy comes from."


text:
Q: Ext-GWT text rotation not working in Internet Explorer 8 I am using Ext-GWT version 3.0 (specifically 3.0.0-rc), and am attempting to rotate some text via a TextSprite. It works fine in Google Chrome but not in Internet Explorer 8.
Java source:
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.sencha.gxt.chart.client.draw.DrawComponent;
import com.sencha.gxt.chart.client.draw.sprite.TextSprite;
import com.sencha.gxt.widget.core.client.container.Viewport;

public class TextRotation implements EntryPoint {
    public void onModuleLoad() {
        TextSprite sprite = new TextSprite("Some text");
        sprite.setRotation(270);
        DrawComponent component = new DrawComponent();
        component.setViewBox(true);
        component.addSprite(sprite);
        Viewport vp = new Viewport();
        vp.add(component);
        RootPanel.get().add(vp);
    }
}

Using the IE developer tools to export the generated source produces the following. The text component is being created, but seems to be placed outside of the visible area:

      <?xml:namespace prefix = vml />
      <vml:shape style="Z-INDEX: 0" class="vml x-vml-sprite" coordsize = "21600,21600" filled = "t" fillcolor = "white" stroked = "f" path = " m0,0 l27388800,0,27388800,16956000,0,16956000 xe">
        <vml:skew class=vml on = "t" matrix = "935375f,0,0,935375f,0,0" offset = "34468954f,52315599f"></vml:skew>
        <vml:fill></vml:fill>
      </vml:shape>
      <vml:shape style="Z-INDEX: 10" class="vml x-vml-sprite" coordsize = "21600,21600" filled = "t" fillcolor = "black" stroked = "f" path = " m0,0 l1,0 e">
        <vml:skew class=vml on = "t" matrix = "0,935375f,-935376f,0,0,0" offset = "52315599f,-34468954f"></vml:skew>
        <vml:textpath style="LINE-HEIGHT: normal; FONT-VARIANT: normal; FONT-FAMILY: ; FONT-SIZE: 12px; v-text-align: left" class=vml on = "t" string = "Some text"></vml:textpath>
        <vml:path class=vml textpathok = "t"></vml:path>
        <vml:fill></vml:fill>
      </vml:shape>

If I then comment out the line "sprite.setRotation(270);" the non-rotated text displays fine. The generated HTML is exactly the same as above, except for the values for the "skew" entries. Diffs as follows:
10c10
<         <vml:skew class=vml on = "t" matrix = "935375f,0,0,935375f,0,0" offset = "34468954f,52315599f"></vml:skew>
---
>         <vml:skew class=vml on = "t" matrix = "1510899f,0,0,1510899f,0,0" offset = "1445363f,14325573f"></vml:skew>
14c14
<         <vml:skew class=vml on = "t" matrix = "0,935375f,-935376f,0,0,0" offset = "52315599f,-34468954f"></vml:skew>
---
>         <vml:skew class=vml on = "t" matrix = "1510899f,0,0,1510899f,0,0" offset = "1445363f,14325573f"></vml:skew>

Googling, examining past problems on the Sencha forums and here gives me no clues.
Thanks.


text:
Q: $\epsilon$-$\delta$ proof that $\lim_{x \to 1} \sqrt{x} = 1$ I'm trying to teach myself how to do $\epsilon$-$\delta$ proofs and would like to know if I solved this proof correctly. The answer given (Spivak, but in the solutions book) was very different.

Exercise: Prove $\lim_{x \to 1} \sqrt{x} = 1$ using $\epsilon$-$\delta$.
My Proof:
We have that $0 < |x-1| < \delta $.
Also, $|x - 1| = \bigl|(\sqrt{x}-1)(\sqrt{x}+1)\bigr| = |\sqrt{x}-1||\sqrt{x}+1| < \delta$.
$\therefore |\sqrt{x}-1|< \frac{\delta}{|\sqrt{x}+1|}$
Now we let $\delta = 1$. Then
\begin{array}{l}
-1<x-1<1 \\
\therefore  0 < x < 2 \\
\therefore  1 < \sqrt{x} + 1<\sqrt{2} + 1 \\
\therefore  \frac{1}{\sqrt{x} + 1}<1.
\end{array}
We had that $$|\sqrt{x}-1|< \frac{\delta}{|\sqrt{x}+1|} \therefore |\sqrt{x}-1|<\delta$$
By letting $\delta=\min(1, \epsilon)$, we get that $|\sqrt{x}-1|<\epsilon$ if $0 < |x-1| < \delta $.
Thus, $\lim_{x \to 1} \sqrt{x} = 1$.

Is my proof correct? Is there a better way to do it (still using $\epsilon-\delta$)?

A: The proof is correct but can be simplified. You don't need the part "Now let $\delta=1$...". In fact it is always true that
$$
  \frac{1}{\sqrt x + 1} \le 1
$$
since $\sqrt x \ge 0$.
Also, a matter of style. In the first line you don't have $0 < |x-1|<\delta$ but you suppose it (this is because $\delta$ is not already been given, but has to be found yet). The same when you write "let $\delta = 1$" you should write "if $\delta \le 1$ ..."

A: Your proof is correct.
We can also adopt the following:
Since $|\sqrt x-1|\lt \epsilon$ is equivalent with $1-2\epsilon+\epsilon^2\lt x\lt 1+2\epsilon+\epsilon^2$, we can choose $\delta$ so that $0\lt\delta\lt \min\{|-2\epsilon+\epsilon^2|,|2\epsilon+\epsilon^2|\}$.
Hope this helps.

A: Using your work here is another flavor of this proof:
Let $\epsilon >0$, and put
 $\delta= \epsilon(\sqrt{x}+1)$.
Assume $0<|x−1|<\delta$.
Then
     $$|F(x)−L|=|x−1|
             =∣(\sqrt{x}−1)(\sqrt{x}+1)∣.$$
By our assumption that  $0<|x−1|<\delta$, we have
    $$|F(x) - L| <|1/(\sqrt{x}+1)|\delta = (1/(\sqrt{x}+1))ϵ(\sqrt{x}+1))  = \epsilon.$$
By letting $\delta=\epsilon(\sqrt{x}+1)$,  we get that $|x−1|<\epsilon$ if 0<|x−1|<δ.
Thus, $\lim_{x\to 1} F(x) = L$
The scratch work is usually omitted as far as finding the co-efficient of delta itself. Then just find the co-eff inverse and include epsilon and it falls out at the end. There is a good link on math exchange that shows a template of how to structure delta-epsilon proofs. It is how I learned to write them up, and this is that method. Good luck.
P.S. * represents multiplication, and the square roots were not working. I am unfamiliar with LaTex so this is the best I can do.


text:
Q: Calculating if item was sold in 24h I have two columns with item list date and item sold date in dataframe.
Need ideas how to calculate if an item was sold in 24hours.
Results should be in new column - sold_in_24 and be True/False, better 1/0.

list_date
sold_date
sold_in_24

2018-09-30 19:06:21
2018-09-30 23:06:21
1

2018-07-08 15:02:32
2018-07-24 19:02:32
0

2018-07-08 19:02:32
2018-07-09 15:02:32
1

What comes to my mind is:
df['sold_in_24'] = [df.sold_date - df.list_date for x in df['sold_in_24'] if x <= 24]

A: If your dates are datetime64[ns] type, you can subtract them and check if the difference is less than 24 hours:
import pandas as pd

df = pd.read_html("https://stackoverflow.com/questions/67246707/calculating-if-item-was-sold-in-24h")[0]
df["list_date"] = pd.to_datetime(df["list_date"])
df["sold_date"] = pd.to_datetime(df["sold_date"])

df["was_sold_in_24h"] = (df["sold_date"] - df["list_date"]) < pd.Timedelta(days=1)

print(df)

Output:
            list_date           sold_date  sold_in_24
0 2018-09-30 19:06:21 2018-09-30 23:06:21        True
1 2018-07-08 15:02:32 2018-07-24 19:02:32       False
2 2018-07-08 19:02:32 2018-07-09 15:02:32        True


text:
Q: How to add current location to a wall post I've managed to post a photo with a message to my wall using the Facebook C# SDK. The next step is to add my current location to the post. I'm using Windows Phone 7.1. I have a Geocode location available which I want to add to the post. I can't find how to add a location parameter to the post. Any form of location would be fine, e.g. "Amsterdam".  Is this possible at all?
Here's a piece of code where I would like to add some location magic.
    var photoDetails = new Dictionary<string, object>();
    photoDetails.Add("message", txtMessage.Text);
    photoDetails.Add("image", selectedImage);
    // add location

    fb.PostAsync("/photos", photoDetails);

A: I found this link searching a way to get the nearest location from the GeoCoordinates i hope this will help you.
And if you have the location then you can add it to the message.
Simple GPS Locator

A: According to the comment by nsiomos on this blog post, adding locations to the wall post just isn't supported yet by the Graph API of Facebook. I certainly hope this will soon be added as a feature for 3rd party apps using Facebook. My only (quite less charming) option left is just paste the location in the message instead of passing it as a parameter.


text:
Q: NPM how do you install another dependency from a subdirectory of another Git repository? In package.json using npm, how do you install another dependency from a subdirectory of another Git repository?
For example, I have tried:
npm install
my package.json ....
  "dependencies": {
    "some-package": "git+https://github.com/myTeam/myrepo.git#develop/folder-with-a-package-json",
    "lodash": "4.17.14"
  },

*

*The remote dependency has valid package.json in the sub directory
folder-with-a-package-json.

*The remote repo is public.

Error:
npm ERR! code 1
npm ERR! Command failed: git checkout develop/folder-with-a-package-json
npm ERR! error: pathspec 'develop/folder-with-a-package-json' did not match any file(s) known to git


text:
Q: Remove duplicate based on value I have code that will delete the entire row if such conditions are met:

*

*ID are duplicate AND

*In the duplicate ID the cond1 = Hello AND

*In the duplicate ID the cond2 = 1

See sample table below. The highlighted should be deleted.
The code is slow thus finding a way to optimize it.

Sub RemoveDupl()

    'to check if the Incident ID has duplicates
    lastRow = Worksheets("Sheet1").Cells(Rows.Count, 6).End(xlUp).Row

    'loop to check all the rows
    For i = 2 To lastRow
        Set rangeIDCheck = Range("A:A")
        For j = 2 To lastRow
            If WorksheetFunction.CountIf(rangeIDCheck, Worksheets("Sheet1").Cells(j, 6).Value) > 1 And Worksheets("Sheet1").Cells(j, 15).Value = "Hello" And Worksheets("Sheet1").Cells(j, 16).Value = "1" Then
                Rows(j).EntireRow.Delete
            End If
        Next
    Next

End Sub

My second code. I only need how to get the current row number. I searched but got nothing. Enclosed in * is the one I need to be replaced.
Sub RemoveDupl()

    'turning off
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Application.Calculation = xlCalculationManual

    Dim Rng As Range
    Dim cel As Range
    Dim Counter As Integer

    Set Rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))

    For Each cel In Rng
        If WorksheetFunction.CountIf(Rng, cel.Value) > 1 And Cells(**Rng.Row**, 15) = "Hello" And Cells(**Rng.Row**, 16) = "1" Then
            cel.EntireRow.Delete
            'cel.EntireRow.Interior.Color = 5296274
        End If
    Next cel

    'turning on
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.Calculation = xlCalculationAutomatic

End Sub

A: Updated After Small Correction (Thanks EEM)
For your first code, you can speed it up quite a bit by performing the deletion all at once at the end. Try this....
Sub RemoveDupl()
Dim WS As Worksheet: Set WS = Sheets("Sheet1")

'to check if the Incident ID has duplicates
lastRow = WS.Cells(Rows.Count, 6).End(xlUp).Row

'loop to check all the rows
Dim aRng As Range

Set aRng = WS.Rows(Rows.Count)

For i = 2 To lastRow
    Set rangeIDCheck = WS.Range("A:A")
        For j = 2 To lastRow
            If WorksheetFunction.CountIf(rangeIDCheck, WS.Cells(j, 6).Value) > 1 And WS.Cells(j, 15).Value = "Hello" And WS.Cells(j, 16).Value = "1" Then
                Rows(j).EntireRow.Delete

                Set aRng = Union(aRng, Rows(j))

            End If
        Next
Next
aRng.ClearContents
aRng.Delete
End Sub

For your second code, you can get the row as a property. So your code would be written like this:
WorksheetFunction.CountIf(Rng, cel.Value) > 1 And Cells(cel.Row, 15) = "Hello"  _
And Cells(cel.Row, 16) = "1" Then

Hope that works.


text:
Q: unexpected XML tag. expected: {http://schemas.xmlsoap.org/soap/envelope/}Body but found: {http://schemas.xmlsoap.org/soap/envelope/}Envelope Am working with SOAP XML I have validate my xml online it's fine, but when send to server am getting error message "unexpected XML tag. expected: {http://schemas.xmlsoap.org/soap/envelope/}Body but found: {http://schemas.xmlsoap.org/soap/envelope/}Envelope", this is the xml am sending
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:pos="http://pos/">
<soapenv:Header>
    <soapenv:Body>
        <pos:balanceInquiry>
            <iccData></iccData>
            <pinBlock></pinBlock>
            <terminalId></terminalId>
        </pos:balanceInquiry>
    </soapenv:Body>
</soapenv:Header>

I have removed values in tags everything remained the same.
@Root(name = "soapenv:Envelope")
@NamespaceList({
        @Namespace( prefix = "soapenv", reference = "http://schemas.xmlsoap.org/soap/envelope/"),
        @Namespace( prefix = "pos", reference = "http://pos/")
})

public class XMLRequestEnvelope {

    @Element(name = "soapenv:Header", required = false)
    private XMLRequestHeader header;

    public XMLRequestHeader getHeader() {
        return header;
    }

    public void setHeader(XMLRequestHeader header) {
        this.header = header;
    }
}

@Root(name = "soapenv:Header", strict = false)
public class XMLRequestHeader {
@Element(name = "soapenv:Body", required = false)
private XMLRequestBody body;

public XMLRequestBody getBody() {
    return body;
}

public void setBody(XMLRequestBody body) {
    this.body = body;
}

}
    @Root(name = "soapenv:Body", strict = false)

     public class XMLRequestBody {
    @Element(name = "pos:balanceInquiry",required = false)

private XMLBalanceInquiry xmlBalanceInquiry;

 public XMLBalanceInquiry getXmlBalanceInquiry() {
        return xmlBalanceInquiry;
    }

  public void setXmlBalanceInquiry(XMLBalanceInquiry xmlBalanceInquiry) {

        this.xmlBalanceInquiry = xmlBalanceInquiry;
    }
    }

 @Root(name = "pos:balanceInquiry", strict = false)
public class XMLBalanceInquiry {

@Element(name = "iccData", required = false)
    private String emvData;

    @Element(name = "pinBlock", required = false)
    private String pinBlock;

 @Element(name = "phoneNo", required = false)
    private String phoneNo;

    @Element(name = "terminalId", required = false)
    private String terminalId;

  public String getEmvData() {
        return emvData;
    }

 public void setEmvData(String emvData) {
        this.emvData = emvData;
    }

 public String getPinBlock() {
        return pinBlock;
    }

public void setPinBlock(String pinBlock) {
        this.pinBlock = pinBlock;
    }

  public String getPhoneNo() {
        return phoneNo;
    }

 public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }

 public String getTerminalId() {
        return terminalId;
    }

   public void setTerminalId(String terminalId) {
        this.terminalId = terminalId;
    }
}


text:
Q: Play Videograbber input via DirectShow locally in Browser I have an Elgato 4k60 Pro Capture Card and can grab video input via hdmi. I have to use the Elgato Software, but I could also open the live inputstream with VLC via DirectShow. But my goal is to see the live inputstream in the browser, just locally for me. Because it works also in VLC I think it could be possible with HTML/JS. I also could stream it with OBS or something over the internet and watch my own stream in the browser, but this way needs too much hardware resouces. Better would be to show the grabbed input directly in the browser. Is there any good solution or existing example? Thank you very much!

A: Locally running browser can open either encoded streaming media or a local user multimedia device such as camera via Media Capture and Streams. So the answer to your question depends on your definition of "see" below:

But my goal is to see the live inputstream in the browser, just locally for me.

The streaming media path requires that something - and browsers do need help with this because they are not the right tool to access media data from devices like Elgato capture card directly - that something encodes the video (and audio) into suitable form. This can be additional application that produces either Media Source Extensions API (MSE) chunks delivered to browser with some helper JS code, which then uses browser MSE interface to populate media streams. Or, alternatively, the encoding application could present the media feed using MPEG-DASH or HLS asset which a browser can play with the help of one of JS players available out there, or native browser support for certain streaming media protocol.
In this sense there is no much of difference whether encoded stream is consumed by your local browser or a browser running on another system on network.
The other path of "seeing" video as a local multimedia device requires, apart of browser support for this relatively new API, that browser's implementation on the platform recognizes the Elgato hardware as a suitable camera, which I am guessing is not the case of Elgato: to my best knowledge (which is a bit stale though) the integration layer they provide is insufficient since modern browsers like Chrome use Media Foundation API (as opposed to DriectShow) to access such local devices and so Elgato remains invisible as a video source.
UPD. I think I stand corrected with the above - Elgato device might be actually visible for Media Capture and Streams API. I checked my records and their Game Capture HD60 Pro looks like having suitable driver for Media Foundation. So 4K60 Pro might work out too. getUserMedia test page is where can quickly check if browser is capable to capture from a local video source.

A: As Roman pointed out, try getUserMedia test page. However, the link he provided doesn't allow choosing video source. Try this webpage as getUserMedia test page:
https://secure28.securewebsession.com/umediaserver.net/demos/publish.html
If your Elgato source is not appearing in Video Capture Source dropdown, that means your Elgato driver is not fully DirectShow compatible. Or maybe it provides compressed output - has an on-board H264 compression, for example.
One thing you could try is Unreal Video Mixer source filter (for x64 Chrome you need x64 version). Unreal Video Mixer is seen by getUserMedia, and it will ingest your Elgato input (uncompress it if needed) and make it available for getUserMedia.


text:
Q: Understanding reactive Recently kotlin flow is gaining a lot of attention. I have never done any reactive programming before so i thought now is a good time to learn it. Even though I have access to books and some articles I could not understand how to integrate it say on an existing app that does not have any rxjava. I tried looking for some sample but the only thing they would give me is very basic. Im really confuse about this reactive programming thing. For example, I have a list that I needed to get on database. Why would I use flow to get that data? If I visualize it as streams, that would give me one data each. While if I get that list I could get the whole list without waiting for each streams to come if I had use flow. I read a lot of articles about this kotlin flow, even rx java. But still, I wanted to understand why streams and how is it any different from other way like the example I just gave?

A:
For example, I have a list that I needed to get on database. Why would I use flow to get that data?

Well, that depends entirely on what you are using to access that database and how it uses Flow.
Let's suppose that you are using Room from the Android Jetpack. In that case, you can use Kotlin coroutines in two ways, via suspend functions and via Flow:
@Query("SELECT * FROM stuff")
suspend fun getStuff(): List<Stuff>

@Query("SELECT * FROM stuff")
fun getStuffNowPlusChanges(): Flow<List<Stuff>>

In both cases, Room will do the database I/O on a background thread, and you can use coroutines to get the results on your desired thread (e.g., Android's main application thread). And initially, the results will be the same: you get a List<Stuff> representing the current contents of the stuff table.
The difference is what happens when the data changes.
In the case of the suspend function, you get just the one List<Stuff> from the point when you call the function. If you change the data in the stuff table, you would need to arrange to call that function again.
However, in the case of the Flow-returning function, if you change the data in the stuff table while you still have an observer of that Flow, the observer will get a fresh List<Stuff> automatically. You do not need to manually call some function again — Room handles that for you.
You will have to decide whether that particular feature is useful to you or not. And if you are using something else for database access, you will need to see if it supports Flow and how Flow is used.


text:
Q: Unable to install Ubuntu on an iMac I download the install .iso from the ubuntu download site, no problems. I burn the ISO to a DVD medium as a disc image on my windows computer, no problem. I take that DVD over to my imac, and it won't read the disc.
The iMac is running OSX now, I want Ubuntu on it.

A: Double check that you have the correct cpu architecture. It may need a PPC arch (Power PC)
If not 64-bit should work.


text:
Q: Flex and Flex-wrap wrap not working? display: flex; //Parent element

and
flex-wrap: wrap; //Direct child elements

Each grid has to fill 25% of the containers width and go down automatically..
But currently they do not act like flex-wrap: wrap; they act like they are 20% width when there are 5 grids... its a bit weird because they are set to be 25% ?
If I put Flex-wrap: wrap; on the parent element where I currently have display:flex; it works, but then they are not equal heights?
What do I do in this situation? I can't figure out how to do this
Find the example here: http://www.chri126g.wigf1.sde.dk/DUER1/
HTML

          Navn
          Smith

          Far
          Jackson

          Mor
          Emelie

          Pris
          500kr

CSS

.flex {
  display: flex;
}
.flex1{
  flex: 1;
}
.flex-d-r{
  display: flex;
  flex-direction: column;
}
.flex-w-w{
  display: flex;
  flex-wrap: wrap;
}
body{
  background-color: lightgrey;
}
.global-wrapper{
  padding: 5px;
  width: 90%;
  min-height: 100vh;
  max-width: 1000px;
  margin: 0 auto;
  background-color: #fff;
}

.dueOuter{
  padding: 5px;
}

.dueInner{
  outline: 1px solid #000;
  min-height: 100px;
  transition: 0.3s ease;
  -webkit-box-shadow: 0px 0px 9px 0px rgba(0,0,0,0.75);
  -moz-box-shadow: 0px 0px 9px 0px rgba(0,0,0,0.75);
  -webkit-box-shadow: 0px 0px 9px 0px rgba(0,0,0,0.75);
  -moz-box-shadow: 0px 0px 9px 0px rgba(0,0,0,0.75);
  box-shadow: 0px 0px 9px 0px rgba(0,0,0,0.75);
}

.dueInner:hover{
  b: 3px solid #000;
}
.dueInner img{
  width: 100%;
}
td{
  width: 100%;
}
tr:nth-of-type(odd){
  background-color: lightgrey;
}

A: You can not do that using flexbox. As I quote this answer by Michael_B on this question

*Flex Lines

  In a multi-line flex container (even one with only a single line), the
  cross size of each line is the minimum size necessary to contain the
  flex items on the line (after alignment due to align-self), and the
  lines are aligned within the flex container with the align-content
  property.
In other words, when there are multiple lines in a row-based flex
  container, the height of each line (the "cross size") is the "minimum
  size necessary to contain the flex items on the line".

If you are looking for a javascript alternative. Here's what you need to add just before :

A: For the parent element (the one with display:flex) You need to add:
flex-wrap: wrap;
align-items: stretch;
Then to have size no-matter what content you have inside you have two options:
 1. Calculate highiest div height with js and apply min-height: [top-height] to all children divs.
 2. OR if You can estimate max height - just do it in css using min-height.
I'm 99% sure there is no way to achieve it using pure flexbox with flex-wrap and different contents.


text:
Q: Firebase - Is Data Persisted When a User Signs Out? I have enabled offline support in my app using:
FirebaseDatabase.getInstance().setPersistenceEnabled(true);

I am using only Google Sign In for authentication.
I was wondering that when a user signs out, does the data related to the user remain persisted in the local sqlite database?
If No, then how can I ensure that it remains persisted as I wouldn't want the user to download stuff again when he signs back again.

A: public void setPersistenceEnabled(boolean isEnabled)

By default the Firebase client will keep data in memory while your application is running, but not when it is restarted. By setting this value to true, the data will be persisted to on-device (disk) storage and will thus be available again when the app is restarted (even when there is no network connectivity at that time
isEnabled - Set to true to enable disk persistence, set to false to disable it.


text:
Q: How to store all values of many nested dictionaries in a list I'm trying to write some code that opens up about 900 nested dictionaries with roughly 99% similar content (very large) and store the value of each key in a list named after the key. For example, if I had two dictionaries: {data=37} {data=74} I would want to combine those two values into a list named data that outputs the following [37,74]
Here is the code I'm currently using to accomplish this:
import pandas as pd
df = pd.read_csv("/Users/---.csv")
i=True
def sort(d):
    for k, v in d.items():
        if isinstance(v, dict):
            sort(v)
        else:
            global i
            if i==True:
                print("{0} : {1}".format(k, v))
                setattr(sys.modules[__name__], k, [v])
                i=False
            else:
                print("{0} : {1}".format(k, v))
                globals()["{}".format(k)].append(v)

for i in df['file_num']:
    with open("/Users/--/allDAFs{}.json".format(i)) as f:
        data=json.load(f)
    sort(data)

The problem with this is two fold:
a. There are some duplicates and I'm not sure why. There are 1400 values for some key when there are only 900 files.
b. I can't link these to a file_num. As you can see I'm sorting through these using file_num and I'd like to link each value to the file_num it came from.
I know I may not be doing this the best way possible so any insight or advice would be greatly appreciated.
EDIT: This is how I need the end result to look like, preferably in a pandas DataFrame:

A: I would use a defaultdict. Maybe I'm missing something, but I don't really see the problem.
import pandas as pd
import collections

def sort(d, output):
    for k, v in d.items():
        if isinstance(v, dict):
            sort(v, output)
        else:
            output[k].append(v)

df = pd.read_csv("/Users/---.csv")
results = collections.defaultdict(list)

for i in df['file_num']:
    with open("/Users/--/allDAFs{}.json".format(i)) as f:
        data = json.load(f)
    sort(data, results)

Then, results will be a dictionary of lists that you can address by same keys.
For your issues with ZIPcodes, make sure, the keys are alays the same datatype (str), maybe even ascii.

A: I used df.json_normalize() like Richie suggested, which worked well.


text:
Q: Unable to install korn sh package I need to install ksh because we have many scripts /bin/ksh that must run on crontab.
There is no internet in the VM (runnnig Ubuntu 20.04.2 LTS) so I uploaded this package and copied it into /tmp. I have this error when I try to install it:
# apt install ksh_2020.0.0-5_arm64.deb
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package ksh_2020.0.0-5_arm64.deb

I tried the following command:
apt install ./ksh_2020.0.0-5_arm64.deb

But it's not working because there are some missing packages:
# apt install ./ksh_2020.0.0-5_arm64.deb
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 grafana : Depends: libfontconfig1 but it is not installed
 ksh : Depends: binfmt-support but it is not installable
 libfontconfig1-dev : Depends: libfontconfig-dev (= 2.13.1-4.2)
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

As the VM can't be connected to the internet, I can't add the missing package.
Is there another way to install ksh, or to execute a ksh script?

A: Your system is behind on upgraded packages (it should report as 20.04.3 if fully updated)
Try providing a path, ie.
apt install ./ksh_2020.0.0-5_arm64.deb
it's the path that makes it be recognized as a local package; you've told it to download & install a package with the name you provided (ie. download & install ksh_2020.0.0-5_arm64.deb) where none of course exists)


text:
Q: Set attribute selected of particular option of select box using jquery I have a select box with following options
select id="box" >

  option value="1"Same Day

  option value="5">96

  option value="4">72

  option value="3">48

  option value="2">24

select>

I Want to add attr selected to option value '4' , i know i can show it selected via
$("#box").val(4)

But this just shows it selected but does not add attribute selected to option 4, what i want is to add attribute selected to option.
Please suggest
Thanks

A: $('#box').children('option:eq(3)').attr('selected', 'selected');

That makes usage of the eq() selector which querys the index you specify.
Slightly faster (even if it's more typing) would be the method .eq() instead of the selector:
$('#box').children('option').eq(3).attr('selected', 'selected');

Since .eq() uses array slices instead of query'ing over Sizzle.
As you notice correctly, both versions start indexing at zero.
Ref.: :eq, .eq()


text:
Q: How do I log out of `sudo su`? I'm using sudo su to start mysql and do some homework with it.
When I finish with mysql (or any other command), then I'm still in sudo.
How do I "log out", so my prompt changes back from # to $?

A: Use
su username

to get back to your user level (or a different user)
Or just press Ctrl+D to exit out of root

A: if your stuck after using sudo su as root: to exit use this command
su -l <user_name>

A: You don't need to use sudo and su together--su switches your user account (without arguments it switches you to root). sudo just elevates your privileges to root for the current command.
It's reccomended to use sudo instead of su if possible, but to return to your normal account after calling su, simply use the exit command

A: *

*logout if used sudo su -

*exit if used sudo -s

A: There isn't any reason to use sudo or su to run the MySQL command-line client. It defaults to using your current Unix user as your MySQL user, but instead you should pass it the user you want to connect to as arguments:
$ mysql -u root # connect as MySQL's root user (without password)
$ mysql -u root -p # -p means prompt for a password

Hopefully, your MySQL root account has a password, and you'll need to use the second form.
Other than that, if you need to run MySQL under sudo (e.g., for file permissions) then do it like this:
$ sudo -u unix-user mysql -u mysql-user -p

You can leave out the arguments (sudo will default to user root, MySQL will default to using the same user as sudo).

A: if you get access denied message -for example - while login to mysql with root password like:
mysql -u root -p

try:
sudo mysql -u root -p

for one time elevation of privileges, for multiple commands use:
sudo su

you will notice that your terminal changed to [root@yourpc]# then whatever commands you like to run
when you want to return back to your own user hit ctrl + d , type exit or
su username

your terminal will be back to [username@yourpc]# and you are now using you own user permissions


text:
Q: Retrieve Image from database, display and attach it to a link I have Images stored in my DB, I want to retrieve them all and display them in the browser. It works just fine, but I want to give the user the ability to click on the picture so that they can have a better view of the picture (so display it with its original size). I tried many things but didn't work. second question: if I want my code to support multiple images type (such gif, jpg, etc..), if there a way to do it without having to save the image type (when I insert the images) and play with a whole bunch of if/else (when I retrieve them)?
This is my code
  $count = 0;
       echo "
";
   while($row = $result->fetch_assoc()) {

       $imagename = base64_encode( $row['Image'] );
       if(($count%3) ==0){
        echo "
";
         echo "
";

            echo "
";
            echo " ";
            echo '';
            echo"
";

        ++$count;

       }else{
                echo "
";
            echo " ";
            echo '';
            echo"
";
            ++$count;

       }

   }
 echo "
" ;

A: The answer to your first question is "You have to use light-box jQuery plugin", in order to display larger (original size) of a thumbnail you need to use any lightbox plugin, I recommend using this one
http://www.jqueryscript.net/zoom/Responsive-jQuery-Lightbox-Like-Image-Zooming-Plugin-Lighter.html
Or you can search for any other plugin, there are thousands of them.
Regarding your second question, If you will use data as an images source, you have to specify a type, no way you can do that without mentioning types.


text:
Q: Keyboard locks in IntelliJ IDEA based editors on Mac Multiple times a day keyboard stops responding in IDEA based products.
If I quickly cmd-tab to another application and back again, it will work again.
It's occurring so often that it's starting to really annoy me. This affects all the Idea based editors I'm using, which are:
PhpStorm, AppCode, Android Studio, PyCharm, IDEA 15.
I notice it often happens when auto completion popup appears. But it also happens without the completion popup.
I've used IDEA products on 3 different macs, and I've seen the problem on all.

A: please follow  IDEA-132221 and IDEA-122525 for updates


text:
Q: How to realize that clicking  tag leads to http request and do not jump to the new page? I want to make a download link.
Here is my HTML:

When I click  tag, I want to perform an http request, and the  tag really does that. But it also jumps to the new page. I do not want that to happen.
I searched and found some solutions such as setting  tag's href="#something", or use ajax. However, those solutions are not what I want.
I am wondering there is a better solution for doing this? PS: I really do not want to use ajax to realize these in here.

A: You can set the target to a new tab. In chrome this tab closes automatically.

A: HTML codes are:

I use nodejs for server,and nodejs codes are:
fs.stat(filepath, function(err, stats) {
    if (err)
        throw err;

    var stream = fs.createReadStream(filepath);
    response.setHeader('Content-Type', mime.lookup(filepath));
    response.setHeader('Content-Disposition', 'attachment;    filename=test.docx');
    response.writeHead(200);
    stream.pipe(response);
});


text:
Q: WCF Service Reference not giving non-async methods I recently made a WCF service in C# and hosted it on a server running IIS 8.
Everything worked perfectly when testing locally and I was able to test all of my methods with success. My issue comes when I try to add a service reference to that WCF service in a separate project, the only methods it exposes at this point are async methods even though I never implemented any of my methods as async.
An example of a method would be:
public string getName(User user)
{
     return user.name;
}

Something as simple as that would work when I tested it in Visual Studio, but when I host it in IIS and try to add a service reference, the only method I can seem to call or have access to is:
getNameAsync

Why would it do this even though I never implemented it as async in the first place? On top of that, I cannot uncheck "generate methods for async" when I add the service reference in the first place.
Any ideas?
Edit: For reference, I am trying to test these methods inside of a Windows 8.1 app that references the service.

A: This is how the code is generated. Normally you will find also and event called GetNameCompleted for which you subscribed in the client code like that (after creating a the method ClientGetNameCompleted):
client.GetNameCompleted += ClientGetNameCompleted ;

In this method you will use the service result. something like that:
private void ClientGetNameCompleted (object sender, GetNameCompletedEventArgs e)
{
    if (e.Result != null)
    {
        // use the e.Result that contains the returned data;
    }
}


text:
Q: Why is the intersection empty for open nested intervals? Is this correct?
The length of, for example $(0, 1/n)$ as n appoaches infinity, doesn't reach 0 because it's not in the set. But, for the closed set it does because it is in the set?
Apologies for the duplicate question, but I'm having trouble with understanding the answers of others. Below is a link to a a similar question.
Why doesn't the nested interval theorem hold for open intervals?

A: It is not that the intersection of a sequence of open nested intervals is always empty, just that it can be empty.
The quintessential example is the one you have given; define the sequence $(I_n)_{n\in\mathbb{N}}$ such that $I_n=(0,1/n)$. Question: If I pick a real number $x$, does it belong to the set $\cap_{n=1}^k I_n$? Only if $0<x<1/k$. Since the reals have the property that there are no non-zero infinitesimals, every real number $x$ has some natural number $k_x$ such that $x>1/k_x$.
Thus, eventually, after a finite number of intersections, $x$ will not belong to our set. Thus, if we take the entire intersection, no real number $x$ gets in our set, and we are empty.
I would ignore the lengths of the intervals for this particular portion of the problem; we only wish to demonstrate that the theorem for nested, closed, and bounded intervals cannot be generalized to nested, open, and bounded intervals.

A: It does not have to do with length. Think about any positive number $x$. By the archimedean property there is some natural $n$ s.t. $1/n<x$, in particular,$x\notin (0,1/n)$ and thus is not in the intersection. Because the only number that could be in the intersection is $0$ but $0\notin (0,1)$, this intersection is empty.


text:
Q: Why is libre office calc inserting a ' at the beginning of the cell? This is the most ridiculous thing i've encountered.. I've imported a csv, I end up with nice neat clean rows of numbers, no formatting, nothing weird, no " or ' left over, just numbers.  When I go to change the format to currency, instead of doing that it leaves it the same at a glance but looking at the formula it adds a little ' at the beginning..m So instead of -145 it becomes '-145
Same thing happens if I clear direct formatting.  Nothing changes visually but now all cells have this damned ' at the start of the formula.  This thing is preventing sum from working, it's preventing everything and I have no idea how to get rid of it.
If I select a cell and try to paste it into another sheet the same behavior happens.  If I paste special and paste numbers only then nothing pastes, it's completely blank.
Anyone have any idea as to what is going on here?  Those 's are not present in the CSV fiel at all until any of the above is attempted
PS - importing the CSV into google drive and opening it with google docs does not result in this behavior
Sample line in the Csv file:
"1/1/2012","18:22:19","PST","VENDOR NAME","Shopping Cart Payment Sent","Completed","USD","-33.25","0.00","-33.25","myemail@email.com","theiremail@email.com","confirmation####","Non-U.S. - Verified","","Shopping Cart","","0.00","","0.00","","","","","","","","","","","","#######","","","#,###.##","","","","","","","", –


text:
Q: Controllers in a separate project, but when I try to add a view via "right click", it creates a new Views folder within my Controllers project..? I've got my Controllers in its own project, my Models in their own projects, and the Main App in ITS own project, which contains the Views folder.
So when I open up my controller cs file and right click on, say for example, the Details action and choose "Add View", it creates a Views folder within my Controllers project, and adds the view there.  I want it to add the view into the Views folder in my Main App project.  How in the world do I do this?????  Thanks so much in advance for anyone's help and advice!!
Mike

A: Right click in your project that has the views to add the view. Views don't care which controller calls them, so there is no reason to click in your controllers project.


text:
Q: Removing commas and quotes from numeric fields in csv file using SSIS I am creating SSIS package which reads data from a csv file and stores in SQL Server database. There are a few numeric fields in the csv files.
They sometimes contain value like "1,008.54"
How do I remove the quotes and comma from the value?
I have successfully separated the rows with this kind of data by using Conditional Split Transformation.
(SUBSTRING([Column 9],1,1) == "\"")
After this, I tried using Derived Column Transformation to REPLACE comma and quotes with empty string. But it is not working.
Please advise.
Thanks!

A: I tested your sample value "1,008.54" in a Data Flow where my source was:
SELECT '"1,008.54"'  AS [Column]
I then placed the following expression in a Derived Column Transformation (imitating what you did attempted)
REPLACE(REPLACE(Column,",",""),"\"","")
and successfully achieved your request:   Using Derived Column Transformation, REPLACE comma and quotes with empty string.
Here's the result as presented by a data viewer after the Derived Column Transformation:
Column  Derived Column 1
"1,008.54"  1008.54


text:
Q: Check host availability by MAC address Is it possible to check if host with secific MAC address are 'alive' ?
I do NOT want to use 3-rd layer ISO/OSI and ICMP ping message

A: You can do an ARP Ping. This only works when you are physically on the same network segment. Read more about this on Wikipedia's ARP Ping article.
Note that there are two different implementations of arping, one which can ping MAC addresses to resolve them to IP addresses and one that doesn't. The implementation in the iproute2 package does not do what you want, but Thomas Habets implementatation does. This is also explained in the Wikipedia ARP Ping article


text:
Q: Finding two missing vertexes of square given two points and equations of diagonal lines The diagonal line equations are $4x-5y+3=0$ and $5x+4y-27=0$.
Vertex $A$ was given $(-1,8)$, I figured it belongs to the second line equation. I have found the center of the square by solving diagonal line equation system $ O(3,3)$, and opposite of $A$ vertex $C(7,-2)$ from midpoint equation.
Now I'm not sure how to proceed with the points $B$ and $D$. I tried $|AB|=|BC|$ , but as I don't know the lengths of sides that didn't work out.

A: You correctly got the intersection of the two lines as being at the point $O=(3,3)$.  Labeling the points clockwise, we know point $A=(-1,8)$ and the point $C=(7,-2)$ from the problem statement.  We also know that $\overline{AO}\perp \overline{OD}$ (they are perpendicular) and that $|\overline{AO}|=|\overline{OD}|$ (they are of the same length).
The linesegment $\overline{AO}$ can be described with the vector $\langle 4,-5\rangle$ (if you havn't seen vectors before, it is a way of saying it traveled 4 spaces to the right and 5 spaces down).  To find the vector describing $\overline{OD}$, reverse the order and apply a negative to one of the entries (in this case the first entry, had you changed the other entry it would have taken you to the point $B$) changing it from $\overline{AO}=\langle 4,-5\rangle$ to $\overline{OD}=\langle -5,-4\rangle$.
It is easy to verify that these representations have the same magnitude and are perpindicular, so travel from $(3,3)$ along the vector $\langle -5,-4\rangle$ to arrive at $D$.  Do so similarly for $B$.
Hover your mouse below for a picture of the situation if desired.

A: You know the center of the square is $(3,3)$.  You need a line segment along the other line of length $\sqrt{4^2+5^2}$ in each direction, so increase $x$ by $5$ and $y$ by $4$ to get one corner, and decrease them by the same amount for the other.

A: The slope of the first diagonal is $\frac{4}{5}$. The slope of the other (on which $A$ and $C$ lie) is $-\frac{5}{4}$.
Let's find $B$, which will be to the right and above $A$, as well as to the right and above $C$.
To get from $A$ to $O$, you follow diagonal $2$: increase the $x$-coordinate by $4$ (going right four units) and decrease the $y$-coordinate by $5$ (going down five units). To find $B$ from $O$, we should follow diagonal $1$: increase the $x$-coordinate by $5$ (going right five units) and increase the $y$-coordinate by $4$ (going up four units).
This means $B$'s coordinates are $(8,7)$.


text:
Q: Tree traversal to find the most 'logical' SQL joins between two tables I'm creating a report builder-like application with the intent on making an extremely novice friendly front end.
The back end of the application will be managed by developers who can build a 'report model' which will specify which tables, fields and joins to include for the end user to use.
I am also looking to add functionality that will not require a report model. My application will scan the target SQL database, and created a virtual model with all of the joins and fields mapped.
After this i will need to be able to generate the most 'logical' or efficient a path between tables e.g with the minimal amount of joins. Kind of similar to the traveling salesman scenario.
I have decided to go about this by using tree's to map all joins from a specific table which will be the start node, and all other tables it could possibly connect to. This way i can do a breadth-first tree traversal to in theory find the most 'logical' path to join.
My issue with this is that not all databases will be set up in a particularly machine logic friendly manner. Meaning that a human may see a logical join because of specific table or field names, that my algorithm may not. (Below is a simple iteration of my algorithm in c# that does not yet record the path between tables)
 public Node<T> findClosestObjToNode(Node<T> node, T obj)
    {
        Boolean matchFound = false;
        List<Node<T>> toSearch = new List<Node<T>>();
        List<Node<T>> toSearchNext = new List<Node<T>>();
        toSearchNext.Add(node); //add proimary node to search list

        while(!matchFound){
            toSearch.AddRange(toSearchNext); //copy the searchnext list to search
            toSearchNext.Clear();

            foreach(Node<T> _node in toSearch){
                if (node.contains(obj)) //check for existance of object in the nodes children
                    return node.getChild(obj); //return the child node that contains the object
                else
                    foreach (Node<T> cNode in node.getChildren()) //no matching object found in child nodes
                        toSearchNext.Add(cNode); //so add each child node to the list of nodes to search
            }
            if(toSearchNext.Count == 0) //no match found
                return null;
        }
        return null;
    }

My question is really. Does the way i have planned above seem like a decent solution to the whole problem, or is there a better way of doing the above to get more accurate table joins.

A: If I have understood your requirements properly, then I question your approach to this problem. Normally, there are not many ways to get a certain piece of data from a database - there is usually one and only one way to get that specific piece of data. With TSP type problems there are multiple possible solutions and the ideal solution is based on some constraint on the system. I don't think you are going to get much gain from your solution as you will most often find that their is only one combination of table joins that will provide you with the data that you need.


text:
Q: Скриншот окон с аппаратной отрисовкой Пытаюсь получить скриншот окон через PrintWindow.
Окна, использующие аппаратную отрисовку не захватываются.
Например Chrome, Edge. Причем в Windows 7 захватываются, а в Windows 10, 11 уже нет.
Есть подозрение, что это связано с версией WDDM.
Есть ли какая нибудь возможность:

*

*захватывать аппаратную отрисовку?

*отключить аппаратную отрисовку для всей системы?

*отключить или еще как то воздействовать на WDDM?


text:
Q: OpenVPN - name resolution between connected clients I am looking for a solution with which distributed clients can easily reach each other via the internet.
For this I have set up an OpenVPN server to which all clients connect.
If I connect myself to the server, I can reach all devices via IP.
What is a (recommended) network structure to provide name resolution for the connected clients?
Or do you have a better solution with which I can easily reach my distributed devices (call them by name)?

A: Using OpenVPN in tun mode (which is the more common mode, and logical choice here) means that OpenVPN assigns a second IP address to each connected device, and clients can reach each other through the openvpn server assigned IP
It is easy enough to ensure that Openvpn assigns a non-changing address to each client.  There are multiple mechanisms whereby this can be done including the use of a shared pool of space which openvpn tracks and stores - the ifconfig-pool-persist directive (just ensure the number if clients is less then the pool size and the pool file is backed up) - or create a specific configuration file per client using ifconfig-push statements on the server.
Its worth pointing out that if you are using pki (private key infrastructure) - which makes sense in most environments, the user name/client name is the name specified un the subject name on the cert.
Once you have the static IPs defined you can define them in your DNS.  How you do this is dependant on your DNS configuration and can be as simple as hard coding these. Alternatively Openvpn provides a hook "lean-address"  which will run a script - with $1 $2 and $3 being yhe name of the action, ip and username-per-subject-cert and can be used to modify your dns as appropriate to your environment.


text:
Q: Filtering DataGridView using Comboboxes Let me preface this by saying I am a beginner as far as .net knowledge.
I am developing a windows form application using tabs in VS2012 in vb. I have bound the datagrid through the designer to a sql server binding source which is populating the data. There are multiple columns in the table and these are split between two tabs with a datagrid on each tab. Both data grids have the same binding source just show different columns.
I created a view within the SQL server to pull in the column names. I think what I want to do and not sure if this is possible but have 2 combo boxes that will be used to filter. One of the would be bound to the view by a dataadapter and then the second to the datagrid binding source.
when the user selects the first combobox(columnname) it would then pull from the datagrid for that column and pull in the valid values to filter. It would then filter the datagridview and refresh it.
Then I am trying to remove the filters through the use of a button.
Can someone please help as I don't even know where to start

A: You can use Dataview in filtering datasources. You can refer to my answer at this question


text:
Q: Can the Death Star kill stars? In Legends, the in-universe etymology of the term "Star Destroyer" lies in the earliest days of the Galactic Republic, when its creator envisioned a new class of ships that is powerful enough to destroy entire star systems. Well, obviously the ship models that eventually adopted the name aren't capable of that (orbital bombardment is the closest thing to it).
But the Death Star is indeed powerful enough to destroy entire planets. That begs the question though: Can the Death Star destroy stars?
Canon or Legends is acceptable, preferably both if there is a difference between the two at all.

A: In Disney Canon, I'm afraid I don't know, but to my knowledge it has never been shown either way.
In Legends Canon, whilst not explicitly stated to my knowledge, it would seem likely that it cannot, as the Death Star was designed at a research centre set up by Tarkin, the Maw Installation. After the completion of the Death Star design and prototype project, the scientists working in the Maw moved onto the Sun Crusher, whose sole purpose was the destruction of stars.
If the Death Star laser could already destroy stars, it would seem that this second project would be a large waste of time and resources.
The Sun Crusher was indeed built, and used to devastating effect as seen in the Jedi Academy trilogy, written by Kevin J. Anderson.

A: In (not so) hard science, giving a very big amount of energy to a star does almost nothing. Temperature rise will cause pressure increase, but energy will be radiated or convected out quite fast. You'll notice only that the star energy production increases together with its radius... but the radiated energy goes in the whole 4pi solid angle. A Helium flash only happens when the lack of Hidrogen causes the star to collapse enough to burn Helium. A nova can't happen at all in a normal star, because it happens only on accreting White Dwarfs. A Supernova, on the other hand, happens only on massive stars at least 8 Sun masses, and only when Iron core collapses.
I bet not even 1000 Death Stars would be able to kill our dwarf G2V Sun, not even to cause it becoming nova or supernova.

A: I don't know if the superlaser had enough joules to do so, but in Lost Stars, Cienna Ree's smart friend says the kyber crystals give the Death Star unlimited power, so its very possible it cause the sun to go nova, but it might destroy the Death Star in the resulting supernova.


text:
Q: DNS: cname wildcard entry subdomain with hyphen I am trying to make a wildcard cname entry on my dns provider as follows:
*-abc.[domain].com or even *abc.[domain].com but it does no work.
If i do *.abc.[domain].com then it will work but I don't want to use dot.
I am using hyphens as opposed to dots as I have a wildcard SSL certificate so all "levels" are covered.

A: That's not going to work. A wildcard must cover a whole "domain level", you can't use it to match parts of a domain. See this and RFC 1034.


text:
Q: Wattage calculation for resistors in series I need the formula for calculating resistor wattage when the resistors are in series.  For example, say I have 3 1/4 watt 10 ohm resistors in series.  What is the potential power dissipation for the entire circuit?

A: Since resistors are in series, the current will be the same throughout the chain. Assuming that the voltage V across the string of resistors is constant, you can calculate the current \$I={V \over R_1+R_2 +R_3+ ...}\$. Power dissipated on each of the resistors: \$P_i=I^2R_i\$. If \$P_i\$ is less than the power rating of the resistor, it should dissipate the power without burning.
A string of N identical resistors in series each rated for P watts can dissipate \$NP\$ watts.


text:
Q: RegisterController Create method redirect with error message issue in Laravel 5.4 Redirect user to register page with error message user already exists.
The thing is I cant use validation as type email because I am adding organization name manually @organization.com in the create code and I prevent users from entering @organization-name.com . Currently validation just checks if email value is filled. Therefore I need some strategy in create method to find out if email exists or not and take appropriate action here redirect back with error or redirect to login page saying user exists
This is my code in Register Controller - Create method
public function create(array $data)
{

    $firstname = Input::get('firstname');
    $lastname  = Input::get('lastname');
    $username     = Input::get('email');
    $email = $username."@hw.ac.uk";
    //I need to do a check if this new user exists or not.
    //If not go to Login page saying message user exists.
    $digits = 5;
    $new_code = rand(pow(10, $digits-1), pow(10, $digits)-1);

    $user = new User;
    $user->firstname             = $firstname;
    $user->lastname              = $lastname;
    $user->email                 = $email;
    $pswd                         = bcrypt(Input::get('password'));
    $user->password              = $pswd;

}

}
but when I register new user for the first time and re-register the same user with all different info but same email address. I get this error:

    SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test@gmail.com' for key 'users_email_unique' (SQL: insert into `users` (...))

I know its a duplicate entry but I want to redirect user to login page and tell that user already exists with this email. How do I do that?

I used this:
$existing = User::select('email')->where('email',$email)->pluck('email');
        if($existing[0] == $email){

            return Redirect()->back()->withErrors('User already exists');
        }else{
            //continue
        }

But I get session guard error.

A: The exception you get is for adding a new user with same email (which is unique as per your migrations). Before creating the user you can first check If it already exists or not.
$user = User::where('email', '=', 'user_email')->first();
if($user == null)
{
  //Add new user
}else {
 return redirect()->route('someroute');
}


text:
Q: a formula for calculating value of interest bearing account to which I make monthly deposits I have two sons, ages 6 and 11, for whom I deposit 50 dollars each into separate education accounts. I think it would be more fair to give my older son a larger amount monthly so that by the time they each turn 18, I will have invested the same amount of money into their accounts. I have noodled around with amortization formulas but I'm not a good enough mathematician to produce a convincing answer to my problem. Basically, I want x dollars invested in an interest bearing account monthly for the next 84 months to equal $(100-x) invested in a similar account for the next 144 months. What is a good formula for figuring this out?

A: Yes, there is a mathematical answer to this.  If you invest $x$ dollars per month at the beginning of the month at $i$ per month compound interest for $n$ months, one month after the last deposit the last one will be worth $x(1+i)$ and the first will be worth $x(1+i)^n$.  This is a geometric series with sum $x(1+i)\frac {(1+i)^n-1}i$ so your equation is
$$x(1+i)\frac {(1+i)^{84}-1}i=(100-x)(1+i)\frac {(1+i)^{144}-1}i$$
Fairness is not a mathematical term.  This calculation will result in each son having the same number of then-year dollars one month after your last deposit.  Do you want to consider the effect of inflation during the five years?  Your younger son will presumably face higher prices in the time he is in college.  How much do you think the inflation will be?  In the US for the past few decades the cost of college has risen faster than inflation.  Maybe this last belongs on personal finance.se


text:
Q: Is the PowerShell ConsoleShell on .NET 4.0 approved for production? After reading several other blog posts and articles (references found below) there appear to be several ways to run PowerShell on .NET 4.0 but few are sufficient for our purposes. Due to how we deploy our software we cannot update the registry or change add an application. This leaves us with two options, create our own shell by using ConsoleShell or override PSHost. We would like to be able to use the first option, ConsoleShell, due to it's simplicity but would like to know what issues we may encounter and whether doing so is recommended.
Reference
Based on other questions I have seen that you can use the following methods to run PowerShell as .NET 4.0. None of these methods appear to be officially sanction by Microsoft but the first shown below is included as a work around in this Microsoft connect issue.
The options to run PowerShell in .NET 4.0 appear to include:

*

*Update the app.config to include .NET 4.0 as supported

*Add a registry setting to switch the version

*Use ConsoleShell to host your own PowerShell Console

*Implement your own PowerShell host, PSHost , as done by PoshConsole or Nuget

A: As far as it is not officially approved (to my knowledge), then nobody can approve it but you. If your scenario works and passes reasonable tests, approve and use it.
I use PowerShell on .NET 4.0 but with the option 4, and used to use the option 1, too (I do not like the option 2, personally). Thus, I approved it, production or not, I use it a lot and it works. I still use PowerShell on .NET 2.0 for two reasons: 1) PowerShell.exe starts faster (especially x64); 2) to be sure that part of my PowerShell development is compatible with .NET 2.
Another thought. If something does not work properly in PowerShell on .NET 2.0 (there are some issues, indeed, see Connect) then the fact "it is approved for production" itself does not help much. One has to overcome existing issues, .NET 2 or .NET 4 does not matter.
P.S. I should have mentioned that I tried the option 3 as well. I did not find use cases suitable for using it in my scenarios. But I did not find any issues in using ConsoleShell either.
P.P.S Yet another option. Make a copy of PowerShell.exe, rename it into MyConsoleShell.exe, use it together with MyConsoleShell.exe.config configured for .NET 4. As far as you are going to use a separate application anyway, then why not to consider this?

A: I'm a bit of a powershell N00b, but I threw this together as a way of forcing an arbitrary script to use .NET 4.0 in my script:
# Place this at the top of your script, and it will run as a .NET 4 ps script.
# #############################################################################
if ($PSVersionTable.CLRVersion.Major -lt 4) { try {
    $cfgPath = $Env:TEMP | Join-Path -ChildPath ([Guid]::NewGuid())
    mkdir $cfgPath | Out-Null
    "<configuration><startup useLegacyV2RuntimeActivationPolicy='true'><supportedRuntime version='v4.0'/></startup></configuration>" | Set-Content -Path $cfgPath\powershell.exe.activation_config -Encoding UTF8
    $darkMagic = 'COMPLUS_ApplicationMigrationRuntimeActivationConfigPath'
    $old = [Environment]::GetEnvironmentVariable($darkMagic)
    [Environment]::SetEnvironmentVariable($darkMagic, $cfgPath)
    & powershell.exe $MyInvocation.MyCommand.Definition $args
} finally {
    [Environment]::SetEnvironmentVariable($darkMagic, $old)
    $cfgPath | Remove-Item -Recurse
    return
}}
# ##############################################################################

# My script starts here:
echo "Your arguments are: $args "
echo "The CLR Major Version is : $($PSVersionTable.CLRVersion.Major)"

It places a check in the beginning of the script, and if it's not .NET 4.0 it creates a configuration file, sets an environment variable and re-runs the powershell script so that it runs under .NET 4.0.
it does incur a bit of a startup time penalty of about a second or so on my pc, but at least it works :)


text:
Q: Open specific folder/path in Explorer with run dialog I want to set up a way to open some path with the run diaglog (Windows + R). Let's say I type in repo and windows would open a explorer in C:\foo\bar\svn.
Is there a better way than creating a repo.bat like that?
@echo off
start explorer C:\foo\bar\svn

A: In addition to your batch file approach being the way i would solve this quickly, it's worth mentioning that launchy can do this for you as well.
http://www.launchy.net/
To me it has replaced the run dialogue as well as the start menu.


text:
Q: "You should go" vs "You should have to go" What's the difference between:

You should go

and

You should have to go

Can I use one instead of the other?

A: should means  "the correct or best thing to do". have to means "to need to or be forced to; must".

You should go

means that going is the best thing to do.

You should have to go

means that the best thing would be if you were forced to go.
As you can see, the two are not interchangeable.


text:
Q: SSMS - Add a custom button to toggle retaining CR/LF in output I'm using SSMS v17 and am hoping this is somehow doable.
In my SQL Server DB, I have many tables that have VARCHAR fields that have, within them, CR/LF characters (multi-line text).
I know there is the setting in Tools > Options > Query Results > SQL Server > Results To Grid for Retain CR/LF on copy or save and I find myself often having to toggle that on / off since, if I always leave it on, I can get bad outcomes when I try and copy from the grid into Excel if there are CR/LF characters, but, other times, I just want the data from a specific row and want to copy that VARCHAR with its included line-breaks, so then I need to toggle it back on, otherwise, I end up getting the cell's value as one, long line (line-feeds are removed).
So, the solution I'd love (but I'm VERY open to other suggestions if there are any) is to have a custom toolbar button for that specific command so I can toggle it much more easily than having to go into the menu bar each time.
My challenge is that I'm not finding that command in the list when I try and customize the toolbar. Does it exist or is there another way to associate a toggle-button to that command? Or, as I saidm I'm very open to other suggestions if anyone has any.
Thanks!!

A: SSMS Boost has that functionality. Copy cell data from Results Grid 1:1 (preserving line breaks)

SSMSBoost introduces "Copy current cell 1:1" command:
select cell you want to view/copy, open context menu -> "Copy current cell 1:1" and full data will be copied to clipboard - all bytes and without any modifications.

And the second one is: Copy Results Grid data to Excel (as xml Spreadsheet)

SSMS Tools Pack also has similar capability Feature: Export To Excel:

This feature does not require Excel to be installed and creates a fully functional XLSX Excel file. Export all result sets, one or multiple tables or a whole database to Excel.
Saving the best for last, the characters like newlines and tabs are fully preserved and properly exported into correct cells.


text:
Q: Unslider not working on website This http://unslider.com/ for some reason is not appearing on my site, only the li text is showing and it is sliding but there is no appearance of the slider, just the text.
I have included the js files along with the css and markup but its somehow not showing me the full slider.
Here is my code:
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <title>Webpage</title>
    <link rel = "stylesheet" type = "text/css" href = "1style.css"/>

 Logo

This is a slide.

This is another slide.

This is a final slide.

Terms of use

Privacy

Cookies

Accessibility

CSS:
.banner { position: relative; overflow: auto; }
.banner li { list-style: none; }
.banner ul li { float: left; }

Can someone check the link i provided above and tell me where i'm going wrong?
Thanks

Seems like none of the answers fix the problem at all, I guess i'll have to find a new slider.
Thanks for the help

A: Unslider picks the height from first list item (
) from your list (
). Hence to make it work perfectly fine just add the height to first element.

A: Hey The problem is with the height of the container.
Because of the low height it isn't capable of displaying the overflow.
So i have made little changes to your code.
And they are :
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<title>Webpage</title>

Logo

This is a slide.

This is another slide.

This is a final slide.

Terms of use

Privacy

Cookies

Accessibility

And It works for me !

A: Check my unslider.com help file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <title>Unslider.com example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Some h1 text

smaller p text

                Hyperlink

Some h1 text

smaller p text

              Hyperlink

Some h1 text

smaller p text

              Hyperlink

Some h1 text

smaller p text

              Hyperlink

          ←
          →

A: Your code is good. Slider is created, but slides are outside the box and overflow is hidden so you don't see them. Add this css
.banner ul { margin: 0; padding: 0; }

A: You need to specify dots:true in your javascript code, for example, apply this, and you will see it works fine.
Here is working jsfiddle link for you.
LINK JSFIDDLE
$(function() {
    $('.banner').unslider({
        speed: 500,               //  The speed to animate each slide (in milliseconds)
        delay: 3000,              //  The delay between slide animations (in milliseconds)
        complete: function() {},  //  A function that gets called after every slide animation
        keys: true,               //  Enable keyboard (left, right) arrow shortcuts
        dots: true,               //  Display dot navigation
        fluid: false              //  Support responsive design. May break non-responsive designs
    });

});


text:
Q: Background changes size when typing i added a background to my android activity , but when i click on an EdiText , the background's size changes any idea ?

A: What is your code to add the background to your activity?
Try adding
android:windowSoftInputMode="stateVisible|adjustPan"
entry inside the <Activity> tag in your AndroidManifest.xml


text:
Q: How can I use Band to distribute a 2 by2 matrix on the offdiagnol of a biger matrix? I am trying to put the 2 by 2 sx = PauliMatrix[1] on the off-diagnoal of a matrix of size n by n. Amusing n=12, I tried this but did not work
SparseArray[{Band[{1, n - 1}, {n, n}] -> {sx}}, {n,n}] // MatrixForm;

this   is what I get

However, this is what I need

For sx, I can get the desired results with
SparseArray[{Band[{1, n}, Automatic, {1, -1}] -> 1}, {n,
   n}] // MatrixForm

but I need to do that for sy=PauliMatrix[2] and sz=PauliMatrix[3] too

A: You can use SparseArray`SparseBlockMatrix
sa =SparseArray`SparseBlockMatrix[
   MapIndexed[{#2[[1]], n - #2[[1]]} -> # &, ConstantArray[#, n/Length@#]]] &;

sa @ sx // MatrixForm

sa @ sy // MatrixForm

sa @ sz // MatrixForm


text:
Q: Convert from map to arraylist I tried to convert a Map<String,ArrayList<Object>> to ArrayList<Object> using this code:
Collection<ArrayList<Object>> coll = map().values();
List list = new ArrayList(coll);
ArrayList<Object> arrayList = new ArrayList<>(list.size());
arrayList.addAll(list);

However, the arraylist I got still groups objects by key still as collection.
How can I convert to ArrayList of separate Objects?

A: You can use Java 8 Streams:
List<Object> list =  map.values().stream()
                         .flatMap(ArrayList::stream)
                         .collect(Collectors.toList());

Without Streams, you'll have to iterate over the elements of your first List and call arrayList.addAll() for each of them separately.

A: A non stream version would be:
List<Object> accumulator = new ArrayList<>();
for(ArrayList<Object> a : map.values())
      accumulator.addAll(a);

A: same result can be achieved by using following traditional approach as well -
Map<String, ArrayList<Object>> map = new HashMap<>();
        ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add("data1");
        objects1.add("data2");
        objects1.add("data3");
        map.put("key1", objects1);
        ArrayList<Object> objects2 = new ArrayList<>();
        objects2.add("data1");
        objects2.add("data2");
        objects2.add("data3");
        map.put("key2", objects2);
        Collection<ArrayList<Object>> collections = map.values();
        List<Object> list = new ArrayList<>();
        for(ArrayList<Object> collection : collections) {
            for(Object obj : collection) {
                list.add(obj);
            }
        }
        System.out.println(list);

It will print the output as :

[data1, data2, data3, data1, data2, data3]


text:
Q: How do i send a message in telegram to someone from whom i only have a chat ID? I only have a chat id number from someone and i have no other information, i have not been in contact with him in Telegram before.
How can i send a message to him only with the chat ID or get his username only with the chat ID.
I know the following link, where there is chat ID, takes me to the chat page with the person.
tg://openmessage?user_id="Chat ID Number"
But this link works when i have already contacted the person in question, or an in a group, or have spoken, or have her number.
What is it like when i have no information about the person in question and only have a chat ID?
Thanks for your reply.

A: It's not possible. You should as you said have encountered them in your dialogs or contacts or any mutual group.
There aren't any known methods to bypass this restriction.