Home Blog Page 3925

Check-Driving HTML Templates


foo

Let’s examine the best way to do it in phases: we begin with the next take a look at that
tries to compile the template. In Go we use the usual html/template package deal.

Go

  func Test_wellFormedHtml(t *testing.T) {
    templ := template.Should(template.ParseFiles("index.tmpl"))
    _ = templ
  }

In Java, we use jmustache
as a result of it is quite simple to make use of; Freemarker or
Velocity are different frequent selections.

Java

  @Check
  void indexIsSoundHtml() {
      var template = Mustache.compiler().compile(
              new InputStreamReader(
                      getClass().getResourceAsStream("/index.tmpl")));
  }

If we run this take a look at, it’ll fail, as a result of the index.tmpl file does
not exist. So we create it, with the above damaged HTML. Now the take a look at ought to go.

Then we create a mannequin for the template to make use of. The appliance manages a todo-list, and
we will create a minimal mannequin for demonstration functions.

Go

  func Test_wellFormedHtml(t *testing.T) {
    templ := template.Should(template.ParseFiles("index.tmpl"))
    mannequin := todo.NewList()
    _ = templ
    _ = mannequin
  }

Java

  @Check
  void indexIsSoundHtml() {
      var template = Mustache.compiler().compile(
              new InputStreamReader(
                      getClass().getResourceAsStream("/index.tmpl")));
      var mannequin = new TodoList();
  }

Now we render the template, saving the ends in a bytes buffer (Go) or as a String (Java).

Go

  func Test_wellFormedHtml(t *testing.T) {
    templ := template.Should(template.ParseFiles("index.tmpl"))
    mannequin := todo.NewList()
    var buf bytes.Buffer
    err := templ.Execute(&buf, mannequin)
    if err != nil {
      panic(err)
    }
  }

Java

  @Check
  void indexIsSoundHtml() {
      var template = Mustache.compiler().compile(
              new InputStreamReader(
                      getClass().getResourceAsStream("/index.tmpl")));
      var mannequin = new TodoList();
  
      var html = template.execute(mannequin);
  }

At this level, we need to parse the HTML and we anticipate to see an
error, as a result of in our damaged HTML there’s a div factor that
is closed by a p factor. There’s an HTML parser within the Go
normal library, however it’s too lenient: if we run it on our damaged HTML, we do not get an
error. Fortunately, the Go normal library additionally has an XML parser that may be
configured to parse HTML (due to this Stack Overflow reply)

Go

  func Test_wellFormedHtml(t *testing.T) {
    templ := template.Should(template.ParseFiles("index.tmpl"))
    mannequin := todo.NewList()
    
    // render the template right into a buffer
    var buf bytes.Buffer
    err := templ.Execute(&buf, mannequin)
    if err != nil {
      panic(err)
    }
  
    // examine that the template might be parsed as (lenient) XML
    decoder := xml.NewDecoder(bytes.NewReader(buf.Bytes()))
    decoder.Strict = false
    decoder.AutoClose = xml.HTMLAutoClose
    decoder.Entity = xml.HTMLEntity
    for {
      _, err := decoder.Token()
      swap err {
      case io.EOF:
        return // We're performed, it is legitimate!
      case nil:
        // do nothing
      default:
        t.Fatalf("Error parsing html: %s", err)
      }
    }
  }

supply

This code configures the HTML parser to have the correct stage of leniency
for HTML, after which parses the HTML token by token. Certainly, we see the error
message we wished:

--- FAIL: Test_wellFormedHtml (0.00s)
    index_template_test.go:61: Error parsing html: XML syntax error on line 4: surprising finish factor 

In Java, a flexible library to make use of is jsoup:

Java

  @Check
  void indexIsSoundHtml() {
      var template = Mustache.compiler().compile(
              new InputStreamReader(
                      getClass().getResourceAsStream("/index.tmpl")));
      var mannequin = new TodoList();
  
      var html = template.execute(mannequin);
  
      var parser = Parser.htmlParser().setTrackErrors(10);
      Jsoup.parse(html, "", parser);
      assertThat(parser.getErrors()).isEmpty();
  }

supply

And we see it fail:

java.lang.AssertionError: 
Anticipating empty however was:<[<1:13>: Unexpected EndTag token [] when in state [InBody],

Success! Now if we copy over the contents of the TodoMVC
template
to our index.tmpl file, the take a look at passes.

The take a look at, nevertheless, is simply too verbose: we extract two helper capabilities, in
order to make the intention of the take a look at clearer, and we get

Go

  func Test_wellFormedHtml(t *testing.T) {
    mannequin := todo.NewList()
  
    buf := renderTemplate("index.tmpl", mannequin)
  
    assertWellFormedHtml(t, buf)
  }

supply

Java

  @Check
  void indexIsSoundHtml() {
      var mannequin = new TodoList();
  
      var html = renderTemplate("/index.tmpl", mannequin);
  
      assertSoundHtml(html);
  }

supply

Stage 2: testing HTML construction

What else ought to we take a look at?

We all know that the seems to be of a web page can solely be examined, finally, by a
human how it’s rendered in a browser. Nonetheless, there may be usually
logic in templates, and we would like to have the ability to take a look at that logic.

One is perhaps tempted to check the rendered HTML with string equality,
however this method fails in apply, as a result of templates comprise a number of
particulars that make string equality assertions impractical. The assertions
grow to be very verbose, and when studying the assertion, it turns into tough
to grasp what it’s that we’re attempting to show.

What we’d like
is a way to say that some components of the rendered HTML
correspond to what we anticipate, and to ignore all the small print we do not
care about.
A method to do that is by operating queries with the CSS selector language:
it’s a highly effective language that enables us to pick out the
components that we care about from the entire HTML doc. As soon as we now have
chosen these components, we (1) depend that the variety of factor returned
is what we anticipate, and (2) that they comprise the textual content or different content material
that we anticipate.

The UI that we’re speculated to generate seems to be like this:

Check-Driving HTML Templates

There are a number of particulars which can be rendered dynamically:

  1. The variety of gadgets and their textual content content material change, clearly
  2. The model of the todo-item adjustments when it is accomplished (e.g., the
    second)
  3. The “2 gadgets left” textual content will change with the variety of non-completed
    gadgets
  4. One of many three buttons “All”, “Energetic”, “Accomplished” shall be
    highlighted, relying on the present url; for example if we determine that the
    url that reveals solely the “Energetic” gadgets is /energetic, then when the present url
    is /energetic, the “Energetic” button ought to be surrounded by a skinny pink
    rectangle
  5. The “Clear accomplished” button ought to solely be seen if any merchandise is
    accomplished

Every of this considerations might be examined with the assistance of CSS selectors.

It is a snippet from the TodoMVC template (barely simplified). I
haven’t but added the dynamic bits, so what we see right here is static
content material, offered for instance:

index.tmpl

  

supply

This uncommon earth steel exhibits us the way forward for our planet’s assets


Demand for neodymium-based magnets may outstrip provide within the coming decade. The longer-term prospects for the steel’s provide aren’t as dire, however a cautious have a look at neodymium’s potential future reveals lots of the challenges we’ll doubtless face throughout the availability chain for supplies within the coming century and past. 

Peak panic

Earlier than we get into our materials future, it’s vital to level out simply how onerous it’s all the time been to make correct predictions of this type. Simply have a look at our steady theorizing concerning the provide of fossil fuels. 

One model of the story, instructed continuously in economics lessons, goes one thing like this: Provided that there’s a restricted provide of oil, sooner or later the world will run out of it. Earlier than then, we should always attain some most quantity of oil extraction, after which manufacturing will begin an irreversible decline. That top level is named “peak oil.”

This concept has been traced again so far as the early 1900s, however some of the well-known analyses got here from M. King Hubbert, who was a geologist at Shell. In a 1956 paper, Hubbert thought-about the full quantity of oil (and different fossil fuels, like coal and pure gasoline) that geologists had recognized on the planet. From the estimated provide and the quantity the world had burned by means of, he predicted that oil manufacturing within the US would peak and start declining between 1965 and 1970. The height of world oil manufacturing, he predicted, would come a bit later, in 2000. 

For some time, it regarded as if Hubbert was proper. US oil manufacturing elevated till 1970, when it reached a dramatic peak. It then declined for many years afterward, till about 2010. However then advances in drilling and fracking strategies unlocked hard-to-reach reserves. Oil manufacturing skyrocketed within the US by means of the 2010s, and as of 2023, the nation was producing extra oil than ever earlier than

Peak-oil panic has lengthy outlived Hubbert, however each time economists and geologists have predicted that we’ve reached, or are about to succeed in, the height of oil manufacturing, they’ve missed the mark (to date).

5 methods to climb the profession ladder and turn out to be a profitable CIO

0


whimiscal staircase light purple background

Eoneren/Getty Photos

Companies proceed to make investments closely in digital transformation, and the CIO is among the large beneficiaries. Corporations want the specialised recommendation of a educated digital chief to make sure the group will get probably the most bang for its buck.

Additionally: 6 methods to make the most of the intelligent concepts behind modern startups

Analysis carried out by the consulting firm Deloitte exhibits that the CIO function is being elevated to the next standing. With almost two-thirds (63%) of expertise leaders saying they now report on to the CEO, the guide refers to this era as a “golden” period for the CIO.

1. Present up as a enterprise chief

Anjali Shaikh, managing director and CIO Program Expertise director at Deloitte Consulting LLP, stated there’s by no means been a extra thrilling time to be a CIO.

“Whereas the function of expertise inside enterprise has elevated over the past a number of years, the affect and worth CIOs can deliver are extra obvious at present than ever,” she stated.

“Know-how is on the middle of the group, and maintaining with this tempo of change is just one other requirement of the function.”

Shaikh stated the elevated recognition of the function of expertise presents a chance many CIOs have been ready for.

Additionally: 5 causes to work with the competitors, in response to enterprise leaders

Nonetheless, she informed ZDNET that delivering worth is a “powerful job” and suggested would-be digital leaders to hone their expertise in a number of key areas.

“Whereas there may be extra strain for CIOs to step outdoors of the consolation of a purely technical function, it is additional proof of the worth of expertise, and they’re being requested to develop on that technical basis and present up as a enterprise chief,” she stated.

“They’re going to have to deal with enhancing their communication expertise, constructing sturdy collaborative relationships all through the group, and completely understanding the trade and the group’s wants and targets to deliver worth to all enterprise areas.” 

2. Construct sturdy relationships with individuals

Omer Grossman, international CIO at expertise specialist CyberArk, says good digital leaders can change the enterprise however should focus on the best areas.

Grossman informed ZDNET that too many tech managers nonetheless deal with IT fairly than what he refers to because the underlying info a part of the function.

“In case you totally make the most of your CIO place to embody accountability for info, then you definitely’re on the best path. In any other case, you will not survive,” he stated.

Additionally: 3 methods to create the best knowledge tradition in your corporation

Whereas taking advantage of expertise continues to be an enormous a part of the CIO function, Grossman stated your long-term success as a digital chief will rely in your individuals expertise.

“It’s essential to construct relationships. You wish to be a trusted adviser and associate,” he stated.

“You must handle your relationships and construct them. You should purchase a fantastic answer, however you will not be capable to implement it efficiently in case your customers reject it. Success is all about individuals.”

3. Increase your variety and sustainability smarts

Bev White, CEO at international recruiter Nash Squared, stated the digital management function is in an nearly fixed state of flux — and that is a very good factor.

“The CIO function has modified in all probability greater than some other senior place over the past 10 to fifteen years,” she stated, suggesting the velocity of the expertise evolution has continued to extend since cloud computing was first adopted.

“CIOs have needed to take care of a panorama of speedy and fixed change — and this fee of change has sped up not too long ago with the arrival of synthetic intelligence.”

Like different consultants, White informed ZDNET there’s by no means been a extra thrilling time to be a CIO.

Additionally: 5 methods to be a fantastic chief at work

Nonetheless, she additionally stated profitable CIOs might want to rise to the challenges of contemporary digital management. Her agency’s analysis suggests CIOs may enhance their deal with two key areas: variety and sustainability.

“In each areas, many of the CIOs in our Pulse survey — 72% and 68% respectively — report that progress has stayed the identical as six months in the past,” she stated.

“However in two key strategic areas, standing nonetheless means falling again. There’s room for CIOs to extend the momentum right here and set the requirements to encourage others within the enterprise.”

4. Work hand in glove together with your friends

Sasha Jory, CIO at insurer Hastings Direct, stated the definition of a profitable digital chief has modified, and up-and-coming IT professionals should focus on collaboration.

“Previously, you had senior individuals who knew the expertise technique, waved their arms, and had armies of individuals to implement issues and switch their concepts into actuality,” she stated.

“Now, you have to be a CIO who understands the enterprise, your clients, and the expertise, and you could encompass your self with people who find themselves motivated, agile, and in a position to ship.”

Additionally: 5 methods to get the very best from individuals, in response to enterprise leaders

Jory informed ZDNET this modification in the kind of one that turns into a reputable digital chief means there are new alternatives for IT professionals to have interaction with their enterprise friends on a degree enjoying subject.

“In case you’re on an island, you will not achieve success. The route for a profitable CIO is to be collaborative and engaged with everyone in order that they will ship the best outcomes,” she stated.

“I do not imagine you may lead expertise transformation with out working hand in glove with your corporation.”

5. Keep abreast of rising applied sciences

JP Avelange, CIO for expertise specialist Expereo, stated the increasing compass of the CIO place means career-oriented IT professionals have to be ready to step into new areas.

“The roles and obligations of the CIO have modified, pushed by the tempo of innovation and the rising function of enterprise models influencing or immediately driving tech spending,” he stated.

“On this new context, CIOs have to be seen as enterprise companions and don’t have any alternative however to develop their scope and adapt to new calls for to remain related.”

Avelange informed ZDNET that CIOs are nonetheless anticipated to care for the basics, which embrace main digital transformation and managing IT budgets successfully.

Additionally: 5 methods to get to the highest of the IT career, in response to this CIO

Nonetheless, they need to additionally ship worth and justify investments in new applied sciences and initiatives.

“The main target of CIOs has expanded to maintaining with rising applied sciences reminiscent of synthetic intelligence, machine studying, and integrating these applied sciences into current methods and processes,” he stated.

“Many CIOs are spearheading cybersecurity measures, dealing with the exponential progress of knowledge, and leveraging it for enterprise insights and decision-making.”



Ideas for Failing Oil-Stuffed Transformers


When giant tools begins to fail, you’ll have to act shortly to restore or change it to keep away from severe issues. For instance, in case your transformer is failing, you don’t need to let it go till it really fails. At that time, it’d catch fireplace and even explode, which can create a harmful scenario for anybody close by, to not point out the property harm it could possibly do to your constructing.

In case you have an oil-filled transformer that you simply imagine could be failing, the next factors make up your finest plan of action.

1. Exchange Your Transformer If Potential

Alternative is the primary and most necessary step to take when a transformer is failing. For those who depart it alone, it can solely worsen, and you may’t afford to danger having a transformer fireplace or explosion in your property. In case you have the funds or can get them, don’t assume twice about changing your transformer instantly.

Once you purchase a brand new transformer, make sure that to carry out all required upkeep to maintain it in good situation. Common upkeep is the important thing to making transformers final a few years, quite than having points compound till the entire system fails. The upkeep concerned might be time-consuming, however contemplate it a part of your regular enterprise bills required for operation. Don’t skip this step as a result of it’s the one solution to forestall your new unit from experiencing the identical destiny because the one it changed.

2. Assess The Potential Penalties of Failure

Transformers might be harmful after they fail. Hopefully, if it’s oil-filled, your failing transformer is situated outdoors so if it does fail, there will likely be much less danger to people. In case you have an oil-filled transformer situated inside a constructing, the danger of harm within the case of a failure is so much increased.

In both case, it’s finest to interchange your transformer, however not less than if it’s outdoors you possibly can hold folks away from it till you’re capable of change it.

3. Think about Switching to a Dry-Kind Transformer

Oil-filled transformers are typically extra inexpensive than dry-types, and they’re fairly helpful. In some instances, they’re completely obligatory as a consequence of voltage necessities. Nonetheless, typically you might have a alternative between an oil-filled and dry-type, and it’s essential to evaluate the professionals and cons of every.

For instance, in the event you don’t have actually excessive voltage wants, a dry-type transformer could be excellent. Dry-types might be extra handy since they are often safely put in indoors when the precise infrastructure is in place and sure requirements are met.

Dry-type transformers also can final for much longer than oil-filled models after they’ve been made with experience. For instance, hand-wound dry-types get rid of errors that may trigger untimely failure. They have an inclination to price greater than oil-filled transformers, however they’ll final for much longer, particularly when made by a good chief within the business.

4. Purchase a New Transformer on Credit score

For those who don’t have the capital up entrance to purchase a brand new transformer, contemplate getting one on credit score. Since a failing transformer is a security hazard, it’s not definitely worth the danger to postpone alternative. Do no matter it’s a must to do to get that new transformer. For those who delight your self on your enterprise not being in debt, let go of the idea that debt is unhealthy. It will possibly serve you properly, particularly when it’s essential to hold your constructing protected.

A Failing Transformer Wants Speedy Consideration

It doesn’t matter what, when you’ve got an oil-filled transformer that’s failing, you could do one thing about it instantly. For those who’re undecided about changing it but, have it checked out by an expert. Get a professional’s opinion on the scenario and take their solutions severely. In the event that they let you know it may be repaired, it’s possible you’ll need to get a second opinion earlier than committing to that restore, but it surely could be one thing that may be mounted. If not, and the technician tells you it must be changed, don’t wait to get a brand new transformer.

The implications of ignoring a failing oil-filled transformer are too nice to disregard. For those who discover something improper along with your unit, like unusually loud noises and vibrations, buzzing that wasn’t occurring earlier than, or it’s getting too sizzling, have it checked and serviced by an expert. Most of all, change it if it’s at or close to the top of its life. Don’t anticipate it to fail as a result of it can price you way more to repair the harm after a transformer failure.

Article Submitted By Group Author

The (Change) Case of the Lacking Binding — Erica Sadun


Right here’s a cool little problem introduced up this morning by a good friend. Take into account the next code:

change foo {
  case .a: return "a"
  case .b(let str) the place str.hasPrefix("c"), .c: return "c"
  case .b: return "b"
}

It gained’t compile.

If you bind an emblem for one sample, you could bind that image for each sample in a case. This prevents you, for instance, from binding str in a single sample after which making an attempt to make use of str within the shared case physique. For instance, take into account this case. What would you anticipate to occur when foo is .c?

func switchTheFallthroughOrder(foo: Foo) -> String {
    change foo {
    case .a: return "a"
    case .b(let str) the place str.hasPrefix("c"), .c:
        // Utilizing `str` right here is dangerous!
        print(str)
        return "c"
    case .b: return "b"
    }
}

Regardless of my first knee-jerk refactoring, shifting out the .c case to make use of fallthrough doesn’t work. Once more, it’s because str will not be sure for .c and may be used within the successive case physique:

Nevertheless, as Greg Titus identified, for those who change the order to make use of the binding case first with fallthrough, Swift is aware of at compile time that the binding gained’t stick with it past that scope. This resolves the error, since str is simply used within the the place clause to slender the sample matching:

Additional, when utilizing bindings in case assessments, a waterfall method the place the sure objects are used earlier than fallthrough can prolong by way of a number of steps with the blessing of the compiler:

case .widest(let first, let second) the place first.satisfiesACondition():
    // can use `first`, `second` right here
    fallthrough
case .medium(let second) the place second.satisfiesAnotherCondition():
    // can use `second` right here even when it was sure 
    // by way of `widest` above by way of fallthrough
    fallthrough
case .narrowest: return someValue

My due to Greg Titus for figuring this all out!