text:
Q: How to select only
* with a
*? I have an
 that contains another
 and
.
I want to be able to access either
 and apply different functionality to each.
I've been going with the approach of:
Example A:

If this
 contains a
, do this when clicking on the
.

Example B:

If this
 does not contain a
, do this when clicking on the
.

It's not working though, so I'm trying to test the basics.
Example A seems to select both
's, even the nested one that does not contain a
.
HTML

i do have a ul - i should be green

i dont have a ul - i should be red

i dont have a ul - i should be red

i dont have a ul - i should be red

jQuery
// why does this first condition cause both li's to be green?

$("li:has(ul)").css('background','Green');

// uncomment the following and only one is green

//$("li:not(:has(ul))").css('background','Red');

jsFiddle
http://jsfiddle.net/rwone/H5ZdE/2/
Edit:
Just to clarify, I am wanting to be specifically selective so that I can apply different click functionality to each
, so that is why I need to figure out how to select them accurately and not just rely on 'overiding' inherited styles etc.

A: // why does this first condition cause both li's to be green?
$("li:has(ul)").css('background','Green');

The above line does NOT cause both li to be green. It causes the first parent li only to be green. However, because the child li (which does not contain a ul) does not have a background color of its own, it appears to be green because it is inheriting its parent's background color.

A: The HTML and Javascript you've written conflict. The second
 is nested inside the first, and because it's styled background green, all child elements are inside that
 background.
See here: http://jsfiddle.net/H5ZdE/4/
The Javascript is not actually styling that second
 to background green. It's simply inside the
 whose background is green.

A: For selecting an li that has a nested ul use
$('li ul').parent()
(this will return the parent li tags of the selected ul tags. You can use li>ul as well)

A: try this
$("li:has(ul)").css('background', 'green')
$('li ul').css('background', 'red')

http://jsfiddle.net/H5ZdE/6/

A: Solution:
The following achieves the desired results ie separate functionality for top level and nested
's.
To be honest I don't yet really know how it works, but it works and I added a bit of extra functionality to test things out.  But no marks needed for code prettiness.
HTML:

test

test

// etc

CSS
#container {
height: 205px;
overflow-y: auto;
width: 400px;
}

.select {
border: 2px solid red !important;
}

.select_blue {
border: 2px solid blue !important;
}

.squares {
list-style: none outside none;
margin: 0;
padding: 0;
white-space:nowrap;
}

#container ul li {
background: none repeat scroll 0 0 #FFFFFF;
border: 2px solid #CCCCCC;
border-radius: 4px;
cursor: pointer;
display: inline-block;
height: 100px;
margin-right: 25px;
vertical-align: top;
width: 100px;
}

jQuery
// just for

$(document).on("click","ul.squares > li:nth-child(1n-7)", function (e) {
$(".hidden_li").hide();
$(this).find(".hidden_li").fadeIn();
$("ul.squares > li:nth-child(1n-7)").removeClass("select");
$(this).addClass("select");
e.preventDefault();
//alert("i am a li");
});

// just for nested

$(document).on("click","ul.nested > li", function (e) {
e.stopPropagation();
$("ul.nested > li").removeClass("select_blue");
$(this).addClass("select_blue");
e.preventDefault();
alert("i am a nested li");
});

More comments and demo on jsFiddle:
http://jsfiddle.net/rwone/H5ZdE/31/


text:
Q: Raise an event whenever a property value gets changed I have a class having 2 properties:
@property (copy) NSString *name; //name of the file
@property (copy) NSString *path; //path of the file
@property NSImage *img; //icon of the file

Problem
I want to name and img auto fill whenever path is changed like an event should be raised whenever the path is changed so that I can refresh name and img.
Many thanks in advance. Please note that I am 2 months new to objective-c and I was in the .net world from the last 2 years.

A: You can go with a well established KVO (Key-Value Observing) technique:
Step 1 : Assuming you already have a model class say MyData with these properties, set your controller class or where you are creating that model object as observer for path something like this:
MyData *data = [[MyData alloc] init];
[data addObserver:self forKeyPath:@"path" options:NSKeyValueObservingOptionNew context:NULL];

Step 2 : Implement observeValueForKeyPath:ofObject:change:context: method to listen to any change in the path property. Something like this:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    MyData *myData = (MyData *)object;
    myData.name = @"My Name";
    myData.image = // Set your image here
}

Step 3 : Importantly, do not forget to remove yourself as observer of this property whenever your object is being deallocated. Otherwise you may end up crashing!

A: (Updated to prevent looping)
You could use a setter function. Instead of using MyClass.name = ... declare a function in that class and use that to change the value:
- (void) setPath:(NSString*)newvalue{
    _path = newvalue;
    [self updateNameAndPicture];
}

Then, when you change it, use
[InstanceOfMyClass setPath:@"/new/path/"];

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to know from which point HttpClient task cancellation is triggered I have the following code to fetch the bearer token and then call the Web API in a c# application.
public async Task<HttpResponseMessage> SendHttpRequest()
{
    HttpResponseMessage response = null;
    try
    {
        HttpClient client = new HttpClient();
        string accessToken = await GetBearerToken(resourceUrl, clientId, clientSecret, tokenProviderUrl);
        if (!string.IsNullOrEmpty(accessToken))
            httpRequest.Headers.Add("Authorization", ("Bearer " + accessToken));

        response = await client.SendAsync(httpRequest);
    }
    catch(Exception ex)
    {
        log.Error("Exception raised while sending HTTP request");
        log.Error("Exception details : " + ex.Message);
    }

    return response;
}

public async Task<string> GetBearerToken()
{
    HttpResponseMessage response = null;
    HttpClient client = new HttpClient();
    string token = "";
    try
    {
        var request = new HttpRequestMessage(HttpMethod.Post, tokenProviderUrl);
        request.Content = new FormUrlEncodedContent(new Dictionary<string, string> {
            { "client_id",clientId},
            { "client_secret", clientSecret },
            { "grant_type", "client_credentials" },
            { "resource", resource },
        });

        response = await client.SendAsync(request);
        var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
        token = payload.Value<string>("access_token");
    }
    catch (HttpRequestException ex)
    {
        log.Error("Error in GetToken : " + ex.Message.ToString());
    }
    return token;
}

The problem I'm facing here is,some times , this code throws an exception saying "Task was cancelled" once in a while and not everytime. I have searched online and came across this answer.So I have checked if the task was being cancelled.Then I increased the Timeout to 30 minuties as mentioned in that answer.
Now the strange thing is, the task waits for 30 mins (or whatever timeout we have specified) and then throws Task was cancelled exception.This is driving me crazy.
I want to know why is the Task getting cancelled when we are not requsting for it explicitly and who or from where the task is getting cancelled? Is there any way to find the source of the cancellation request?
Any help in this regard is highly appreciated as I'm unable to figure out the issue.
Please assume that all the variables have correct values though it is not mentioned here.
EDIT
Exception Message :

A task was canceled.

This is the Exception Stack Trace :

Exception StackTrace :    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.Net.Http.HttpClient.d__58.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
  at SampleProject.d__2.MoveNext() in
  C:\Users\SampleProject\HttpHelper.cs:line 145
  --- End of stack trace from previous location where exception was thrown ---


text:
Q: Ag-grid getRowStyle doesn't work properly I am trying to implement a row style such that if important columns are missing a value, then it should be red (like an alert). I have the following logic:
(defn missing-requirements? [params]
  (not (every? (js->clj (.-data params)) @state/important-tags)))

And this is the main function that is being rendered
(def ag-adapter (r/adapt-react-class (.-AgGridReact js/agGridReact)))

(defn home-page []
  [:div [:h2 "Ekspono tag-model"]
   [:p "My portfolio / Top Index " [:a {:style {:background-color "#C0C0C0" :float "right" :color "black"}
                                        :href "https://www.google.com" :target "_blank"} "Show problems"]]
   [:div {:className "ag-theme-balham" :style {:height 200 :width 700 :color "purple"}}
    [ag-adapter {:modules "AllCommunityModules"
                 :columnDefs  @state/cols
                 :rowData @state/rows
                 :defaultColDef {:sortable true
                                 :filter "agTextColumnFilter"
                                 :floatingfilter true
                                 :resizable true
                                 :flex 1
                                 :width deafult-col-w}
                 :getRowStyle (fn [params] (if (error/missing-requirements? params) {:background-color "Green"}))
                 :sidebars "filters"
                 :onGridReady (fn [params]
                                (:gridApi (.-api params))
                                (:gridColumnApi (.-columnApi params)))}]]])

Just :rowStyle {:background-color "red"} works fine. Does someone know what could be wrong? I have ag-grid-react version 21.0.1-1 as a dependency.

A: It was solved by adding #js as shown below
:getRowStyle (fn [params] (if (error/missing-requirements? params) #js {:background-color "Green"}))


text:
Q: object to datetime conversion_ converting from mm/dd/yyyy object value type to date type (python, pandas) All variables are object dtype. I'd like to convert the dtype from object to datetime.
    df = pd.DataFrame(
                    {"ID":['A','B','C','D','E'],
                     "date":['4/12/2017','4/27/2017','4/28/2017','4/29/2017','4/210/2017'],
                     })

What I've 3 different approaches. First,
df['date'] = pd.to_datetime(df['date'], format="%m-%d-%Y")

This didn't work out, giving me value error saying "time data '4/12/2017' doesn't match format specified"
Second,
parse(exerciseCsv['mostRecentExerciseDate'], dayfirst=True)

Third,
[datetime.strptime(x, '%m/%d/%Y') for x in exerciseCsv['mostRecentExerciseDate']]

All of above didn't work out. This looks like a simple task, can anyone help me how to get this done and explain me why this isn't working?

A: I think you need add parameter errors='coerce' if possible some bad data, which are converted to NaT (NaN for datetime):
df['date'] = pd.to_datetime(df['date'], errors='coerce')
print (df)
  ID       date
0  A 2017-04-12
1  B 2017-04-27
2  C 2017-04-28
3  D 2017-04-29
4  E        NaT

If only typo in last value:
df = pd.DataFrame(
                    {"ID":['A','B','C','D','E'],
                     "date":['4/12/2017','4/27/2017','4/28/2017','4/29/2017','4/21/2017'],
                     })

df['date'] = pd.to_datetime(df['date'])
print (df)
  ID       date
0  A 2017-04-12
1  B 2017-04-27
2  C 2017-04-28
3  D 2017-04-29
4  E 2017-04-21

As mentioned Stephen Rauch in comment need pattern change by data - add / instead -:
df['date'] = pd.to_datetime(df['date'], format="%m/%d/%Y")
print (df)
  ID       date
0  A 2017-04-12
1  B 2017-04-27
2  C 2017-04-28
3  D 2017-04-29
4  E 2017-04-21


text:
Q: Does the size of the node_modules folder matters during cold starts for cloud functions? I know that you should only import the required modules inside the index file's global scope to reduce the time of the cold starts.
But I haven't yet found out that if the size of the node_modules folder (or the length of the dependencies property of the package.json file) matters for cold starts in case of cloud functions or only the imported modules count?

A: The size doesn't matter! When you publish your code, a container is built (with buildpacks). This container is cached and so, when the function start, the container don't have to be downloaded.
There, the size don't impact the startup time (because there isn't download).
HOWEVER, a large node_modules folder (and more generally, in any languages, a large number of dependencies) can mean a lot of things initialized at startup (services, connexion to database,...). If it's in eager mode, that increases the startup duration.
Prefer a lazy initialization of your components, even the global ones. Prefer also the light frameworks (or no framework) instead of big Berta!!
EDIT
There is no cache policy management for the functions version. When a version is built and active, the image is cached, that's all. When a new is built, the previous will be evicted, a day. You can't manage this, it's serverless!
To insist on the size doesn't matter, I found 2 links about Cloud Run. Yes, Cloud Run!! In fact, Cloud Run and Cloud Functions share the same backend and the same behavior (your function is packaged in a container (as explained before) and served with the same logic as the Cloud Run containers)
So, here the official Google documentation and an unofficial FAQ maintained by a guru of Cloud Run (Ahmet, Dev Advocate on Cloud Run @Google)
Eventually, the size doesn't matter, but I found that the language matters!! In this article also wrote by a Googler, there is an explanation of NodeJS startup behavior

When a module boots, node.js resolves all require() calls from the entry point using synchronous I/O, which can take a significant amount of time if the number of dependencies are large, or if the content itself requires a lot of linking.

So, it's more a language problem and optimization to perform (lazy loading?) than a platform issue. The article provides many way to optimize the code!

A: under the hood when you deploy a cloud function, Google will create an image from your code source located into GCS. This image will embbed all runtime libraries needed by your source code to run. Each time you need a new instance of your function Google will start a container from this image.
Now, container "physics" directly relates the startup time with the size of your image. The thiner your image is, the quicker is the startup time. So yes, it kind of matters :)
More info in the official GCP page.


text:
Q: How to access html page before a shiny app The code below, when executed, first enters an html page, where it asks for a username and password. Therefore, how can I register a username and password so that I can enter the shiny APP? Maybe use some php code along? I know there are shiny packages that work with login and password, however, I would like to use an html page that I created myself to access the shiny app.
Shiny code
library(shiny)
ui <- fluidPage(

    sidebarLayout(
        sidebarPanel(

            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30)
        ),

        mainPanel(
           plotOutput("distPlot")
        )
    )
)

server <- function(input, output) {

    output$distPlot <- renderPlot({
        x    <- faithful[, 2]
        bins <- seq(min(x), max(x), length.out = input$bins + 1)

        hist(x, breaks = bins, col = 'darkgray', border = 'white')
    })

}

shinyApp(ui = htmlTemplate("www/index.html"), server = server)

Output

Index.html
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.101.0">
    <title>Signin Template · Bootstrap v5.2</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/5.2/examples/sign-in/">

<link href="assets/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="signin.css" rel="stylesheet">

  <form>

Insert your login and password

      <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com">
      E-mail

      <input type="password" class="form-control" id="floatingPassword" placeholder="Senha">
      Password

        <input type="checkbox" value="remember-me"> Remember me

    <button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>

© 2017–2022

  </form>

A: I recommend the shinymanagerpackage (https://datastorm-open.github.io/shinymanager/) as it does provide a good, reliable and (I guess) safe way to have a login-page for your app.
You can even store the credentials in a small, local SQLite-database that again is password protected.
It also comes with a simple administration panel as well as access-statistics.

A: you can use php's get and post requests to use username and password loin page using html reference https://www.w3schools.com/tags/ref_httpmethods.asp


text:
Q: String to date conversion issue in PHP5.6 date('m/d/Y', strtotime('7-Jan-69'))

It gives output as 01/07/2069, Where
date('m/d/Y', strtotime('7-Jan-75'))

This gives output as 01/07/1975, Why is so and what is the catch?

A: From the docs:

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC)

Any date before 1970 will be understand as date after 1970

A: do you need something like this?
<?
    // function to convert string and print
    function convertString ($date)
    {
        // convert date and time to seconds
        $sec = strtotime($date);

        // convert seconds into a specific format
        $date = date("Y-m-d H:i", $sec);

        // append seconds to the date and time
        $date = $date . ":00";

        // print final date and time
        echo $date;
    }

    // Driver code
    $date = "06/12/2014 04:13 PM";
    convertString($date);
?>

A: To fix that you can use DateTime instead of strtotime() like below,
<?php
$date = $dt = new DateTime('7-Jan-75');
echo $date->format('m/d/Y');
?>

Reason for not working in your case with strtotime:

If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999.
  See the notes below for possible differences on 32bit systems
  (possible dates might end on 2038-01-19 03:14:07).

DEMO: https://3v4l.org/d8eoK


text:
Q: How to make external dependencies on a shared items project in VS? I am in need of sharing some header files between two different projects. So I created a shared items project, and now I can't figure out how to add external dependencies to it, so I could use includes from the WDK 10 shared folder. Did anyone run into this problem before? I can still add external dependencies on a library project, but somehow not on shared items.

A: As the article says

These "shared items" projects don't participate in build but they can
contain any number of C++ headers and sources.

And you need to add the dependencies to the actual build project.


text:
Q: How to get right amplitudes (without playing) of the audiotrack samples with web audio api I did some experiments with the samples volume data, provided to me by web audio api and it appeares that they are different from the data got from other programs like audasity for example. It shows the duration of audio longer at about 40 seconds if we take divide samples array length to sample rate (leftChannel.length/44100 in my case), and also where audacity shows loud samples in audio, my script shows quiet (almost silent sometimes). And I played pieces reported by my script as quiet in audacity and there is definitely loud sound.
So the question is: is my way to find ampitudes of audio samples correct? And what is wrong with my code?
I've read the thread about creating waveform for audiotrack Create a waveform of the full track with Web Audio API
and there is good example of what I used, so here is my code:

(function($) {

  window.AudioContext = window.AudioContext || window.webkitAudioContext;
  var context = new window.AudioContext(); // Create audio container
  var audioData;
  var checkPoint = 21; //this is point in seconds just for debugging, remove later!!
  function decode(audioData) {
    try{
        context.decodeAudioData(audioData,
        function(decoded){
            drawSound(decoded);
            playAudio(decoded);
        },
        function(){ // do nothing here
        });
    } catch(e) {
        console.log('decode exception',e.message);
    }
  }

  function drawSound(buffer) {
    var leftChannel = buffer.getChannelData(0);
    console.log('audio duration: ' + leftChannel.length/44100 + ' sec');
    for (var i = 0; i < leftChannel.length; i++) {
      var volume = leftChannel[i];
      //draw(volume, i);

      //this is just for debugging, remove later!!
      if (Math.abs(i - checkPoint * 44100) < 100) {
        console.log(leftChannel[i]);
      }

    }
  }

  function playAudio(buffer) {
    console.log('start playing audio');
    var audioTrack = context.createBufferSource();
    audioTrack.connect(context.destination);
    audioTrack.buffer = buffer;
    audioTrack.start();
  }

  $(document).ready(function() {
    $('body').append($('<input type="text" id="checkpoint" />'));
    $('#checkpoint').change(function() {
      checkPoint = $(this).val();
    });
    $('body').append($('<input type="file" id="audiofile" />'));
    $('input[type="file"]').change(function() {
      var reader = new FileReader();
      reader.onload = function(e) {
        audioData = this.result;
        decode(audioData);
      };
      reader.readAsArrayBuffer(this.files[0]);
    });

  });
})(jQuery);
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  </head>
  <body>

  </body>
</html>

A: If you think this is a bug in Chrome, please file a bug at crbug.com/new. And provide one audiotrack that produces different results and details about the different machines.
Note also that in chrome, ffmpeg is used to decode the files.  The decoded file could differ in length from audacity.

A: I've made more thorough measurements and more testing and found that there is no  error in my script,  BUT!! web audio api gives the results equal to audasity both for the length of audiotrack and for the amplitudes on one of my computers (both in Chrome and Firefox) and wrong results on another computer (again browser independently), so I conclude that web audio api uses some low level processor dependent features because I have the same OS (windows 7) on both my computers, the only difference is hardware.
The code, provided in my post is working as expected.

A: Thanks to Raymond Toy I've managed to solve this issue. It appeares that result returned by buffer.getChannelData(0) depends from computer audiocard's sample rate (which you can find from context.sampleRate). And if you want to find the length of track you should do it like this:
var samples = buffer.getChannelData(0);
var duration = samples/context.sampleRate;

And offset of sample from start in seconds is:
var sample = samples[i];
var offsetInSeconds = i/context.sampleRate

My mistake was that I used mp3 audiotrack's sample rate in formulas and this caused errors on computer with different audiocard sample rate.
As Raymond Toy noticed, if you need only duration of audio you can get it even simpler like this:
var duration = buffer.duration;


text:
Q: HTTP Compression with ASP.Net MVC on IIS 6.0 I'm serving some farily large webpages (~600k) via MVC over IIS 6.0. Is there any opportunity to use HTTP compression to reduce the amount of bandwidth used?
Is this possible without a file extension to identify to IIS that it should compress the MVC response?
Thanks!
Chris

A: When you enable wildcard mapping, IIS 6 compression no longer works for extensionless URL (like MVC) because IIS 6 does not see any extension which is defined in IIS Metabase.
One solution is to use a custom HttpModule to do the compression for dynamic requests by yourself. There is no magic in Gzip : it's simply GzipStream.
there is an example here and sample code here.


text:
Q: Can't commit to SVN [500 internal server error] Recently svn is returning error 500 to tortoise when we trying commit  some files .pdf and .js (printscreen)
I am using windows 7, tortoise last version, and i turned off my antivirus
I emailed  to server team, but they have not found the solution

A: an internal server error is always an error on the server side. The only way to get more information on this is to check the Apache error log file on the server.

A: Check if the Password is expired or not by Deleting the SVN credentials and try committing again. It worked for me follow the below steps.
Type %APPDATA% in windows start and open the folder location. Navigate to svn.simple folder (Roaming -> Subversion -> auth -> svn.simple). Delete the file present in this folder. Move to eclipse, Right click on the Project, Team -> Cleanup. Now try committing.


text:
Q: innerhtml equivalent in jquery is not working My div is not showing content what I am expecting
My controllerAction:
    ///
    /// GetCountiresForManufacturer
    ///
    /// <returns></returns>
    [Authorize(Roles = "Administrator")]
    [AcceptVerbs(HttpVerbs.Get)]
    public string GetCountiresForManufacturer(string manufacturer)
    {
        var sb = new StringBuilder();
        var rows = new List<Manufacturer>();
        var data = new Dictionary<string, List<Country>>();
       // var countries = new List<Country>();
        if (manufacturer.StartsWith(","))
        {
            manufacturer = manufacturer.TrimStart(',');
        }
        string[] manufacturers = manufacturer.Split(',');
        foreach (var s in manufacturers)
        {
            var manufacturerRow = _manufacturerRepository.GetManufacturerByName(s);
            rows.Add(manufacturerRow);
        }

        foreach (var row in rows)
        {
            if(row==null)
            {
                continue;
            }
            var countriesList = _countryRepository
           .GetAllCountriesForManufacturer(row.Id);
           // countries.Add(countriesList);
            data.Add(row.Description, countriesList.ToList());
        }
        foreach (var s in data)
        {
            sb.Append(" <input id =\"Brand\"  name=\"Brand\" value=\""+s.Key+"\"/>");
            foreach (var manufacturer1 in s.Value)
            {
                sb.Append("<input id =\"Dove\" type=\"checkbox\"
               value=\""+manufacturer1.Name+"\"/>");
            }
        }

        return sb.ToString();
    }

My view:
        <%@ Control Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<EmsAdmin.Models.User>" %>
    <%@ Import Namespace="EmsAdmin.Models" %>

    <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and
      try again.") %>
    <% using (Html.BeginForm(new {}))
   {%>
  <%= Html.AntiForgeryToken() %>
 <%: Model.Id %>
<%= Html.HiddenFor(e=>e.SelectedBrands) %>

<%= Html.LabelFor(e=>e.Name,"Name:") %>
<%= Html.TextBoxFor(e => e.Name,  new { @style = "width: 255px;" })%>
<%= Html.ValidationMessageFor(e=>e.Name,"") %>

<%= Html.LabelFor(e=>e.Email,"Email:") %>
<%= Html.TextBoxFor(e => e.Email, new { @style = "width:250px;" })%>
<%= Html.ValidationMessageFor(e=>e.Email,"") %>

<%= Html.LabelFor(e=>e.Corporation.Description,"Corporation:") %>
<%= Html.TextBoxFor(e => e.Corporation.Description, new { @style = "width:250px;" })%>
<%= Html.ValidationMessageFor(e=>e.Corporation.Description,"") %>

Approve User

<%= Html.LabelFor(e=>e.Approve,"Aprrove User:") %>
<%= Html.CheckBoxFor(e=> e.Approve,Model.Approve) %> Switch this on if you
  want to
    add regitrar
<%= Html.ValidationMessageFor(e=>e.Approve,"") %>

Multi Select Brands If Required:

<% foreach (var manufacturer in Model.Manufacturer)
   {%>
 <input type="checkbox" id="<%: manufacturer.Id %>" class="checkbox" value="<%:
 manufacturer.Description %>" /><%: manufacturer.Description %>

<%} %>
<input type="submit" value="UpdateBrands" class="brands" />

<input type="submit" value="Save" />
<%= Html.ActionLink("Cancel","Details",new {id=Model.Id},new {@title="exit without
 saving"}) %>

 <% } %>


text:
Q: How to find and use the row number of a specific value using an Excel macro I know this question has been addressed in several places here, but none so far are solving my problem, and I can't think of anything else to search for.
Specifically, within an Excel macro I need to find the row number of the cell on a specific sheet that has a value that matches a variable. Then I need to use that row number to perform an action on another cell in that row. The value I'm looking for will be in Column C, then the action will be performed in Column A.
I have tried these solutions but no luck yet:
How to find the row number of a specific value in Excel using vbscript
Assigning the value of a worksheet cell to a constant
I've tried pasting my variable value into B1 as a placeholder, but I can't find a way to find the matching value elsewhere on the sheet (there will be only one other). I've tried:
Public Const SKUVALUE As String = "$B$1"

but of course that returns the quoted string, not the value of the B1 cell.
If it would help for me to explain the bigger picture of my project I will be happy to do that, but it's somewhat complicated. In short I am trying to bring content from one sheet to another sheet based on a numeric value (SKU) that is assigned to a specific row on each sheet. The row numbers will not match because of filters being applied on the first sheet. If I can mirror those filters on the second sheet then I would know the row number, but that sounds like a nightmare to implement. I can't begin to think how to do it.
I'm really at my wit's end with this. Any suggestions will be much appreciated.
Thank you.

A: You could try to use a loop to accomplish this. Depending on your data this should work. You did not provide much detail into the action to perform in column A or how your variable is declared so this is a start.
 Sub Macro1()
' This macro will loop through each row and look for your variable in column C if it finds your variable in column C it will then perform your action in column A of that same row.

Dim variable As String
variable = "insert value or cell here"

With Sheets("Sheet1")
    LR = .Cells(Rows.Count, "C").End(xlUp).Row
    For i = LR To 2 Step -1
        If .Cells(i, "C").Value = variable Then
            .Cells(i, "A").Value = "perform action here"
        End If
    Next i
End With

End Sub

A: UPDATE: My problem was with using variables correctly, and a solution appears to be:
Public Const SKUVALUE As String = "$B$1"
Public imageValue As Long
Public n As Long

Then:
Sub FindFirstInstance()
Dim ws As Excel.Worksheet
Dim FoundCell As Excel.Range
Dim imageValue As Long: imageValue = Range(SKUVALUE).Value
Set ws = ActiveSheet
Set FoundCell = ws.Range("C:C").Find(what:=imageValue, lookat:=xlWhole)
If Not FoundCell Is Nothing Then
    MsgBox (imageValue & " found in row: " & FoundCell.Row)
n = FoundCell.Row
MsgBox "n is " & n
Range("$C$1").Value = n
Else
MsgBox (imageValue & " not found")
End If
End Sub

The problem I'm continuing to have is the global/public variables not working between sheets. That's why I'm putting the value of n into C1 above, so I can grab it later. But I will keep working on that. For the moment, I think I have what I need. Many thanks.


text:
Q: How to make a post request with async fetch in mvc and JavaScript? Im trying to fetch subcategories from my mvc application with reference to the category id with async fetch
I already fetched the categories and its all working
but when i try to fetch the subcategories with a post request it doesn't work!
//SubCategories

            const categoriesLiList = document.querySelectorAll('.btn');

            const getSubCategories = async () => {

                const liBtnClick = list => {
                    nodeListForEach(list, cur => {
                        cur.addEventListener('click', () => {
                            debugger;
                            let categoryId = cur.value;
                            console.log(categoryId);

                            const getSubCategoriesById = async (url = ``, data = {}) => {
                                const subsResult = await fetch(url, {
                                    method: "POST",
                                    mode: "cors",
                                    cache: "no-cache",
                                    credentials: "same-origin",
                                    headers: {
                                        "Content-Type": "application/json"
                                    },
                                    redirect: "follow",
                                    referrer: "no-referrer",
                                    body: JSON.stringify(data)
                                });

                                const subsData = await subsResult.json();

                                const populateSubCategories = arr => {
                                    arr.forEach(cur => {
                                        const subCategoriesLi = `
                                <li>${cur.Name}</li>
                            `;

                                        document.querySelector('#subcategories').insertAdjacentHTML('beforeend', subCategoriesLi);

                                    });
                                };

                                populateSubCategories(subsData);
                            };

                            getSubCategoriesById(`/controllername/jsonresult/ID`, { ID: categoryId });
                        });
                    });
                };

                liBtnClick(categoriesLiList);

            };

            getSubCategories();

The result should be the data from the api but its not reading the ID param.
what should i change in my post request??

EDIT: I am such an idiot lol my api wasn't working correctly, so for future purposes always test your apis with postman :)
also, there's no need for a post request! just a normal fetch get reques:
await fetch(`/controllerName/JsonResult/${categoryId}`);

A: I am such an idiot lol
my api wasn't working correctly, so for future purposes always test your apis with postman :)
also, there's no need for a post request! just a normal fetch get reques:
await fetch(`/controllerName/JsonResult/${categoryId}`);


text:
Q: Java Persistence Entitymanager - Select from another query's result set I currently have the query stated below. I know this works as a SQL query, but because I am using the EntityManager, from javax.persistence, it requires JPQL. And I don't know JPQL. If there is a way to rewrite this in JPQL that would be nice.
Query q = entityManager.createNativeQuery("
    WITH original AS (SELECT *, COUNT(ref) as c FROM Tri WHERE triH IN :list GROUP BY ref
    SELECT ref FROM original WHERE c = :amtTri");
q.setParameter("list", posTri);
q.setParameter("amtTri", posTri.size());

Actual query:
WITH original AS (SELECT *, COUNT(ref) as c FROM Tri WHERE triH IN :list GROUP BY ref
SELECT ref FROM original WHERE c = :amtTri

I am trying to do this in a Quarkus project using the Repository method, if there is a way to use that, that would also be fine
Thanks in advance!

A: I believe that using the EntityManager don't obligates you to use JPQL, you can also use Native Queries.
As your query looks not so simple (for me at least), I would do it using Native Queries and not JPQL. You can run Native Queries using the EntityManager from javax.persistence. This tutorial explains how you can do this.


text:
Q: python 3.8 , Problem installing matplotlib . Visual Studio 2010 build tools not found when trying to install matplotlib via pip i get this

"FreeType version 2.3 or higher is required. You may set the
  MPLLOCALFREETYPE environment variable to 1 to let Matplotlib download
  it."

so i use command
set MPLLOCALFREETYPE=1

and try again and get this instead

error MSB8020: The build tools for Visual Studio 2010 (Platform
  Toolset = 'v100') cann ot be found. To build using the v100 build
  tools, please install Visual Studio 2010 build tools.  Alternatively,
  you may upgrade to the current Visual Studio tools by selecting the
  Project menu or right-click the solution, and then selecting "Retarget
  solution".
  [C:\Users\digikwondo\AppData\Local\Temp\pip-install-3ci6qqh3\matplotlib\build\freetype-2.6.1\builds\windows\vc2010\freetype.vcxproj]
      Done Building Project "C:\Users\digikwondo\AppData\Local\Temp\pip-install-3ci6qqh3\matplotlib\build\freetype-2.6.1\builds\windows\vc2010\freetype.vcxproj"
  (default targets) -- FAILED.
      Done Building Project "C:\Users\digikwondo\AppData\Local\Temp\pip-install-3ci6qqh3\matplotlib\build\freetype-2.6.1\builds\windows\vc2010\freetype.sln"
  (Clean;Build target(s)) -- FAILED.
Build FAILED.

i am building on windows 10 and have the following visual studio build tools packages installed

*

*Windows Universal C Runtime

*C++ Build Tools core features

*MSVC v142 - VS 2019 C++ x64/x86 build tools (v14.24)

*C++ CMake tools for Windows

*.NET Framework 4.8 SDK

*.NET Framework 4.6.1 targeting pack

*C++/CLI support for v142 build tools (14.24)

*Windows 10 SDK (10.0.17763.0)

*Windows 10 SDK (10.0.17134.0)

*Windows 10 SDK (10.0.16299.0)

*Windows 10 SDK (10.0.18362.0)

*C++ core features

*Windows Universal CRT SDK

*NuGet targets and build tasks

*.NET Framework 4.6 targeting pack

*C++ Universal Windows Platform runtime for v142 build tools

*Visual Studio SDK Build Tools Core

*C++ Windows XP Support for VS 2017 (v141) tools

*MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)

*MSVC v140 - VS 2015 C++ build tools (v14.00)

*C++/CLI support for v142 build tools (14.24)

*C++ Modules for v142 build tools (x64/x86 – experimental)

*MSVC v142 - VS 2019 C++ x64/x86 build tools (v14.24)

*C++ CMake tools for Windows

*Testing tools core features - Build Tools

*C++ AddressSanitizer (Experimental)

i have a feeling there is something simple i am missing here. would appreciate any guidance
as im quite stuck.  (installing with python 3.7 in separate venv instead of python 3.8 works ok on same win 10 machine. )


text:
Q: Bootstrap data-spy doesn't make my navbar full size

       A09hopper.xyz

Home

Page 1

Page 2

 Sign Up

 Login

Main Page

This is the main page. Just like a contents page.

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

Text

This is my code. At the top of the page it is full width. When data-spy kicks in it   starts to go to quarer of the size. I have no idea why though?
If this can be solved with CSS please can someone say what needs to be fixed and I will toy around with it until I get it right.

A: Please go through this link
Check the code and fix this.
Hope it will help you.


text:
Q: ¿Cómo seleccionar una fila de un Jtable y almacenarla en un archivo? ¿Cómo podria seleccionar todos los elementos de una fila de un Jtable y almacenarlos en un nuevo archivo de texto por medio del evento MouseCliked?
hola buenas soy bastante novata en java, y estoy haciendo un programa donde manejo los archivos de texto al menos esta es mi primer ventana donde se visualizan por medio de un Jtable los datos que se ingresaron al primer archivo, entonces ahora lo que ocupo hacer es que por medio del evento MouseCliked seleccionar uno y almacenarlo en un nuevo archivo
pero sinceramente no me da la cabeza para pensar como podría hacer esto, osea tomar la seleccion y dividir cada string para luego almacenarlo en un nuevo archivo, ingresarlo es fácil porque ya lo hice y igual mostrarlo, pero ahora debo sacar el seleccionado y guardarlo en un nuevo archivo pero no se como podría hacer esto ? podrían darme una ayuda el evento mouseClick ya lo tengo pero nose como deberia hacer la logica para programar esto que les comento, les agradeceria de antemano que me explicaran como podria manejar el Jtable, para al darle click a uno de estos elementos se guarden el id,nombre,primer apellido, segundo apellido, tipo de prestamo y la renta a pagar en un nuevo archivo al darle al boton agregar usuario
uso netbeans
este es un poco el codigo que cree para hacer el recorrido y guardar en un arreglo todos los string de esa fila
 Object[] rowData = new Object[tabladatos.getColumnCount()];

        for(int i = 0 ; i < tabladatos.getColumnCount(); i++){

            rowData = (Object[]) tabladatos.getValueAt(tabladatos.getColumnCount(),i);
        }

        JOptionPane.showMessageDialog(null, rowData);
    }

A: Puedes crear un atributo de clase para que guarde el numero de fila al cual haces click en la tabla y cuando das click en el boton de guardar primero obtienes los valores de cada columna de la fila seleccionada.
Veamos el código.
public class TuClase extends javax.swing.JFrame  {
    private int seleccionFila;

    //obtenemos el número de fila seleccionada al dar click en la tabla
    private void tuTablaMouseClicked(java.awt.event.MouseEvent evt) {
        seleccionFila= tuTabla.rowAtPoint(evt.getPoint());
    }

    // evento al dar click en el boton agregar usuario
    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {
        //creamos variable locales para obtener los valores de cada columna de la fila seleccionada
        int id=Integer.parseInt(String.valueOf(tuTabla.getValueAt(seleccionFila, 0)));
        String nombre=String.valueOf(tuTabla.getValueAt(seleccionFila, 1));
        String apellido1=String.valueOf(tuTabla.getValueAt(seleccionFila, 2));
        String apellido2=String.valueOf(tuTabla.getValueAt(seleccionFila, 3));
        String tipoPrestamo=String.valueOf(tuTabla.getValueAt(seleccionFila, 4));
        double renta=Double.parseDouble(String.valueOf(tuTabla.getValueAt(seleccionFila, 5)));
        /*
         Agregas el código para guardar en el archivo, según la descripción de tu problema
         sabes como realizarlo
        */
    }

}


text:
Q: How can I prevent a scheduled task from running if the same task is already running? I have written a php script to check if there are any new files in a folder and, if any new files exist, upload them to a server.  These files can be quite large.  I want to run this script frequently-let's say every 5 min-as a scheduled task so that the files get moved to the server as soon as possible.  However, once the script is already attempting to upload a file, I do not want it to be run again, as I am afraid the second instance will overwrite the file that is already being uploaded to the server.
How can I run the script as a scheduled task unless the script is already running?

A: Assuming you're just setting the task to "Repeat" in the XP "Scheduled Tasks" system, no further action on your part is needed. Scheduled Tasks won't "Repeat" a task if it's already running.
If you want to override that default, you can check the box "If the task is still running, stop it at this time" to cause the task scheduler to kill the last instance before starting a new one (though it sounds like you probably don't want that).

A: The way I have done this is to run the task from a batch file that starts once a day shortly after midnight and runs until next midnight. The advantag of this is that because it's a single script you cannot get a second instance running. I suppose a disadvantage might be that you can predict exactly how often the script runs because it would wait a set time after each run. Anyhow if you're interested my script looks like:
rem *** Get the day number. When the day number changes that signals
rem *** the script to exit.

for /f "tokens=1" %%i in ('date /t') do set THEDATE=%%i
set THEDAY=%THEDATE:~0,2%

rem *** Open the log file

echo Starting Whatever >%LOGFILE%
date /t >>%LOGFILE%
echo . >>%LOGFILE%

rem *** Start the monitoring loop

:start

rem *** Run your script

rem Run the script here

rem *** Pause for 300 seconds

sleep 300

rem *** Check the day number. If it is still the same loop back to the
rem *** start of the monitoring loop.

for /f "tokens=1" %%i in ('date /t') do set THEDATE=%%i
if %THEDATE:~0,2% == %THEDAY% goto start

JR

A: In the windows task scheduler there is a checkbox (or options) for what to do if the task is already running when the task starts again.  You can set it not to start or run in parallel

A: The usual way is to test for some global thingy (often a specific empty file) when the task starts. If it exists, the task is already running. If not, set the global thingy, do your stuff, unset the global thingy when the task is done.
This has problems if the task fails without unsetting the global thingy. You may want to always unset it in the computer startup routine since the task can't be running if you've restarted. Better is to find a global thingy that goes away automatically when the task ends.


text:
Q: Regular expression to determine if phone number starts with a zero How would I go about ensuring that numbers entered into a field starts with a 0? My initial question was suggesting that the company wants to force users to input 0 first, but I think an elegant solution would work better.
    function creationValidationNumber(dataValues, setErrors) {
     let testData:any = {};

     if ("numberPrime" in dataValues) testData.numberPrime = /^[a-zA-Z][0-9a-zA-Z
     .,'-]*$/g.test(dataValues.numberPrime) ? "" : "Numbers must start with a 0";

     setErrors({ ...testData });

     return Object.values(testData).every((x) => x === "");
    }

I just don't know how to get the regular expression to test and throw an error if it doesn't start with 0
If anyone could please guide me on the right path.

A: You don't need regex for this. Just check if the first character is "0":
dataValues.numberPrime[0] == "0"

A: I don't know why you have a more complicated regex, all you need is:
/^0/


text:
Q: SqlServer 2012 - Column '' in table '' is of a type that is invalid for use as a key column in an index Depois de ver esse erro na hora de criar um índice NONCLUSTERED eu fiquei pensando se realmente seria necessário criar esse índice no seguinte cenário:
Tenho uma tabela com 11 colunas, uma coluna eu guardo uma URL, ou seja é uma coluna nvarchar(300), essa coluna aceita valores nulls.
Em um determinado momento eu preciso fazer um SQL para pegar os valores da tabela onde essa coluna não é nula. Por isso pretendia criar um índice , para acelerar isso.
Estou usando EF6 e SQLServer 2012. Existe ganho em se criar um índice nesse cenário? Se existe como eu o criaria?

A: Este índice não seria útil para este tipo de query que você descreveu.

Não devemos criar índices para colunas cuja informação varia muito pouco entre os registros.

Por exemplo, não faz sentido criar um índice para uma coluna que contenha sempre ou zero ou um. É pouco provável que um índice como este seja usado pelo banco pois um table scan (percorrer a tabela inteira em vez de usar o índice) na maioria das vezes seria mais eficiente.
Como a sua consulta verifica apenas se a coluna é ou não é nula, o que está sendo verificado é se ela se encontra em um de apenas dois estados possíveis, ou seja, assim como no exemplo dos zeros e ums, é muito pouco provável que este índice seja utilizado pois o table scan geralmente terá melhor performance.

Índices que não são utilizados nas consultas não deveriam ser criados pois apesar de não trazerem nenhum benefício ainda precisam ser mantidos pelo banco ou seja: ocupam espaço e consomem processamento.

Veja este artigo Microsoft para orientações gerais muito interessantes sobre o design de índices: SQL Server Index Design Guide.

Por fim, apesar de haver orientações gerais úteis, é sempre bom analisar o plano de execução das queries para identificar se em um cenário específico um índice deve ou não ser criado ou removido.


text:
Q: Exposing a vector of shared_pointers without giving ownership I have a simple class containing a vector of shared pointers:
class Bar {
public:
  /* stuff */
private:
  std::vector<std::shared_ptr<Foo>> foos;
};

I wish to expose my foos through a getFoos() function, that would not share the ownership of the objects. One way to do so would be:
std::vector<std::reference_wrapper<Foo>> Bar::getFoos() const {
  std::vector<std::reference_wrapper<Foo>> fooRefs;
  fooRefs.reserve(foos.size());
  for (auto& ptr : foos) {
    fooRefs.push_back(std::ref(*ptr));
  }
  return fooRefs;
}

but that's pretty ugly. Also, I'll most likely need to cache the results since this function gets called pretty often. More complexity, more ugliness.
Is there a cleaner/better way to deal with this issue?

A: I would expose the Foo by index and also give the possibility to obtain iterators to them
class Bar {
public:
  class FooIt {
    // Add typedefs for category etc
    std::vector<std::shared_ptr<Foo>>::iterator it; // maybe template on this to easily provide the const overload too
  public:
    Foo& operator*() const {
      return **it;
    }
    // write Functions to expose ++ etc of it
  };

  FooIt begin() {
    return FooIt{begin(foos)};
  }

  FooIt end() {
    retuen FooIt{end(foos)};
  }
  // Enables ranged for over Bar, only do if that makes sense for your Bar

  Foo& getFoo(size_t index) { // maybe even operator [] if appropriate
    return foos[index];
  }
};

Of course this is much boilerplate. But actually you can write the FooIt in a general, templated version if you have this problem at multiple places.

A: Possibly a range view with range-v3:
class Bar {
public:
  /* stuff */

     auto get_foos() const { return foos | ranges::views::indirect; }
private:
  std::vector<std::shared_pointer<Foo>> foos;
};

Similar to your std::vector<reference_wrapper>, but without extra vector.

views::indirect
      Given a source range of readable values (e.g. pointers or iterators), return a new view that is the result of dereferencing each.

Can also be done with view::transform.


text:
Q: How to download jasper server source code? How to download jasper server source code? From github: https://github.com/TIBCOSoftware/jasperreports I see only the old version, how to download newer version like 7.x, 8.x?
Thanks


text:
Q: Is it possible to control MPU6000 with Maxon controller Board? I am developing a robotic wrist in which I have two DC Motor+encoder pairs connected to a Maxon Escon Module 50/5 each. To control that the output of the wrist is correct, I want to place an IMU unit at the end to measure orientation. The MPU6000 seems like a cheap and easy solution. The setup would look like this:

The MPU would be connected to VCC, GND pins 11&12 and to two Analog In pins 27&29. I have been doing some research but there doesn't seem to be anybody who tried this in the past. Any help or suggestions are very much appreciated.
Best,
Chusi

A: Maybe you do not know what it is you really need, but this should have been obvious from skimming the functionality of the Maxon and MPU. Or even just looking at the block diagram you provided.
The MPU6000 communicates over I2C or SPI. It does not communicate over analog lines so there is no point to connecting it to the Maxon's analog inputs.
There was a possibility that the digital inputs  could support I2C or SPI, but if you skim the functionality of the Maxon you will see this is not the case. The digital and analog I/O on the Maxon are just for simple control and monitoring for motor driver use.
But on top of all of this, you cannot expect the Maxon to just know how to communicate with the MPU. The Maxon would need the capability to programmed like a microcontroller or processor. But it is just a motor driver. Nothing more.
So, no, you need a processor or microcontroller to communicate with the MPU and then command the Maxon. The good news is, this is not difficult or expensive. Even an Arduino could probably do it.


text:
Q: Bulk, partial updates with Django Rest Framework I want to partially-update multiple items at once. I've already added a mixin for allowing me to bulk-create (and that works well) but even though I've added a partial argument, it doesn't allow for patching a list.
I'm guessing that this is a routing issue. I need a new view to handle PATCH on / (rather than /id/), but I'm well out of my depth.
Existing answers for this don't work for 3.8, or at least haven't worked for me. What do I need to do to the following?
class ResourceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Resource
        fields = ('id', 'name', ...)
        read_only_fields = ('id',)

 class BulkMixin:
     def get_serializer(self, *args, **kwargs):
        if isinstance(kwargs.get('data', {}), list):
            kwargs['many'] = True
            kwargs['partial'] = True

        return super().get_serializer(*args, **kwargs)

class ResourceViewSet(BulkMixin, viewsets.ModelViewSet):
    serializer_class = ResourceSerializer

A: After ~10 hours banging my head against this wall, I decided that the right way could take a back seat and I'd make do with the hack way that works. I added the following gnarlfest to my viewset.
from rest_framework.decorators import action

@action(methods=['patch'], detail=False)
def bulk_update(self, request):

    data = {  # we need to separate out the id from the data
        i['id']: {k: v for k, v in i.items() if k != 'id'}
        for i in request.data
    }

    for inst in self.get_queryset().filter(id__in=data.keys()):
        serializer = self.get_serializer(inst, data=data[inst.id], partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

    return Response({})

If I patch in a list of [{id: 123, otherfield: "abc"}, ...] this will now bulk-partial update. I'm fairly sure this is doing n+1 queries and that it'd be a lot more efficient in raw ORM... but for now, it's infinitely better than n requests. Also, if the ID isn't in the queryset, it will pass over rather than erroring. That works for me, but may not for others.
I'll stick a bounty on this question in 48h to tempt in some good answers.

A: I would suggest not trying to implement this yourself. Consider using django-rest-framework-bulk. It supports bulk, partial updates and provides serializers, views, and a router to make things really simple to setup.


text:
Q: SVG graphic in FPDF I need SVG data to print to an FPDF generated PDF. I'm bringing in said data from a post variable named $svg. When I try and write the variable to the page I get the entire data in text, not as an image (as expected), is there a way to get FPDF to draw the $svg on to the PDF? Below is my terrible attempt. Thanks.
    $pdf->Write( 6, $svg);

A: In PHP TCPDF supports .svg (http://www.tcpdf.org/)

A: FPDF does not support SVG as far as I know. But if you can convert your SVG vectors to EPS you can use ImageEps().
http://www.fpdf.org/en/script/script84.php


text:
Q: Why we don't see adjustable "High" and "Low" Voltages for discrete logic gates For single, discrete logic gate chips, why is it that we don't have adjustable types? The closest we have are those that vary along with voltage supply.
I suppose it uses a voltage reference in the chip. So why not have it be set externally? Medium voltage (power supply level) logic could be useful in some applications.

A: You can have adjustable logic level thresholds if you really want to.  Older Logic Analysers use very fast comparitors that allow the threshold voltage to be set for the particular logic family and circuit that you are working with.
You can still do that today if you really need to.
But for general-purpose logic design, why would you want adjustable logic levels?  The TTL standard has served well for the past many decades and is still applicable today, even with new chip families that weren't even dreamed of 30 years ago.
The actual logic levels inside most chips does NOT rely upon a specific voltage reference.  Instead, the circuit is carefully designed to have the appropriate logic level thresholds for the particular manufacturing process that is used to build the chips.

A: Power efficiency and performance are main goals. Designing a logic family to operate with a well defined power supply range allows to optimize to meet those goals. In particular there is a distinct advantage in reducing (and thus limiting) power supply range, that is reduced power dissipation.
The now obsolete CD4000 CMOS family was indeed capable of handling a very large power supply range (the supply could range from ~5V to ~15V), but it was slow compared with more modern CMOS families.
Moreover, even in recent logic families there are special parts which allow operation with different power supply levels, if the need arise, such as those parts with open-drain outputs.
Keep in mind that logic chips are used essentially to perform "digital processing", and this doesn't require, in principle, high power levels (ideally one would want to use no power to process information). Whenever the need arise to drive devices that require a significant amount of power from logic level outputs you can always use standard interfacing techniques. For example, you can connect the logic output to a power MOSFET in order to switch on a relay. It would be wasteful (in many ways) to create an entire logic family capable of directly driving (relatively) high power loads when in reality this is only seldom necessary (in a complex digital board the number of "gates" that actually need to drive such loads directly is usually much smaller than the overall "gate count").


text:
Q: how to save userdata using shared preferences
hello i am new to flutter, can anyone say how to save user preferred choice using shared preferences whenever the user opens the app the user choice should load with the app now the choice are empty when the app restarts  ......................................................................................................................................................................................

A:  _save() async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'my_int_key';
    final value = 'my_int_value';
    prefs.setInt(key, value);
    print('saved $value');
  }

This code will save your data to share prefs so you can read when you open the app next time. you might need to change variables as per your requirement.
Further you can read the saved data by:
 _read() async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'my_int_key';
    final value = prefs.getInt(key) ?? 0;
    print('read: $value');
  }

A: You can use package Shared Preferences
This is how you can initialize preference object
SharedPreferences _prefs = await SharedPreferences.getInstance();

And set data like this
_prefs.setString('key', value);
_prefs.setInt('key', value);

Get data like this
_prefs.getString('key');
_prefs.getInt('key');


text:
Q: Algorithm for lightest unnested planar vertex-disjoint cycle-cover
Question:
given a finite set $\mathcal{P}$ of disjoint points in the Euclidean plane and the set $\mathcal{C}$ of all simple polygons whose corners are subsets of $\mathcal{P}$,

*

*what is the complexity of calculating the lightest subset $\mathcal{X}_{\min}\subseteq\mathcal{C}$ of unnested closed polygons that covers $\mathcal{P}$ when the weight of a polygon is defined to be equal to the length of its perimeter?

*Has that problem already been investigated, resp. what kind of heuristics can used to find good approximate solutions?

Without requiring that polygons must not be nested, the solution can be calculated with Tutte's 2-factor algorithm in polynomial time, so the essential question is as to whether demanding unnestedness tips the complexity-scales to $NP$.


text:
Q: In teamcity, I have a batch of mstests running after the .sln file gets built. When the tests fail, I don't get emailed. Why? My email notifier in teamcity works well when the compilation fails. I have it set to notify me of failures and also the first success after the failure.
But when one test fails, I don't get an email. The build is set to fail when at least one test doesn't pass. I have nice red dot next to the build number.
The weird thing is, sometimes I get a success email after the test has been fixed, but not always. Does anyone know of any logs I can use to figure out why I'm not getting my email?
Here is another weird thing: I set the notifications to send me an email when the build fails and when the build succeeds. When the tests fail, I still get no email.
I do get notified properly in the windows try program, however.

A: There is teamcity-notification.log, especially useful if you enable DEBUG logging:
http://confluence.jetbrains.net/display/TCD65/Reporting+Issues#ReportingIssues-LoggingEvents
Are the rules for email and tray notifiers the same? If yes, most probably that is a transportation failure, the error must be in the log.
BTW there is TeamCity 7.0 RC1 available:
http://confluence.jetbrains.net/display/TW/TeamCity+EAP

A: I'm dumb, they were in my spam folder all along.


text:
Q: Commands in WPF, Implementation question I know I've already asked questions on this, but something that's just confusing.
I'm doing a tutorial on WPF MVVM pattern, but it seems I cannot get it right, as in the tutorial, it doesn't go into detail on how to implement the ICommand interface.  (not sure how correct it really is?!!)
I have the following implementation of ICommand:
class ViewCommand : ICommand
    {
        #region ICommand Members

        private Predicate<object> _canExecute;
        private Predicate<bool> _execute(object param);

        public ViewCommand(Action<object> action)
        {

        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        #endregion
    }

and now this use:
class StartViewModel : ViewModel
    {
        public ViewCommand startViewCommand;

        public ViewCommand StartCommand
        {
            get
            {
                if (startViewCommand == null)
                    startViewCommand = new ViewCommand(
                        param => this.StartApplication()); // StartApplication returns void
                return startViewCommand;
            }
        }

I cannot figure out what my constructor of the ViewCommand class is supposed to do?  In the  StartViewModel class it's using a lambda expression in the constructor, so there needs to be some delegate, but I'm not sure what and how it's meant to work with Execute and CanExecute. I put a Action<object>, but it's probably wrong...
Lastly, can someone point me to a tutorial on how to implement ICommand that explains it?
Thanks!

A: Have a look at Josh Smith's tutorial pay attention to relay command, where he implements it.

A: Your _execute delegate shouldn't be a Predicate<bool>, it should be an Action<object>. Anyway, why don't you use an existing class like Josh Smith's RelayCommand, or MVVM toolkit DelegateCommand ?


text:
Q: Browser Webcam Access / WebRTC - how to determine max resolution and aspect ratio? Given the following, how do I determine the max possible resolution and default aspect ratio?
  openCamera: function () {
        (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia).call(
            navigator,
            { video: true },
            function (localMediaStream) {
                if (webCamWindow) {
                    var vendorURL = window.URL || window.webkitURL;

                    if (navigator.mozGetUserMedia) {
                        webCamWindow.mozSrcObject = localMediaStream;
                        webCamWindow.play();
                    } else {
                        webCamWindow.src = vendorURL.createObjectURL(localMediaStream);
                    }
                }
                stream = localMediaStream;

            },
            function () { alert('fail') }
        );
    },

A: You can use webrtc-camera-resultion to get the best (max) dimensions and the aspect ratio of the camera.
With this library, which scans through all possible support matrix and returns the best one it could find, you can get an outcome of the camera media devices in this format:
label: 4K(UHD)  // Camera name
width: 3840     // Maximum width
height: 2160    // Maximum height
ratio: 16:9     // Aspect ratio

You can then use it in navigator.mediaDevices.getUserMedia:
{
    audio: true,
    video: {
        mandatory: {
            minWidth: _minWidth,
            minHeight: _minHeight,
            maxWidth: _maxWidth,,
            maxHeight: _maxHeight
        }
    }
}, function (stream) {
       ...


text:
Q: Множественные редиректы htacces есть htaccess
Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule .* https://www.test.ru%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*[^/])$ https://www.test.ru/$1/ [L,R=301]

Открываю несуществующую страницу с ошибкой в адресе получаю несколько редиректов...
как сделать чтобы был 1 редирект?
сейчас
http://www.test.ru/documents/test
301 Moved Permanently
https://www.test.ru/documents/test
301 Moved Permanently
https://www.test.ru/documents/test/

нужно
http://www.test.ru/documents/test
301 Moved Permanently
https://www.test.ru/documents/test/

при этом правила вида
 RedirectMatch 301  ^/fitness/$  /services/fitness/

или
RewriteRule ^fitness/$ services/fitness/ [R=301,L]

отправляют на http а не https..
уже все голову сломал. спасибо


text:
Q: Highstock not displaying stock chart I have a weird problem - My highstock JS is not displaying the graph. It displays all other components. I am just trying out their example app but because of CORS issues I am rendering the JSON locally.
When I hard code the data and run the same code in JSFiddle, the data is displayed fine.
My code:
var chart1;
$.getJSON("http://localhost:5000/stock", function (data) {
    // Create the chart
    chart1 = Highcharts.stockChart('stockDiv', {
        xAxis: {
            min: Date.UTC(2013, 6, 17, 16, 00), //previous day  at 16.00
            max: new Date().getTime() //get actual time
        },
        title: {
            text: 'AAPL Stock Price'
        },
        series: [{
            name: 'AAPL',
            data: data,
            tooltip: {
                valueDecimals: 2
            },
            turboThreshold: data.length,
        }]
    });
});

My HTML

I am loading this js in a local python webserver and rendering the json data at the /stock url.
I checked in the debugger to see that the data is indeed present.
Totally flumoxxed by why this data is not getting displayed.
Appreciate any help !
This is what my output looks like


text:
Q: How to get which letter/word focused by the SQL LIKE operator I am trying to making a search engine something like this:
PHP
<?php
require_once 'config.php';
$text = $_GET['text'];
$select = $_GET['select'];
$sql = "SELECT * FROM papers WHERE {$select} LIKE '%{$text}%' ORDER BY ID DESC, {$select} ASC LIMIT 15";
$result = $conn->query($sql);
if (!$result) {
    trigger_error('Invalid query: ' . $conn->error);
}
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) { ?>

            <?php echo $row["ID"] ?>.

            <?php echo $row["Name"] ?>

            CH: <?php echo $row["ch"] ?>

            EN: <?php echo $row["en"] ?>

<?php
}
} else {
    echo '
Not Found!
';
}
?>

JS
$('#search,#select').change(search);
$('#search').keyup(search);
function search() {
    var text = $('#search').val();
    var select = $('#select').val();
    var tl = $('#search').val().length
        tl == 0 ? $('#searchre').hide('slow') : $('#searchre').show('slow');
    $.ajax({
        url: 'search.php',
        data: {
            'text': text,
            'select': select
        },
        dataType: 'html',
        success: function (html) {
            $('#searchre').html(html);
        }
    });
}

It's working fine.But I am trying to highlight the input word on the result. How can I do this? And one more problem is that when I type U it's showing first PUT when have a word with first letter U like umbrella. How can I solve this?

A: to highlight keyword you may use something like
$('#searchre').html(html.replace(text, '
' +keyword + '
'));

and add some CSS to the class `.keyword'
.keyword{
   color:yellow;
}

and to get the result with the order of keyword position you can use php sort function something like below
            <?php
        require_once 'config.php';
        $text = isset($_GET['text']) ? $_GET['text'] : '';
        $select = isset($_GET['select']) ? $_GET['select'] : '';

        $sql = "SELECT * FROM papers WHERE {$select} LIKE '%{$text}%' ORDER BY ID DESC, {$select} ASC LIMIT 15";
        $result = $conn->query($sql);

        if (!$result) trigger_error('Invalid query: ' . $conn->error);

        $resultArray = [];

        while ($row = $result->fetch_assoc()) {
            $resultArray[] = $row;
        }

        usort($resultArray, function ($a, $b) {
            //here I assume the column name to 'name' you may need to change it
            return (strpos($a['name'], $text) < strpos($b['name'], $text)) ? -1 : 1;
        });

        if ($resultArray) {
            foreach ($resultArray as $row) { ?>
                // output data of each row

                    <?php echo $row["ID"] ?>.

                    <?php echo $row["Name"] ?>

                    CH: <?php echo $row["ch"] ?>

                    EN: <?php echo $row["en"] ?>

                <?php
            }
        } else {
            echo '
Not Found!
';
        }
        ?>


text:
Q: asp.net forms authentication deny any user from accessing new web forms I'm having problem with an assignment on asp.net. I would like to ask, is there any way in which i can prevent any users (including authenticated users) from accessing newly created web forms unless I specified the access rights to the page in the web config?
i tried using
<deny users="*">

but it denies all users from accessing any pages, even those which i have already specified access rights, for example:
<location path="home.aspx">

A: Here is a good article to  look at, the example is on MS Support
  <configuration>
        <system.web>
            <authentication mode="Forms" >
                <forms loginUrl="login.aspx" name=".ASPNETAUTH" protection="None" path="/" timeout="20" >
                </forms>
            </authentication>
    <!-- This section denies access to all files in this
    application except for those that you have not explicitly
    specified by using another setting. -->
            <authorization>
                <deny users="?" />
            </authorization>
        </system.web>
    <!-- This section gives the unauthenticated
    user access to the ThePageThatUnauthenticatedUsersCanVisit.aspx
    page only. It is located in the same folder
    as this configuration file. -->
            <location path="ThePageThatUnauthenticatedUsersCanVisit.aspx">
            <system.web>
            <authorization>
                <allow users ="*" />
            </authorization>
            </system.web>
            </location>
    <!-- This section gives the unauthenticated
    user access to all of the files that are stored
    in the TheDirectoryThatUnauthenticatedUsersCanVisit folder.  -->
            <location path="TheDirectoryThatUnauthenticatedUsersCanVisit">
            <system.web>
            <authorization>
                <allow users ="*" />
            </authorization>
            </system.web>
            </location>
    </configuration>

A: This should help you:
<location path="FolderName/pagename.aspx">
        <system.web>
            <authorization>
                <deny users="*"/>
            </authorization>
        </system.web>
    </location>


text:
Q: how to convert a table to another in SQL (similar to pivot, but not exactly) I have a database table looks like this in the below, in SQL Server 2016:
   ProjectKey  -   Type    -    Percentage
   ----------------------------------------
   40               8            100%
   50               6            40%
   50               9            60%
   60               3            30%
   60               8            30%
   60               9            40%

(the max rows for the same ProjectKey is 3)
I want to write a query to be able to convert the above table to the following:
   ProjectKey   - Type1  -  Percentage1  - Type2  - Percentage2  - Type3  - Percentage3
   -------------------------------------------------------------------------------------
   40              8         100%           null     null           null    null
   50              6         40%            9        60%            null    null
   60              3         30%            8        30%            9       40%

If it can be achieved by writing a SQL query that would be great. Anyone can help? Thank you very much!

A: You can use row_number() and conditional aggregation:
select projectkey,
       max(case when seqnum = 1 then type end) as type_1,
       max(case when seqnum = 1 then percentage end) as percentage_1,
       max(case when seqnum = 2 then type end) as type_2,
       max(case when seqnum = 2 then percentage end) as percentage_2,
       max(case when seqnum = 3 then type end) as type_3,
       max(case when seqnum = 3 then percentage end) as percentage_3
from (select t.*,
             row_number() over (partition by projectkey order by type) as seqnum
      from t
     ) t
group by projectkey;


text:
Q: Application Request Routing doesn't route to same machine I have setup an ARR in my IIS server. My requirement is I have to route a request to this ARR server to one of my application which is hosted in local IIS(ARR server itself). Is it possible?
ie. Suppose in my ARR server has Application1. Then I have to do the following
Broswer -> ARR (iis server) -> Application1(which is itself in ARR server).
If possible how can implement such a setup?

A: Yes you can.
You need, at least, 2 sites to implement this. One will get the requests and route them to ARR via a Rewrite Rule, the other one will be the node behind ARR.
For example, considering your domain name is "example.com":
IIS
  - Site 1 (binding: http://example.com:80)
  - Site 2 (binding: http://127.0.0.1:22001)

Rewrite Rule
  - Match All
    - {HTTP_HOST} matches example.com
    - {SERVER_PORT} does not match 22001
 - Action: Route to Farm

This is a good starting point to do zero-downtime deployment. If you want to know more check this repo on GitHub: https://github.com/yosoyadri/IIS-ARR-Zero-Downtime

A: If you don't like it being on the same port, you can also have it go to a different IP instead.


text:
Q: How to find parent nodes path from flattened array? I have flattened hierarchy array as follows.
I'd like to get path to the specific node as array.
var arr = [

    {id:1, parent_id:null},
    {id:2, parent_id:1},
    {id:3, parent_id:null},
    {id:4, parent_id:2},
    {id:5, parent_id:4}

]

getPath(arr, 5) return [1,2,4]

Do you have any suggestion?

A: You could use a hash table for all id and their parents and iterate until no parent is available.

function getPath(nodes, id) {
    var parents = Object.create(null),
        path = [];

    nodes.forEach(function (n) {
        parents[n.id] = n.parent_id;
    });

    while (id = parents[id]) {
        path.unshift(id);
    }
    return path;
}

var array = [{ id: 1, parent_id: null }, { id: 2, parent_id: 1 }, { id: 3, parent_id: null }, { id: 4, parent_id: 2 }, { id: 5, parent_id: 4 }];

console.log(getPath(array, 5)); // [1, 2, 4]

A: You could define a recursive function that finds the item in the array with an id value matching the provided key parameter, and then checks if the current item has a parent_id truthy value.
If there is a parent_id:
The function will define results as an array if it wasn't passed into the function, and will then add the current item's parent_id to the front of the results array. Next, it will call itself with the following three parameters:

*

*The starting array (arr).

*The current item's parent_id as the key to look at next.

*The results array as the array to return when completely done.

If there is no parent_id:
The function will instead return the results array.

var arr = [
{id:1, parent_id:null},
{id:2, parent_id:1},
{id:3, parent_id:null},
{id:4, parent_id:2},
{id:5, parent_id:4}
];

function getPath(arr, key, results) {
    var nextObj = arr.filter(function(obj){
        return obj.id == key;
    })[0];
    if(nextObj && nextObj.parent_id) {
        results = typeof results !== 'object' ? [] : results;
        var nextKey = nextObj.parent_id;
        results.unshift(nextKey);
        return getPath(arr, nextKey, results);
    }
    return results;
}

console.log(getPath(arr, 5));

A: Here is my simple answer for what you want to achieve:

var arr = [

    {id:1, parent_id:null},
    {id:2, parent_id:1},
    {id:3, parent_id:null},
    {id:4, parent_id:2},
    {id:5, parent_id:4}
];
var res=[];
function getPath(arr, x){
    for(var i=0; i<arr.length; i++){
        if(arr[i].id== x){
            getPath(arr, arr[i].parent_id);
            if(arr[i].parent_id !== null){
           res.push(arr[i].parent_id);
            }

        }
    }

}
getPath(arr, 5);
console.log(res);

I have just used recursion and it works great.

A: Recursive function to get the desired output.

var arr = [

    {id:1, parent_id:null},
    {id:2, parent_id:1},
    {id:3, parent_id:null},
    {id:4, parent_id:2},
    {id:5, parent_id:4}

]

let resultArr = [];

function getPath(arr, num) {
 for(var i in arr) {
   if(arr[i].id === num) {
     //console.log(num);
      getPath(arr, arr[i].parent_id);
      resultArr.push(num);
   break;
    }
  }

  return resultArr.slice(0, (resultArr.length - 1));
}

var res = getPath(arr, 5);
console.log(res);


text:
Q: Printing special characters in php I have a php variable which contains data from an IO stream (say, a file I've just read). This string contains a number of special characters such as \n and \t and so forth. I need to be able to print all of these characters to screen so that I can examine the string visually. I'm presuming there's some way of escaping them, but for the life of me I can't figure out how.

A: addcslashes("test\n", "\0..\37\177..\377")

A: Well interesting question. I haven't been able to find anything in Google about escaping newline char.
I guess you could try using nl2br, which would convert your newlines to <br />, but that isn't quite useful, since you won't know when you have an actual break tag or newline char.
So, to get past this, you I recommend two options. If you only want to examine the string, use var_dump() or var_export()
The following code gives gives the output 'text \\n':
$var = 'text \n';

var_export($var);

Or, if you want to work further with it, you can use a piece of code like that, but let's be honest, this is quite messy...
$var = 'text \n';

$search = array('\n', '\r', '\r\n');
$replace = array('[n]', '[r]', '[r][n]');

echo str_replace($search, $replace, $var);

This would output text [n]

A: I think this is a very old question but none of the answers are very helpful. We use this function for examining strings like this, so hopefully it can help someone else out:
function convert_non_visual_ascii_chars_to_representation($string) {
    $non_vis_chars = [
        0 => 'NUL',
        1 => 'SOH',
        2 => 'STX',
        3 => 'ETX',
        4 => 'EOT',
        5 => 'ENQ',
        6 => 'ACK',
        7 => 'BEL',
        8 => 'BS',
        9 => 'TAB',
        10 => 'LF',
        11 => 'VT',
        12 => 'FF',
        13 => 'CR',
        14 => 'SO',
        15 => 'SI',
        16 => 'DLE',
        17 => 'DC1',
        18 => 'DC2',
        19 => 'DC3',
        20 => 'DC4',
        21 => 'NAK',
        22 => 'SYN',
        23 => 'ETB',
        24 => 'CAN',
        25 => 'EM',
        26 => 'SUB',
        27 => 'ESC',
        28 => 'FS',
        29 => 'GS',
        30 => 'RS',
        31 => 'US',
    ];

    // Convert the string
    $new_string = '';
    $length = strlen($string);
    for ($i = 0; $i < $length; $i++) {
        $char_code = ord($string[$i]);
        if (isset($non_vis_chars[$char_code])) {
            $new_string = $new_string . '[' . $non_vis_chars[$char_code] . '/' . $char_code . ']';
        } else {
            $new_string = $new_string . $string[$i];
        }
    }

    return $new_string;
}


text:
Q: Rational symmetric polynomial in the roots of an integer polynomial is rational I'm reading a book on trigonometric series, and the author uses the following result in a proof:
Let $f\in \mathbb{Z}[x]$ be a polynomial (with integers coefficients) of degree $n>0$, and let $S\in\mathbb{Q}[x_1,\dots,x_n]$ be a symmetric polynomial.
Let $\alpha_1,\dots,\alpha_n$ be the roots of $f$. Then $S(\alpha_1,\dots,\alpha_n)\in \mathbb{Q}$.
Is there an elementary proof of this fact? I've tried writing
$$\alpha_k=\sum_{i\neq k}a_i\alpha_k^i, \ 1\le k\le n$$
So
$$S(\alpha_1,\dots,\alpha_n)=S\left(\sum_{i\neq 1}a_i\alpha_1^i,\dots,\sum_{i\neq n}a_i\alpha_n^i\right)$$
which does not seem too useful. Also, by the fundamental theorem of symmetric polynomials, it would suffice to show the claim for elementary symmetric polynomials.


text:
Q: purchased an parallel build agent, but free is gone I've just purchased a parallel build agent, but after that the free agent with 1800 minutes is gone.
Is that correct?
It was not clear from the documentation

A: If you are buying Microsoft-hosted CI/CD. This is the expected behavior.

You can pay for additional capacity per parallel job. Paid parallel
  jobs remove the monthly time limit and allow you to run each job for
  up to 360 minutes (6 hours). Buy Microsoft-hosted parallel jobs.
Source Link

Please notice our official description. After you bought one paid parallel job, you will not get a new additional parallel job. It's just move the limitation for your prefer free job. That's why your free is "gone".


text:
Q: ¿Cuando se debe usar self en un Model en Rails? Dentro de un Model, cuando tengo en un método una operación de escritura de una variable, ¿porque es necesario agregar self para que funcione correctamente?
Por ejemplo, si tengo el siguiente código:
class Zombie < ActiveRecord::Base
  beffore_save :make_rotting

  def make_rotting
    if age > 20
        self.rotting = true
    end
  end

end

Por otro lado, si omito el self, no funiona:
class Zombie < ActiveRecord::Base
  beffore_save :make_rotting

  def make_rotting
    if age > 20
        rotting = true  #No funciona correctamente
    end
  end

end

Nota: la variable age la lee sin ningún problema en ambos casos.
¿Porque hay diferencia en el comportamiento de rotting con la presencia de self, mientras que en age no cambia?

A: Cuando haces rotting = true, lo que estás haciendo es declarar una variable local que funciona en el ámbito del método make_rotting y desaparecerá cuando la ejecución del método finalice.
Ahora, cuando llamas a self.rotting = true, estás pidiendo modificar el atributo rotting de tu instancia actual de zombie, que es como debería hacerse.
En general, en un método de instancia de un modelo, deberías usar self cuando modifiques atributos o cuando exista alguna ambiguedad entre llamar a una variable local y un atributo/método ya definido, por ejemplo:
  def make_rotting(age)
    if (age || self.age) > 20
        self.rotting = true
    end
  end

La primera llamada a age hace referencia a la variable local que viene como parámetro del método, mientras que la segunda (self.age) hace referencia al atributo, sin que necesariamente estemos modificando este atributo.
Respecto a por qué es lo mismo llamar a age o self.age si el caso es solo leer un atributo, es por el orden en el que ruby trata de resolver la llamada a age:

*

*Primero revisa en el ámbito de make_rotting si existe alguna variable age definida.

*En caso de no encontrarle, buscará en el ámbito de la instancia de zombie si ageestá definido.

En caso de usar self.age, estás explícitamente indicando que busque la definición en la instancia de zombie.


text:
Q: mongodb jest error ReferenceError: You are trying to `import` a file after the Jest environment has been torn down I am trying to test basic mongoDB operation using Jest.
  it('should insert a record into collection', async () => {
  const users = await db.collection('mariochar');
  const mockUser = { name: 'marioChar3'};
  await users.insertOne(mockUser);

  const insertedUser = await users.findOne({name: 'marioChar3'});
  expect(insertedUser).toEqual(mockUser);
});

If I use the default Jest suggested template as above, tests are passing correctly and records can also be seen in the database.
However, since I was learning from this youtube tutorial, I tried to test the Schema directly as shown in the video like this:
  it('should insert a mario into collection', async () => {
    const MarioCharSchema = new Schema({
      name: String,
      weight: Number
    })
    const MarioChar = await mongoose.model('mariochar', MarioCharSchema)
    const char = await new MarioChar({ name: "Mario" })
    char.save()
    console.log(char.isNew)
    expect(char.isNew).toBeTruthy()
  });

I get the error: ReferenceError: You are trying toimporta file after the Jest environment has been torn down.
After viewing few posts in stackoverflow, I added the fake timer and I am posting the complete code below. It did not get rid of the error.
My second question is that even though Jest shows the above error and also npm ERR! Test failed.  See above for more details., it shows the test as passed. Is there a way to report it as failed instead since it is easy to mistake it as passed when there will be a lot of tests?
const { MongoClient } = require('mongodb');

const mongoose = require('mongoose')
const Schema = mongoose.Schema
jest.useFakeTimers()
describe('insert', () => {
 let connection;
 let db;

 beforeAll(async () => {
   jest.useFakeTimers()
   connection = await MongoClient.connect("mongodb://localhost/testaroo", {
     useNewUrlParser: true,
     useUnifiedTopology: true
   });
   db = await connection.db();
 });

 afterAll(async () => {
   await connection.close();
 });

 it('should insert a mario into collection', async () => {
   const MarioCharSchema = new Schema({
     name: String,
     weight: Number
   })
   const MarioChar = await mongoose.model('mariochar', MarioCharSchema)
   const char = await new MarioChar({ name: "Mario" })
   char.save()
   expect(char.isNew).toBeTruthy()
 });
});

jest.config.js
module.exports = {
  "preset": '@shelf/jest-mongodb',
  "timers": "fake",
  "testEnvironment": "node"
};

package.json
...
  "dependencies": {
    "mongoose": "^5.9.18"
  },
  "devDependencies": {
    "@shelf/jest-mongodb": "^1.1.5",
    "jest": "^26.0.1"
  }
...

full error:
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at model.Document.$__getAllSubdocs (node_modules/mongoose/lib/document.js:2890:37)
      at _getPathsToValidate (node_modules/mongoose/lib/document.js:2159:23)
      at model.Document.$__validate (node_modules/mongoose/lib/document.js:2314:23)
      at node_modules/kareem/index.js:369:33
      at node_modules/@jest/fake-timers/build/legacyFakeTimers.js:496:18
 PASS  test/saving.test.js


text:
Q: Normal vector field associated to deformations of Riemannian submanifolds Let $(M,g)$ be a Riemannian manifold of dimension $n$ and $X$ be a immersed submanifold in $M$ of dimension $k$ i.e there is a immersion $F_{0}:X \longrightarrow M$.
A deformation of the submanifold $X$ is defined by a smooth family of immersions $F : I \times X \longrightarrow M$ i.e. $F_{t}: X \longrightarrow M$ is an immersion for all $t \in I$ and $F_{0}$ is the immersion of $X$ defined above, so we have a family of immersed submanifolds $F(t,(X))=X_{t}$.
Let $F_{*}( \frac{\partial}{\partial t})$ be the deformation vector field on $M$ associated to this deformation i.e. for any $p\in X$ take the curve $F(\cdot,p):I \longrightarrow M$ and  $F_{*}( \frac{\partial}{\partial t})$ at $p$ is the tangent vector to this curve at $t=0$.
Now this is my problem:  I have read that if the submanifold $X$ is compact and orientable then we can find a family of diffeomorphisms of $X$ depending on $t$ such that we can assume that the vector field of the deformation is normal to $X_{t}$ for all $t$. It is not clear how this reparametrization is done, if I consider the submanifold $X_{0}$ and the deformation vector field on it, i has 2 components corresponding to the splitting $TM \vert_{X}=T(X) \oplus N(X)$ how I get rid of the tangent component using diffeomorphisms of $X$ as it is stated above?
Thanks for your help

A: This is not exactly what you are asking, but in algebraic geometry we would say the following: the family of immersions $(F_t)$ is not uniquely defined, we can replace $F_t$ by $F_t\circ\varphi _t$, where $(\varphi _t)$ is a one-parameter family of diffeomeorphisms of $X$ -- this will give the same family of submanifolds. Thus $F_*(\frac{\partial}{\partial t} )$ is well defined only in the quotient $TM_{|X}/TX$, which is canonically isomorphic to the normal bundle.

A: If you're looking for an explicit example, see page 8 in Regularity Theory for Mean Curvature Flow by Ecker.  The preview on amazon includes the page.
http://www.amazon.com/Regularity-Theory-Mean-Curvature-Flow/dp/0817637818
The equation (2.1) referred to is the mean curvature flow equation,
$$\frac{\partial x}{\partial t} = \vec H(x)$$


text:
Q: Why use "strlen30()" instead of "strlen()"? I've read and wondered about the source code of sqlite
static int strlen30(const char *z){
  const char *z2 = z;
  while( *z2 ){ z2++; }
  return 0x3fffffff & (int)(z2 - z);
}

Why use strlen30() instead of strlen() (in string.h)??

A: The commit message that went in with this change states:

[793aaebd8024896c] part of check-in [c872d55493] Never use strlen(). Use our own internal sqlite3Strlen30() which is guaranteed to never overflow an integer. Additional explicit casts to avoid nuisance warning messages. (CVS 6007) (user: drh branch: trunk)

A: (this is my answer from Why reimplement strlen as loop+subtraction? , but it was closed)

I can't tell you the reason why they had to re-implement it, and why they chose int instead if size_t as the return type. But about the function:
/*
 ** Compute a string length that is limited to what can be stored in
 ** lower 30 bits of a 32-bit signed integer.
 */
static int strlen30(const char *z){
    const char *z2 = z;
    while( *z2 ){ z2++; }
    return 0x3fffffff & (int)(z2 - z);
}

Standard References
The standard says in (ISO/IEC 14882:2003(E)) 3.9.1 Fundamental Types, 4.:

Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer. 41)
...
41): This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer
  type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer
  type

That part of the standard does not define overflow-behaviour for signed integers. If we look at 5. Expressions, 5.:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined, unless such an expression is a constant expression
  (5.19), in which case the program is ill-formed. [Note: most existing implementations of C + + ignore integer
  overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point
  exceptions vary among machines, and is usually adjustable by a library function. ]

So far for overflow.
As for subtracting two pointers to array elements, 5.7 Additive operators, 6.:

When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. The type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as ptrdiff_t in the cstddef header (18.1). [...]

Looking at 18.1:

The contents are the same as the Standard C library header stddef.h

So let's look at the C standard (I only have a copy of C99, though), 7.17 Common Definitions :

*The types used for size_t and ptrdiff_t should not have an integer conversion rank
  greater than that of signed long int unless the implementation supports objects
  large enough to make this necessary.

No further guarantee made about ptrdiff_t. Then, Annex E (still in ISO/IEC 9899:TC2) gives the minimum magnitude for signed long int, but not a maximum:
#define LONG_MAX +2147483647

Now what are the maxima for int, the return type for sqlite - strlen30()? Let's skip the C++ quotation that forwards us to the C-standard once again, and we'll see in C99, Annex E, the minimum maximum for int:
#define INT_MAX +32767

Summary

*

*Usually, ptrdiff_t is not bigger than signed long, which is not smaller than 32bits.

*int is just defined to be at least 16bits long.

*Therefore, subtracting two pointers may give a result that does not fit into the  int of your platform.

*We remember from above that for signed types, a result that does not fit yields undefined behaviour.

*strlen30 does applies a bitwise or upon the pointer-subtract-result:

          | 32 bit                         |
ptr_diff  |10111101111110011110111110011111| // could be even larger
&         |00111111111111111111111111111111| // == 3FFFFFFF16
          ----------------------------------
=         |00111101111110011110111110011111| // truncated

That prevents undefiend behaviour by truncation of the pointer-subtraction result to a maximum value of 3FFFFFFF16 = 107374182310.
I am not sure about why they chose exactly that value, because on most machines, only the most significant bit tells the signedness. It could have made sense versus the standard to choose the minimum INT_MAX, but 1073741823 is indeed slightly strange without knowing more details (though it of course perfectly does what the comment above their function says: truncate to 30bits and prevent overflow).

A: The CVS commit message says:

Never use strlen(). Use our own internal sqlite3Strlen30() which is guaranteed to never overflow an integer. Additional explicit casts to avoid nuisance warning messages. (CVS 6007)

I couldn't find any further reference to this commit or explanation how they got an overflow in that place. I believe that it was an error reported by some static code analysis tool.


text:
Q: Create a media player for Hybrid App Hi I am creating a streaming app using Ionic Cordova and Angular Js and want to know how to create a good media (audio) player that can stream or be used offline. Is there any library that can I use? If not what is the best solution. Thank you...

A: I use the HTML 5 media tags for online streaming, references here: W3 schools for media tags