text:
Q: Does OCaml have C-like round() and trunc() functions? OCaml's standard library includes several floating-point functions equivalent to C ones, such as mod_float for C's fmod(), the exponentiation operator ** for C's pow(), and other functions such as ceil, log, etc.
But does it also include equivalents for round() and trunc()? There is truncate/int_of_float, but their type is float -> int and not float -> float.

A: It contains the modf function, that is a swiss-knife function, with which you can define the truncatef and roundf functions:
# let truncatef x = snd (modf x);;
val truncatef : float -> float = <fun>
# truncatef 3.14;;
 - : float = 3.

The round function also can be expressed with modf
# let roundf x = snd (modf (x +. copysign 0.5 x));;
val roundf : float -> float = <fun>
# roundf 3.14;;
- : float = 3.
# roundf 3.54;;
- : float = 4.
# roundf (~-.3.54);;
- : float = -4.

However it can be expressed more succinctly (and efficiently) with floor
# let roundf x = floor (x +. 0.5)

But both rounding functions are a little bit buggy, as comment in core's implementation states:
(* Outside of the range [round_nearest_lb..round_nearest_ub], all representable doubles
   are integers in the mathematical sense, and [round_nearest] should be identity.

   However, for odd numbers with the absolute value between 2**52 and 2**53, the formula
   [round_nearest x = floor (x + 0.5)] does not hold:

   # let naive_round_nearest x = floor (x +. 0.5);;
   # let x = 2. ** 52. +. 1.;;
   val x : float = 4503599627370497.
   # naive_round_nearest x;;
   - :     float = 4503599627370498.
*)
let round_nearest_lb = -.(2. ** 52.)
let round_nearest_ub =    2. ** 52.

So a little bit more correct way to implement the rounding would be (from Core library):
let round_nearest t =
  if t >= round_nearest_lb && t <= round_nearest_ub then
    floor (t +. 0.5)
  else
    t

But even this round_nearest is not flawless, for example:
# round_nearest 0.49999999999999994;;
- : float = 1.

This 0.49999999999999994 is an immediate predecessor of 0.5. Pascal's blog contains suggestions on how to solve this issue. The following should work in OCaml:
let round_nearest t =
  if t >= round_nearest_lb && t <= round_nearest_ub then
    floor (t +. 0.49999999999999994)
  else
    t

# round_nearest 0.49999999999999994;;
- : float = 0.
# round_nearest (~-.0.49999999999999994);;
- : float = 0.
# round_nearest (~-.1.49999999999999994);;
- : float = -1.
# round_nearest 0.5;;
- : float = 1.
# round_nearest ~-.0.5;;
- : float = -1.
#

And this is only one rounding policy, round to nearest (the intuitive one). There are other policies, that have their own caveats.

A: The Core library has a Float module with many such functions.

A: For truncate, someone gave you an answer already:
let truncatef x = snd (modf x);

For round, I suggest:
BatFloat.round_to_int or BatFloat.round
Check this for details.

A: If you want a function truncate having the type float -> float, you can do this but it is very ugly :
let mytruncate x = float_of_int (truncate x)


text:
Q: Asymptotic relations at infinity I am attempting to show that

If $f(x) - g(x) \ll 1,\, x \to \infty$, then $e^{f(x)}\sim e^{g(x)}, \,x\to \infty$

From the first line, I am able to show that
$$ \lim_{x\to \infty} \frac{f(x) - g(x)}{1} = 0$$
from which it is clear that
$$ \lim_{x\to \infty}\left[f(x) - g(x)\right] = 0$$
However, I am a little stuck at this point. Where do exponentials come in?
Any help/hints much appreciated.

A: As you've shown
$$f(x)-g(x)\to 0,\quad\text{as}\, x\to\infty$$
So
$$\frac{e^{f(x)}}{e^{g(x)}}=e^{f(x)-g(x)}\to 1$$
All you need is
$$e^v\to 1,\quad\text{as}\,v\to 0$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: UIWebView says "URL can't be shown" when trying to open an URL for another app, but it works in Safari I'm trying to fix an old iOS app where UIWebView won't open an URL to another app. The app says "URL cannot be shown", which might indicate the URL is wrong, but I am able to open it directly in Safari.
I received the responsibility for fixing an app for my company and I do not have much experience with Objective C, so I hope you can help me.
The app have previously worked, but suddenly stopped working in 2016. This is probably because of an update that happened at this time, which changed somURL can't be showne functionality.
The app opens a UIWebView and through this accesses a webservice from where the user can input some information, etc. This webservice then calls another app to print a label, but instead just displays a pop-up with URL can't be shown.
When I write this URL directly into Safari, it opens the app and works with no problems. This made me think the problem might be somewhere in UIWebView, but I cannot locate exactly where this might be.
I do not know what cope snippet or information might be worth including, but if you ask what you need I can provide it.

A: Presumably if it used to work, there are calls to UIApplication's canOpenUrl: and openUrl: (likely you'll find these in your web view delegate's webView:shouldStartLoadWithRequest:navigationType:)
iOS9 made changes to how UIApplication canOpenUrl: works - mostly it doesn't any more.
If you're OK with supporting only iOS10 - look at using
openURL:options:completionHandler: instead
https://developer.apple.com/documentation/uikit/uiapplication/1648685-openurl?language=objc

A: So, in addition to my comment, try to do this :
Go to your controller where you deal with your webview, and add this piece of code to that method:
- (BOOL)webView:(UIWebView *)wv shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    // Determine if we want the system to handle it.
    NSURL *url = request.URL;
    if (![url.scheme isEqual:@"http"] && ![url.scheme isEqual:@"https"]) {
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url];
            return NO;
        }
    }
    return YES;
}

Then, also, handle some error that can be ignored :
- (void)webView:(UIWebView *)wv didFailLoadWithError:(NSError *)error {
    // Ignore NSURLErrorDomain error -999.
    if (error.code == NSURLErrorCancelled) return;

    // Ignore "Fame Load Interrupted" errors. Seen after app store links.
    if (error.code == 102 && [error.domain isEqual:@"WebKitErrorDomain"]) return;

    // Normal error handling…
}

Let me know if it's working for you.
You can read the full post of that solution here.
Happy coding !


text:
Q: Exception raised during rendering: Unable to locate mode 0 After update BuildTools to version 25.0.0.
compileSdkVersion 25
buildToolsVersion "25"

I have problem with android layout preview. Now it show error:

Exception raised during rendering: Unable to locate mode 0

I tried to Clean & Rebuild project, but it doesn't work.
Before update everything was good.
I know that I can go back to previous versions of BuildTools, but I want to know why it doesn't work on version 25.0.0?

Seems like it is a problem with RecyclerView
java.lang.IllegalStateException: Unable to locate mode 0
at android.view.DisplayInfo.findMode(DisplayInfo.java:458)
at android.view.DisplayInfo.getMode(DisplayInfo.java:445)
at android.view.Display.getRefreshRate(Display.java:648)
at android.support.v7.widget.RecyclerView.onAttachedToWindow(RecyclerView.java:2392)
at android.view.View.dispatchAttachedToWindow(View.java:15392)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2953)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2960)
at android.view.AttachInfo_Accessor.setAttachInfo(AttachInfo_Accessor.java:42)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:333)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:429)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:389)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:548)
at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:533)
at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:966)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:533)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$53(RenderTask.java:659)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

A:
The Android Support Library provides backward-compatible utility
  functions. Apps can use these utility functions to provide an
  appropriate user experience across a wide range of Android system
  versions.

It's a bug issue and should be fixed in the future Release of the support-design library.

*

*Rendering Problems - Exception raised during rendering: Unable to locate mode 0
You should downgrade your version for Temporary Solutions .
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:design:v7:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'

A: It's an Annoying bug of version 25..
A Temporary solution is to downgrade your project,
 compile 'com.android.support:appcompat-v7:24.2.1'
 compile 'com.android.support:design:24.2.1'
 compile 'com.android.support:recyclerview-v7:24.2.1'

A: To see preview I use this trick.....
add  app:layoutManager="0" for the recyclerView in a layout XML
But it will throw InflateException at run time. So REMOVE this property from XML layout file before running the app!

A: As temp solution you can create child class of recycler view and override only onAttachedToWindow as below. Then use this class in your XML layouts
@Override
protected void onAttachedToWindow() {
    if (!isInEditMode()) {
        super.onAttachedToWindow();
    }
}

Update: starting from support library 25.0.1, fix already included in the library and issue not exist anymore

A: Another temporary solution is to replace <android.support.v7.widget.RecyclerView with <RecyclerView so you can see the rendered View. When compiling, change it back to <android.support.v7.widget.RecyclerView

A: This issue has been resolved, update the support library to
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:design:25.0.1'


text:
Q: react warning: Functions are not valid as a React child with forwardRef I would like to click a remote button to print a pdf ( with the react-pdf library component: PDFDownloadLink ) , but sometimes it usually fails, and in the console I get this warning:
Functions are not valid as a React child
I have read other answers in this forum but I just can't see the bug in my code.
Thank you very much for your help!
 const pdfRef = useRef(null);

      // sessionStorage on window load event
      window.onload = () => {
        let reloading = sessionStorage.getItem("reloading");
        if (reloading) {
          sessionStorage.removeItem("reloading");
          pdfRef.current.click();
        }
      }
      // Save a session on handlePDF call
      const handlePDF = () => {
        sessionStorage.setItem("reloading", "true");
        window.location.reload(false);
      };

const PdfLinkButton = forwardRef((props, ref) => (
    <button style={{ display: "none" }} class="btn btn-primary  mb-5">
      <PDFDownloadLink
        style={{ backgroundColor: "#0A71F1", color: "white" }}
        document={<TestPDF />}
        fileName="Informe CMF.pdf"
      >

        <div ref={ref}>
          {({ loading }) => (loading ? "Loading" : "Download PDF ")}
        </div>
      </PDFDownloadLink>
    </button>
  ));

return (

<>
<button onClick={ handlePDF } class="btn btn-primary  mb-5">
                Download PDF
              </button>

<PdfLinkButton ref={ pdfRef } />

</>

)


text:
Q: how to show full image with overlay in jquery? Could you please tell me how to show big or large image on button click with overlay. I am making a image slider in which user click on image and it shows the full image with overlay. I tried like this
https://plnkr.co/edit/7AqAHSSPwZyj7cipXMrq?p=preview
.overlay {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    width:100%;
    height:100%;
    background-color:black;
    z-index:9999;
    color:white;
}

$(function() {

  var counter = 0;
  $('#next').click(function() {
    if (counter <  $('.imageBlock').length-1) {
      counter++;
      $('.imageBlock').hide();
      $('.imageBlock').eq(counter).show();
    }
  })
  $('#pre').click(function() {
    if (counter > 0) {
      counter--;
      $('.imageBlock').hide();
      $('.imageBlock').eq(counter).show();
    }
  })

  $('.imageBlock').click(function(){
    $('body html').addClass('overlay')
  })

})

A: Here's an example where clicking the image - we take the src, and add it to a hidden div (.overlay img) and then show the div.
clicking the overlay hides it again.
Hope this is helpful

   $('.thumb').on('click', function(){
  $('.overlay img').attr('src', $(this).attr('src'));
  $('.overlay').show();
});

$('.overlay').on('click', function(){
  $('.overlay').hide();
});

.thumb {
  width: 250px;
}
.overlay {
  display: none;
  position: absolute;
  top:0px;
  background: #000;
  width: 100%;
  height: 100vh;
  white-space: nowrap;

    text-align: center;
}

.overlay img {
  width: 100%;
  border:5px solid #000;
  vertical-align: middle;
}

.helper {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

Here's a fiddle: https://jsfiddle.net/BradChelly/kbode1cx/

A: If you want to use a library, you can use prettyPhoto that does everything you need.
If you don't want to use a library, you can do that in your code (last jQuery event of your JS file) :
$('.imageBlock').click(function(){
    $('body').toggleClass('overlay');
    $('.imageBlock').eq(counter).find('.large img').toggle();
})

A: For starters $('body html').addClass('overlay') doesn't work, because that selects an html element inside a body element.. which doesn't exist.
I think you meant to target either class (to make it cross-browser):
$('body,html')
You could toggle the class:
$('body,html').toggleClass('overlay')
Then adjust your css. Probably something like this:
.overlay .imageBlock .small img {
display: none;
}
.overlay .imageBlock .large img {
display: block;
}

BTW, if you only need the .small and .large wrappers with img just for the overlay feature, then you're making things harder than needed...


text:
Q: Update the css of one loaded DOM asynchronously once another user clicks a button in his loaded DOM in a django webapp I am developing a django webapp where I have one html that gets loaded for two different users (User1 and User2) with some slight changes in it. I want my user1 to disable/enable some of the fields (like  field) of that html in runtime so that user2 can only update the ones that user1 has made enabled.
Currently, user1 can disable/enable html elements via javascript but that changes are only being reflected in his html. User2 cannot see the changes in his html.
What will be the perfect way to achieve this functionality? I am not very familiar with everything in Django. Pardon my obvious knowledge gaps.
Thanks.


text:
Q: Which word should I use to describe the noise made by an electronic device? The noises made by electronic devices (lamps, electronic chargers, etc.) sound to me like a high-pitched,barely audible "zzzzzz".
In my mind is the word "buzz". Beyond that I don't really know.
What word should I use to describe them?

A: This is usually referred to as humming.

A: Depends on the device.  A variety of onomatopoetic words would be serviceable--buzz or hmmmmm, for instance; but your particular device might not make that noise.  In the case of sound effects, remember that you're free to improvise on the spelling.  :-)


text:
Q: Docusign, how getting an access token without logging(authorization) in browser I make requests to the docusign API on the backend where I want to get an access token, is it possible to get an acess token without authorization in the browser?

A: Yes, you can do that by using the Json Web Token Model of OAuth.
You would still need to obtain consent one per-user/app, but once obtained, you can get tokens for this using an API call without having the need for a web browser or user to login.
https://developers.docusign.com/platform/auth/jwt/jwt-get-token/ should help you step-by-step getting JWT tokens.


text:
Q: How to connect HTML WebSocket to C++ Socket I have an app where I am trying to connect to a C++ server which opens up a socket.
// Client side
var ws = new WebSocket('ws://<<IP:PORT>>');

In the server side, it is opening up a socket using
int sockfd = socket(domain, type, protocol)

(ref: https://www.geeksforgeeks.org/socket-programming-cc/)
Not aware of the c++ server implementation.
I was told that the server would start a WebSocket server to which my HTML app can connect.
But, the connection is not happening. I feel that the WebSocket on the client side is not same as socket on the server side and hence the connection is not establishing.
Please, someone, suggest what is wrong and how to make it right.
P.S. Please don't mind if it is a dumb question.

A: Since the server guys are not ready to change their implementation of the plain socket, as a workaround I created a C++ client which connects to the server using the plain socket. Then I am creating a WebSocket Server using NodeJs which executes the C++ client as a child process to get the data. So, my WebSocket client is now able to get the data from the main server through the NodeJs WebSocket interface server.
Cons:

*

*A dependency of the C++ client.

*Latency (since network speed is not a factor now, it works).


text:
Q: Refresh Activity without Closing it I'm using this code in activity opened from notification, but whenever refresh button is pressed activity stops instead of restarting
  refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(getIntent());
                overridePendingTransition(0, 0);
                finish();
            }
        });

A: Main Activity to profile activity
Intent i = new Intent(this,  Profile.class);
startActivityForResult(i, 1);

Profile activity to set result
Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here")
setResult(RESULT_OK, intent);
finish();

A: try this code:
frist activity finish(); then restart using startActivity(getIntent());
finish();
overridePendingTransition( 0, 0);
startActivity(getIntent());
overridePendingTransition( 0, 0);


text:
Q: JavaScript - How to hide errors on Form Validation How do I hide the error(s) messages and the red border when a user corrects their errors on my form? At the moment it will keep showing the error(s) until the page is refreshed or submitted.
function checkForm() {
            var valid = true;

            if (!retext.test(document.myform.textfield.value)) {
                document.myform.textfield.style.border = "3.5px solid red";
                document.getElementById("text").innerHTML = "Invalid text.";
                document.getElementById("text").style.display = "block";
                valid = false;
            }

            if (!re.test(document.myform.email.value)) {
                document.myform.email.style.border = "3.5px solid red";
                document.getElementById("emailwarn").innerHTML = "Invalid email.";
                document.getElementById("emailwarn").style.display = "block";
                valid = false;
            }

            if (!retel.test(document.myform.tel.value)) {
                document.myform.tel.style.border = "3.5px solid red";
                document.getElementById("telwarn").innerHTML = "Invalid telephone number.";
                document.getElementById("telwarn").style.display = "block";
                valid = false;
            }

            return valid;
        }

I really have no idea on how to do this.

A: Assuming the checkForm function is called each time the form is amended you can include else clauses to reset the style and visible state of the warnings
function checkForm() {
    var valid = true;

    if (!retext.test(document.myform.textfield.value)) {
        document.myform.textfield.border = "3.5px solid red";
        document.getElementById("text").innerHTML = "Invalid text.";
        document.getElementById("text").style.display = "block";
        valid = false;
    } else {
        document.myform.textfield.border = 0;
        document.getElementById("text").style.display = "none";
    }

    if (!re.test(document.myform.email.value)) {
        document.myform.email.style.border = "3.5px solid red";
        document.getElementById("emailwarn").innerHTML = "Invalid email.";
        document.getElementById("emailwarn").style.display = "block";
        valid = false;
    } else {
        document.myform.email.border = 0;
        document.getElementById("emailwarn").style.display = "none";
    }

    if (!retel.test(document.myform.tel.value)) {
        document.myform.tel.style.border = "3.5px solid red";
        document.getElementById("telwarn").innerHTML = "Invalid telephone number.";
        document.getElementById("telwarn").style.display = "block";
        valid = false;
    } else {
        document.myform.tel.border = 0;
        document.getElementById("telwarn").style.display = "none";
    }

    return valid;
}

A: Just add code which clears up the error messages at the beginning of your checkForm() function.
In your current code if error messages had been set once they have no chance to be changed on the correct input.
For example,
function clearErrors() {
  document.getElementById("text").style.display      = "none";
  document.getElementById("emailwarn").style.display = "none";
  document.getElementById("telwarn").style.display   = "none";
}

function checkForm() {
  var valid = true;

  clearErrors();

  ...

A: Well first it would be better to seperate javascript and CSS styles, by applying classes:
input.error {
  border: 3.5px solid red;
}

To apply the style:
document.myform.textfield.classList.add("error");

To remove the style:
document.myform.textfield.classList.remove("error");

To hide the warn element use:
document.getElementById("telwarn").style.display = "none";

Beware that classList does not work with ie < 10


text:
Q: JavaScript Test RegExp function non-latin characters bug Well, I have noticed this during using console.
> var a = new RegExp('\\b' + "абв" + '\\b', "gim");
> a.test("абв");
false

> var b = new RegExp("абв", "gim");
> b.test("абв");
true

And then with latin characters:
> var c = new RegExp('\\b' + "abc" + '\\b', "gim");
> c.test("abc");
true

I would glad to read your suggestions about fixing this.

A: \b refers only to word boundaries in an ASCII perception. You can create DIY boundaries. Also if you already know the pattern will remain constant, use a regular expression literal as follows:
/(^| )абв( |$)/.test("абв"); // true


text:
Q: WPF split HTML string for every TextBlock Does anyone know how to split the HTML string for every TextBlock? I split them, but something is wrong. The lines count are not the same in every page. How do I solve this issue?
Here's the code:
XAML:

<Window x:Class="Ebook.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:WPFMitsuControls;assembly=WPFMitsuControls"
Title="eBook" Height="600" Width="800"
Loaded="MainWindow_OnLoaded" Background="Silver">
    <DockPanel>
        <Viewbox Margin="10">
            <Grid>
                <controls:Book x:Name="myBook" Width="600" Height="400" Margin="20">
                    <controls:Book.ItemTemplate>
                        <DataTemplate>
                            <Border BorderThickness="4" BorderBrush="Gray" Background="White">
                                <ContentControl Content="{Binding .}" />
                            </Border>
                        </DataTemplate>
                    </controls:Book.ItemTemplate>
                </controls:Book>
                <Button Content="<" HorizontalAlignment="Left" VerticalAlignment="Center" VerticalContentAlignment="Center" Background="Transparent" Height="50" Click="AutoPreviousClick" />
                <Button Content=">" HorizontalAlignment="Right" VerticalAlignment="Center" VerticalContentAlignment="Center" Background="Transparent" Height="50" Click="AutoNextClick" />
            </Grid>
        </Viewbox>
    </DockPanel>
</Window>

CODE:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Globalization;
using System.IO;

namespace Ebook
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        string html_str =  "
The standard Lorem Ipsum passage, used since the 1500s
"
                        + "
'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
"
                        + "
Section 1.10.32 of 'de Finibus Bonorum et Malorum', written by Cicero in 45 BC
"
                        + "
'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?'
"
                        + "
1914 translation by H. Rackham
"
                        + "
'But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?'
"
                        + "
Section 1.10.33 of 'de Finibus Bonorum et Malorum', written by Cicero in 45 BC
"
                        + "
'At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.'
"
                        + "
1914 translation by H. Rackham
"
                        + "
'On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains.'
";

        private void AutoNextClick(object sender, RoutedEventArgs e)
        {
            myBook.AnimateToNextPage(false, 700);
            myBook.Focus();
        }

        private void AutoPreviousClick(object sender, RoutedEventArgs e)
        {
            myBook.AnimateToPreviousPage(false, 700);
            myBook.Focus();
        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            List<string> lines = WrapText(html_str, 200, "Arial", 12);
            int rows = 20;
            int pages = lines.Count / rows;
            string _Page = "";
            int j = 0, k = 0;
            TextBlock tb1;
            for (int i = 0; i < pages; i++)
            {
                tb1 = new TextBlock();
                tb1.TextWrapping = TextWrapping.Wrap;
                tb1.Margin = new Thickness(5);
                tb1.TextAlignment = TextAlignment.Justify;
                _Page = "";
                for (j = 0; j < rows; j++)
                {
                    _Page += lines[rows * i + j] + "\n";
                    k++;
                }
                //myBook.Items.Add(new TextBlock { Text = _Page, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(5), TextAlignment = TextAlignment.Justify });
                tb1.Inlines.AddRange(MarkupProcessor.HTMLToWPF(_Page));
                myBook.Items.Add(tb1);
            }
        }

        static List<string> WrapText(string text, double pixels, string fontFamily, float emSize)
        {
            string[] originalLines = text.Split(new string[] { " " },
                StringSplitOptions.None);

            List<string> wrappedLines = new List<string>();

            StringBuilder actualLine = new StringBuilder();
            double actualWidth = 0;

            foreach (var item in originalLines)
            {
                FormattedText formatted = new FormattedText(item,
                    CultureInfo.CurrentCulture,
                    System.Windows.FlowDirection.LeftToRight,
                    new Typeface(fontFamily), emSize, Brushes.Black);

                actualLine.Append(item + " ");
                actualWidth += formatted.Width;

                if (actualWidth > pixels)
                {
                    wrappedLines.Add(actualLine.ToString());
                    actualLine = new StringBuilder();
                    actualWidth = 0;
                }
            }

            if (actualLine.Length > 0)
                wrappedLines.Add(actualLine.ToString());

            return wrappedLines;
        }
    }
}

http://i.stack.imgur.com/AEpsm.png
Here's the download link to the project: http://www.megafileupload.com/en/file/532650/WPF-Ebook-zip.html

A: You can`t control number of lines because of this:
tb1.TextWrapping = TextWrapping.Wrap;

Line count will depend on length of string. Long strings will be wrapped.


text:
Q: lxml.html set error "TypeError: Argument must be bytes or unicode, got 'NoneType' " I am trying to put a 'defer' attribute into script tags using lxml.html but I get the error
TypeError: Argument must be bytes or unicode, got 'NoneType'
or
TypeError: set() takes exactly 2 positional arguments (1 given)
if I use
script.set('defer')

According to http://lxml.de/lxmlhtml.html
.set(key, value=None):
Sets an HTML attribute. If no value is given, or if the value is None, it creates a boolean attribute like
<form novalidate></form>

or
<div custom-attribute></div>.

my code is
import lxml.html

htmldoc = lxml.html.parse( file )
headElement = htmldoc.find("head")
listOfScripts = headElement.xpath("script")

if len(listOfScripts) > 0:
    for script in listOfScripts:
        script.set('defer', value=None)

A: The documentation you linked is for the latest version of lxml, the feature about .set() that you're talking about was added in version 3.7, your version however, is < 3.7
View the changelog here:

3.7.0 (2016-12-10)
Features added
• GH#201: Calling the method .set('attrname') without value argument (or None) on HTML elements
  creates an attribute without value that serialises like  attrname>. Patch by Daniel Holth.


text:
Q: htaccess URL rewrite - requested URL not found on server Having an issue where the URL rewrite is running but the server will not display the contents.  My .htaccess file is
    RewriteEngine On
    RewriteBase /
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /project\.php [NC]
    RewriteCond %{QUERY_STRING} id=([0-9]+) [NC]
    RewriteRule . project-%1.html? [R=301]

Thanks for your help!
EDIT: Sorry, here is some more info!
I want to rewrite
    www.siteurl.co.uk/project.php?id=82

to
    www.siteurl.co.uk/project-82.html

The code in the .htaccess rewrites the URL perfectly but the page does not display.  I get a
    404 The requested URL /project-82.html was not found on this server.

I hope that helps!

A: You only have one half of the solution, creating the pretty urls.  What is missing is the other half, sending the pretty urls to an application for processing as below
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /project\.php [NC]
RewriteCond %{QUERY_STRING} id=([0-9]+) [NC]
RewriteRule . project-%1.html? [R=301]

#you need this rule to process your www.siteurl.co.uk/project-82.html request
RewriteRule ^project-([0-9]+)\.html$ project.php?id=$1 [L,NC,QSA]

A: try putting     RewriteRule ^project-%1.html? [R=301] instead of the .

A: Don't know what the "[A-Z]{3-9}\ " is for? maybe I'm missing something?
But maybe something like this instead:
RewriteCond %{THE_REQUEST} ^project\.php [NC]
RewriteCond %{QUERY_STRING} id=([0-9]+) [NC]
RewriteRule . project-%1.html? [R=301]

or
RewriteCond %{QUERY_STRING} id=([0-9]+) [NC]
RewriteRule ^/project\.php project-%1.html? [R=301]

Note that this is just off the top of my head, and I didn't test it.
EDIT: Just adjusted the second example which had an extra slash in it, and tested it out on my webserver (note that I'm using IIS/URLRewrite, but should be same):
RewriteBase /
RewriteCond %{QUERY_STRING} id=([0-9]+) [NC]
RewriteRule ^project\.php project-%1.html? [R=301]

I entered http://localhost/project.php?id=123 and it went to http://localhost/project-123.html
But I think I missed something... you say the url rewrite is working, and the url is changing but you're getting a 404? In that case then your rewrite sounds fine - and something else is not permitting your html files to be accessed (or they don't exist)?


text:
Q: Zapier lazy load input fields choices I'm building a Zapier app for a platform that have dynamic fields. I have an API that returns the list of fields for one of my resource (for example) :
[
  { name: "First Name", key: "first_name", type: "String" },
  { name: "Civility", key: "civility", type: "Multiple" }
]

I build my action's inputFields based on this API :
create: {
  [...],
  operation: {
    inputFields: [
      fetchFields()
    ],
    [...]
  },
}

The API returns type that are list of values (i.e : Civility), but to get these values I have to make another API call.
For now, what I have done is in my fetchFields function, each time I encounter a type: "Multiple", I do another API call to get the possible values and set it as choices in my input field. However this is expensive and the page on Zapier takes too much time to display the fields.
I tried to use the z.dehydrate feature provided by Zapier but it doesn't work for input choices.
I can't use a dynamic dropdown here as I can't pass the key of the field possible value I'm looking for. For example, to get back the possible values for Civility, I'll need to pass the civility key to my API.
What are the options in this case?

A: David here, from the Zapier Platform team.
Thanks for writing in! I think what you're doing is possible, but I'm also not 100% that I understand what you're asking.
You can have multiple API calls in the function (which it sounds like you are). In the end, the function should return an array of Field objects (as descried here).
The key thing you might not be aware of is that subsequent steps have access to a partially-filled bundle.inputData, so you can have a first function that gets field options and allows a user to select something, then a second function that runs and pulls in fields based on that choice.
Otherwise, I think a function that does 2 api calls (one to fetch the field types and one to turn them into Zapier field objects) is the best bet.
If this didn't answer your question, feel free to email partners@zapier.com or join the slack org (linked at the bottom of the readme) and we'll try to solve it there.


text:
Q: How to derive the gradient of RNN and what is the definition of Loss function in this graph? I am reading Deep Learning and I am not able to follow the gradient derivation of RNN.
The graph of RNN is like this:

The updating equations are as follow:

The loss function is:

And the derivation of gradient is like this:

I am confused by equation 10.18.
What is the function of loss here and why this holds:

A: I hope this will help:
.
.
.
.
https://drive.google.com/file/d/0B7TWwiIrcJstZjdWTG84VVF1eDA/view

A: Inspired by this :Softmax and the negative log-likelihood
I write my own Softmax function as:
$$\widehat{y}_i^{(t)}=\frac{e^{o_i^{(t)}}}{\sum_j{e^{o_j^{(t)}}}}$$
and it's derivative with respect to $o_i^{(t)}$:
$$\frac{\partial{\widehat{y}_i^{(t)}}} {\partial{o_i^{(t)}}} =\widehat{y}_i^{(t)}(1-\widehat{y}_i^{(t)})$$
My negative log-likelihood is written as:
$$L^{(t)}=-\sum_{i}\log{\widehat{y}_i^{(t)}}$$
and it's derivative with respect to $\widehat{y}_i^{(t)}$:
$$\frac{\partial{L^{(t)}}}{\partial{\widehat{y}_i^{(t)}}}=-\frac{1}{\widehat{y}_i^{(t)}}$$
Combining the equations above, I get:
$$\frac{\partial{L^{(t)}}}{\partial{o_i^{(t)}}}=\frac{\partial{L^{(t)}}}{\partial{\widehat{y}_i^{(t)}}} \frac{\partial{\widehat{y}_i^{(t)}}}{\partial{o_i^{(t)}}}=-\frac{1}{\widehat{y}_i^{(t)}}[\widehat{y}_i^{(t)}(1-\widehat{y}_i^{(t)})]=\widehat{y}_i^{(t)}-1 $$
I have two questions now:

*

*Is my derivation above correct?

*If it is, why is there a small difference between my result and the book Deep Learning :
$$\textbf{1}_{i=y^{(t)}}$$
what dose $\textbf{1}_{i=y^{(t)}}$ mean and can it be just a simple 1 ?


text:
Q: Setting Google Places 'Types' on Dropdown Input I'm using the Google Places API to list pick up and drop off locations for a transportation service. We have two fields that, when typed in, autosuggest results.
When a a dropdown, #transport-type, is set to the first option, value = 1, then the input field, #pick-up-location, should have 'types' airport added to its results.
JS:
function transport_types() {
 if ($('#transport-type').val() == 1) {
     var input = document.getElementById('pick-up-location');
     var options = { types: ['airport'] };
     autocomplete = new google.maps.places.Autocomplete(input, options);
 }
 if ($('#transport-type').val() == 2) {
     var input = document.getElementById('drop-off-location');
     var options = { types: ['airport'] };
     autocomplete = new google.maps.places.Autocomplete(input, options);
 }
 google.maps.event.addDomListener(window, 'load', initialize);
}

Dropdown HTML:
<select id="transport-type" name="TransNeeded" required="true" tabindex="101" onChange="transport_types();">
  <option value='0' selected='selected'>Where do you want to go?</option>
  <option value='1' onfocus="enableGoogle('', true);"  id="pick-up-type">Pick-Up Location is an Airport</option>
  <option value='2' onfocus="enableGoogle('', true);" id="drop-off-type">Drop-Off Location is an Airport</option>
  <option value='3' onfocus="enableGoogle('', true);" id="point-point-type">Point to Point or Charter</option>
</select>

Input HTML:
<input type="text" id="pick-up-location" name="PUFullAddress" tabindex="104" value="Pick-Up Location" required="true"
  onblur="if(this.value.length==0) { $('#pick-up-location').attr('value', ''); }"
  onkeypress="delay(50);"
  onfocus="enableGoogle('PU', false);"
/>

<input id="drop-off-location" name="DOFullAddress" type="text" tabindex="105" value="Drop-Off Location" required="true"
 onblur="if(this.value.length==0) { $('#drop-off-location').attr('value', ' '); }"
 onkeypress="delay(50);"
 onfocus="enableGoogle('DO', false);"
/>

I'm not the most seasoned jQuery programmer, so it could even be an issue of syntax. I appreciate any insight you guys can provide.
Thanks for your time!

A: You're missing a close bracket and have an extra ;
Try the following
 if ($('#transport-type').attr('value', '1')) {


text:
Q: Spring boot pageable is not working with where clause I tried to use spring pageable with Where clause and containing but it returns nothing.
My Spring version : 2.1.4.RELEASE
Database : MySql
public interface ItemRepository extends JpaRepository<ItemEntity, String> {

    List<ItemEntity> findByCodeIgnoreCaseContainingAndNameIgnoreCaseContaining(String code, String name);

}

A: Either Change the JPA Query as below :
Page<User> findByCodeIgnoreCaseContainingAndNameIgnoreCaseContaining(String code, String name,Pageable pageable);

Or use PagingAndSortingRepository instead of JpaRepository.
Please refer https://www.baeldung.com/spring-data-jpa-pagination-sorting


text:
Q: Is it possible to use google signin with react-native-web? We're building a react-native application which has a Google Signin powered by react-native-google-signin. This library uses native functionality which is not available in the web, so my expectation is that it is not possible to port our react-native application to the web.
Is it possible to use google signin with react-native-web?

A: react-native-web tries to provide DOM based implementation of react-native elements and it is mostly UI focused.
It is possible to use google signin but you will have to use web integration of google signin https://developers.google.com/identity/sign-in/web/sign-in
You can also try https://github.com/anthonyjgrove/react-google-login or any other equivalent web libraries


text:
Q: performance of distributed tensorflow is bad and found high cpu-sys (long time wait on futex) all,I am trying to run an NN model with distributed-tensorflow(2ps+2 worker,each on a standalone machine),the performance is bad,and worker's cpu-usage is between 50%~800% (machine has 40 cores)

*

*I am pretty sure the input queue is ok(without starving problem).

*I also have tried the "tcmlloc/lib/libtcmalloc.so",but no help

*with profile tools "strace",I found something strange:long time wait on futex,sometimes even 2+ seconds wait on futex
enter image description here

*I also get the timeline infoenter image description here

*however,When I run the same programe with no-distributed mode,I can achieved almost 4-5 times of performance compared with the distributed mode,and the cpu-usage almost 2000%~3000%

*my code is:`    with tf.device(tf.train.replica_device_setter(worker_device = "/job:worker/task:%d" % FLAGS.task_id,cluster=cluster)):
global_step = tf.contrib.framework.get_or_create_global_step()

indexes, values, labels = inputs.inputs()
logits = models.inference([indexes, values])
with tf.name_scope('loss'):
    diff = labels * tf.log(logits)
    with tf.name_scope('total'):
        loss = -tf.reduce_mean(diff)

tf.summary.scalar('loss', loss)
with tf.name_scope('train'):
    print("learning_rate = %f" % FLAGS.learning_rate)
    #sync_opt = tf.train.SyncReplicasOptimizer(tf.train.AdamOptimizer(FLAGS.learning_rate),
                                              #replicas_to_aggregate=1, total_num_replicas=1, use_locking=False)
    sync_opt = tf.train.AdamOptimizer(FLAGS.learning_rate)
    train_step = sync_opt.minimize(loss, global_step=global_step)

with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
    with tf.name_scope('accuracy'):
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', accuracy)
hooks = [tf.train.StopAtStepHook(num_steps=6000)]
sess_config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)

with tf.train.MonitoredTrainingSession(master=server.target,
                                        is_chief=if_chief,
                                        checkpoint_dir=None,
                                        hooks=hooks,config=sess_config,stop_grace_period_secs=20) as session:

    step = 0
    while not session.should_stop():
        start_time = time.time()

        run_metadata = tf.RunMetadata()
        _, global_step_value,loss_value = session.run([train_step, global_step,loss],options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE),
        run_metadata=run_metadata)
        if step > 0 and step % 1 == 0:

            duration = time.time() - start_time
            format_str = ("After %d traning steps (%d global steps), "
                          "loss on training batch is %3f. "
                          "(cost %d s)")
            print(format_str % (step, global_step_value, loss_value,duration))
        step += 1

        if step >0 and step % 10 == 0 :
             tl = timeline.Timeline(run_metadata.step_stats)
             ctf = tl.generate_chrome_trace_format()
             with open('timeline.json', 'w') as f:
                 f.write(ctf)`

Any suggestions? Thanks!


text:
Q: How to best design address locations in any SQL Database? Overview
I'm working on some Emergency Services reporting and mapping application for California (kind of weird, considering the fires there, right now...). We need to map demographic and emergency data for an internal govt unit.
What we have are all the streets, cities and neighborhoods in California. Each neighborhood also has it's relevant shapefile (lat long that defines it's boundaries). This was given to us by the US Census board (all public domain stuff) website.
Problem
I'm not sure how to best design the DB tables. We haven't been told what type of DB we need to use .. so we're open to suggestions if that helps. We have experience with MS SQL 2005 and 2008 (and the spatial stuff in '08).
We can have the following legit data.

*

*Street, City, State

*City, State

*Neighborhood, State

*State

The reason why State is a legit location is because we're told this might be sold to other states, so we need to plan for that now.
So, originally, i thought of this...

*

*LocationId INTEGER PK Identity

*Street NVARCHAR(100)

*Neighbourhood NVARCHAR(100)

*City NVARCHAR(100)

*State NVARCHAR(100)

*Latitude VARCHAR(15)

*Longitude VARCHAR(15)

*Shapefile

None of those are nullable, btw. But after a short while, i thought that it was a waste to have so many 'California' text or 'San Diego' text in the fields. So i changed the table to be more normalised by making the Neighborhood, City and State fields a foreign key to their own new table (eg. lookups) .. and those two fields are now NULLABLE.
So .. that all works fine. except when i try and do some Sql statements on them. Because of the NULLABLE FK's, it's a nightmare to make all these outer join queries :(
What about having the main table, the sub-lookup tables (eg. Neighbourhoods, Cities and States) linked via ID's and then place all this in a view? Remember, NeighborhoodID and CitiyID would be NULLABLE.. ???
I just want to see people's thoughts on this and the reasons they made their suggestions, please. I'm really worried and confused but are eager to learn.
Please help!

edit 1: I need to stick to an RDBMS Database.
edit 2: I'm thinking about going a single table (de-normalized) with constraints to keep the sum of the fields unqiue OR multi-tables with nullable FK's on the main table (eg. Locations (main table), Neighborhoods, Cities, States ... normalized db schema).
edit 3: Added City to the sample, second list.
edit 4: Added view question.

A: Taking the example:

*

*Street, City, State

*City, State

*Neighborhood, State

*State

Firstly go back to basic principles, all of the above are distinct geospatial entities, so your address is composed of a name, and one or many geospatial specifiers. This tells us that we really should be storing them in a single table. The key here is to think of the data more abstractly,
So your address table needs a 1-many relationship to another table, called address_entities which is as follows:

*

*int ID

*varchar() name

*varchar() type

*int parentID

*geography position.

*int parentID

This means that you will obviously need a table to link the address to the address entity table above. Now, each geospatial entity is inherently hierarchical, and whilst it makes the SQL harder, and personally I try to avoid self referencing tables there are times when it is a good solution and this is one of them.
The benefits are huge, even though it makes the code harder, it is worth it in the long run.
Also, even when it isn't an immediate requirement, think globally, not all addresses in the world have a street, or state, for example,in france a valid address could be
- la Maison des Fou
- 24500 Eymet

So, bear that in mind when designing schemas.

A: As @Oddthinking noted in a comment, your problems started at:

So I changed the table to be more normalised by making the Neighborhood, City and State fields a foreign key to their own new table (eg. lookups) .. and those two fields are now NULLABLE.
So .. that all works fine. except when I try and do some SQL statements on them. Because of the NULLABLE FK's, it's a nightmare to make all these outer join queries.

This reminds me of the "Doctor, doctor, it hurts when I hit myself like this" joke.
Why exactly did you make the foreign key fields nullable?  They were mandatory before, so you should keep them as mandatory, precisely to avoid the nightmares of outer join queries.
Your explanation (question) is somewhat confusing in that you list three fields (Neighborhood, City and State) and then say "those two fields are now nullable".  Which two are?  And why?  And what is in the lookup table?  Or is there more than one lookup table?  There might be an argument for some sort of NeighbourhoodID number which is a foreign key to a Neighbourhood table, which defines the City and State as well as Neighbourhood name.  You might then decide that there is a closed list of cities and the cities have an ID number too, and that number determines the state too.  You are probably as well off using a two-letter state code as creating a (probably 4-byte) state ID number.   However, do not forget that a check criterion that ensures that the state code is one of the 50 or so valid state codes is harder to write than a foreign key that references a table of states.  Since neither states nor cities changes very often, I'd probably use the table of states with a foreign key - but the key column would be the state code.
That means you might have a table of Neighbourhoods with columns NeighbourhoodID, Name, CityID; a table of Cities with columns CityID, Name, State; and a table of States with columns State and Name.  You can add other columns as you see fit.  And your primary table would contain a NeighbourhoodID column that is a foreign key to Neighbourhoods table.

A: This is a nice place to start. A whole #$(#$-load of database schemas to check out:
http://www.databaseanswers.org/data_models/

A: This a problem I've had to deal with and RDBMS systems aren't the best at storing hierarchical data. You might want to look at using an object database since these have to deal with nested objects and are optimized for the problem.
If you need to use an RDBMS, you may have to stick with a de-normalized schema though. Having separate tables to maintain your cities, streets etc may be handy for tracking changes though. If a city or street needs to be renamed, you can update the master record in the respective table and schedule a job to update a text copy of the string in your 'main' table. This will prevent you from having to run updates on 10's 100's of thousands of rows during prime time, but still lets you store the most up-to-data data in the db. Of course, this makes the data duplication situation even worse, but it's the price to pay for performance.

A: Is this an OLTP system and reporting system or only a reporting system?  If it's only a reporting system, you can denormalize the data in a data warehouse fashion (with snowflake dimensions or not for the hierachies of geographic jurisdictions) and you'll find the reporting to be easier.
I would start from the results and work back, because it sounds to me like you are getting fed the data and you are trying to bring it into a database to support the reporting and mapping.  In this case, the database schema being a traditional normalized system is not important because redundancy in the data is not something that will cause maintenance problems for users, etc.
If this seems appropriate, you want to look into the Kimball books.


text:
Q: How to simplify expression $\int_a^b f(x)dx+\int_{f(a)}^{f(b)} f^{-1}(x)dx \ ?$ How to simplify expression
$$\int_a^b f(x)dx+\int_{f(a)}^{f(b)} f^{-1}(x)dx \ ?$$
The answer is $bf(b)-af(a)$  but I am wondering how to get the answer.

A: Here is a graphical proof (that doesn't assume that $f$ is differentiable).
Take a look at the following figure :

The colored areas constitute a rectangle whose area can be computed in two ways :
A) globally, as :
$$\text{length} \times \text{width} \  = \ b.f(b)\tag{1}$$
B) by considering it as partitionned into three non-overlapping regions :

*

*the blue region (deep blue + light blue) : its area is the area under the curve of $f$ starting at $a$ and ending at $b$ i.e., $\int_a^b f(x)dx$,

*the red region (deep red + light red) : its area is the area under the curve of $f^{-1}$, starting at $f(a)$ and ending at $f(b)$, i.e., $\int_{f(a)}^{f(b)} f^{-1}(x)dx$ (one has to turn his head 90° !),

*the green region, a rectangle whose area is : $a.f(a)$.
Equating the two ways of computing this area, we get :
$$b.f(b)=\int_a^b f(x)dx+\int_{f(a)}^{f(b)} f^{-1}(x)dx + a.f(a)$$
which is equivalent to the relationship you want to establish.
Addendum : It has taken me some time to spot an analogous question. Here it is, on this site : Show rigorously that the sum of integrals of $f$ and of its inverse is $bf(b)-af(a)$ with some very interesting answers (the accepted answer of Julian Aguirre, and the answer of Kobe ; the answer of Vim is the same as mine). Another reference : Prove that $\int_a^bf(x)dx+ \int_{f(a)}^{f(b)} f^{-1}(y)dy=bf(b)-af(a)$.
Last but not least, a generalisation of the equation at hand is given by Young's inequality : (http://mathworld.wolfram.com/YoungsInequality.html) as remarked in this answer (https://math.stackexchange.com/q/1154557).


text:
Q: Code builds and runs, but shows red squiggles. using CMAKE in vs code, C++ i have just started to use vscode and CMAKE. and to learn this i have made a simple project in this regard
My code builds and runs, however the red squiggles does not seem to go away. what should i do, is it still a stable program??
project structure:
|CMakeLists.txt
|App
+---CMakeLists.txt
+---main.cpp
|Source_DIR
+---CMakeLists.txt
+---src
------+---helloworld.cpp
+---include
------+---helloworld.h
toplevel cmakelists.txt:
cmake_minimum_required(VERSION 3.15...3.18)

project(Project_RetroTron VERSION 1.0.0)

add_subdirectory(source_DIR)
add_subdirectory(app)

source_DIR/cmakelists.txt:
add_library(hello_world
src/helloworld.cpp)

target_include_directories(hello_world PUBLIC PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>)

source_DIR/include/helloworld.h
#ifndef HELLOWORLD_H
#define HELLOWORLD_H

class helloWorld
{
public:
    helloWorld();
};

#endif

source_DIR/src/helloworld.cpp
#include <iostream>
#include "helloworld.h"

helloWorld::helloWorld()
{
std::cout <<"hello my man" << std::endl;
}

app/CMakeLists.txt
add_executable(helloworldMain main.cpp)

target_link_libraries(helloworldMain PRIVATE hello_world)

app/main.cpp
#include <iostream>
#include <stdio.h>
#include "helloworld.h"
int main()
{
helloWorld heya;
}

i also use cmake-tools which generates this .vscode folder with a settings.JSON file on the top level of the hiearchy:
{
"C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools"
}

used vscode on windows. the build have been erased and rerun so it does not have any old files to refer to.
why do i still have an error!!!
this is the result of a build and run, adn as you can see it runs fine:
cmake make generation
build
run
still it shows error


text:
Q: How to add a post-processing to Sagemaker endpoint? I had a ML model deployed at the Sagemaker endpoint.
I want to add a post-processing after the model making a prediction.
I haved tried add an inference.py (which includes a output_handler) to the model. However that doesn't seem to work.
model = TensorFlowModel(
    role=role,
    model_data=step_train_model.properties.ModelArtifacts.S3ModelArtifacts,
    source_dir = 'Scripts',
    entry_point = "inference.py",
    framework_version=tensorflow_version,
    sagemaker_session=sagemaker_session,
)


text:
Q: How to properly write this usort function I have an array of rows from a database I need to sort by two parameters. I have tried to use the usort() function to accomplish this, but I'm running into some trouble.
Here is my code:
if ($sort == 'rating-desc') usort($records, array('browse_model', 'cmp'));
private function cmp($a, $b) {
    $ratingCmp = strcmp($b['rating'], $a['rating']);
    if ($ratingCmp == 0) {
        return strcmp($b['title'], $a['title']);
    } else {
        return $ratingCmp;
    }
}

Here is the print_r() result of the array before usort():
Array
(
[0] => Array
    (
        [isbn] => 1847199488
        [title] => CodeIgniter 1.7
        [rating] => 3.5
    )

[1] => Array
    (
        [isbn] => 059615593X
        [title] => CSS Cookbook, 3rd Edition (Animal Guide)
        [rating] => 3.5
    )

[2] => Array
    (
        [isbn] => 0321637984
        [title] => Essential Facebook Development: Build Successful Applications for the Facebook Platform
        [rating] => 3.5
    )

[3] => Array
    (
        [isbn] => 0980576857
        [title] => jQuery: Novice to Ninja
        [rating] => 4.5
    )

[4] => Array
    (
        [isbn] => 0596157134
        [title] => Learning PHP, MySQL, and JavaScript: A Step-By-Step Guide to Creating Dynamic Websites (Animal Guide)
        [rating] => 4.5
    )

)

And here is the the result after the usort() (sorted by rating, but not by title):
Array
(
[0] => Array
    (
        [isbn] => 0980576857
        [title] => jQuery: Novice to Ninja
        [rating] => 4.5
    )

[1] => Array
    (
        [isbn] => 0596157134
        [title] => Learning PHP, MySQL, and JavaScript: A Step-By-Step Guide to Creating Dynamic Websites (Animal Guide)
        [rating] => 4.5
    )

[2] => Array
    (
        [isbn] => 0321637984
        [title] => Essential Facebook Development: Build Successful Applications for the Facebook Platform
        [rating] => 3.5
    )

[3] => Array
    (
        [isbn] => 1847199488
        [title] => CodeIgniter 1.7
        [rating] => 3.5
    )

[4] => Array
    (
        [isbn] => 059615593X
        [title] => CSS Cookbook, 3rd Edition (Animal Guide)
        [rating] => 3.5
    )

)

So it puts them in order by rating, but not by title. How can I modify this so it sorts by rating, then by title?
For what it's worth, I've also tried this:
if ($sort == 'rating-desc') {
        foreach ($records as $key => $row) {
            $rating[$key] = $row['rating'];
            $title[$key] = $row['title'];
        }
        array_multisort($title, SORT_DESC, $rating, SORT_ASC, $records);
    }

But that result isn't correct either. It shows the same result as the usort I tried above.
What am I missing?
Thanks much,
Marcus
EDIT: Following some of the suggestions below, here are several things I've tried. None of them solve my problem. They all return the ratings sorted properly, but the title is descending.
private function cmp($a, $b) {
    if ($a['rating'] == $b['rating']) {
        return strcasecmp($b['title'], $a['title']);
    }
    return $b['rating'] - $a['rating'];
}

private function cmp($a, $b) {
    if ($a['rating'] == $b['rating'])
        return strcasecmp($a['title'], $b['title']);
    return $b['rating'] - $a['rating'];
}

    if ($sort == 'rating-desc') {
        foreach ($records as $key => $row) {
            $rating[$key] = $row['rating'];
            $title[$key] = $row['title'];
        }
        array_multisort($rating, SORT_DESC, $title, SORT_ASC, $records);
    }

    if ($sort == 'rating-desc') {
        foreach ($records as $key => $row) {
            $rating[$key] = $row['rating'];
            $title[$key] = $row['title'];
        }
        array_multisort($rating, SORT_DESC, $title, SORT_DESC, $records);
    }

Here is my entire code example - the entire model...

class Browse_model extends Model {

    function Browse_model() {
        parent::Model();
    }

    function get_form_tags() {
        $sql = 'select t.id, t.tag, coalesce(btc.count, 0) as count from tags as t left outer join (select tag_id, count(*) as count from books_tags group by tag_id) as btc on t.id = btc.tag_id order by count desc, tag asc';
        $query = $this->db->query($sql);
        $tags = $query->result();
        return $tags;
    }

    function get_book_info($tags, $andor, $read, $sort) {

        /*
         * SELECT b.isbn, b.title, b.publisher, b.date, b.thumb, b.filename, b.pages, t.tag
         * FROM books AS b
         * INNER JOIN books_tags AS bt ON b.isbn = bt.book_id
         * INNER JOIN tags AS t ON bt.tag_id = t.id
         * ORDER BY b.title, t.tag
         */

        switch ($sort) {
            case 'alpha-desc':
                $order = 'b.title DESC, t.tag';
                break;
            case 'date-desc':
                $order = 'b.date DESC, b.title, t.tag';
                break;
            case 'date-asc':
                $order = 'b.date, b.title, t.tag';
                break;
            default:
                $order = 'b.title, t.tag';
                break;
        }

        $this->db->select('b.isbn, b.title, b.publisher, b.date, b.thumb, b.filename, b.pages, t.tag');
        $this->db->from('books AS b');
        $this->db->join('books_tags AS bt', 'b.isbn = bt.book_id', 'inner');
        $this->db->join('tags AS t', 'bt.tag_id = t.id', 'inner');
        $this->db->order_by($order);
        $query = $this->db->get();
        $result = $query->result();

        $counter = '';
        $records = $meta = $tags = array();
        $count = count($result);
        $i = 1;

        foreach ($result as $book) {
            // If this is not the last row
            if ($i < $count) {
                // If this is the first appearance of this book
                if ($counter != $book->isbn) {
                    // If the meta array already exists
                    if ($meta) {
                        // Add the combined tag string to the meta array
                        $meta['tags'] = implode(', ', $tags);
                        // Add the meta array
                        $records[] = $meta;
                        // Empty the tags array
                        $tags = array();
                    }
                    // Reset the counter
                    $counter = $book->isbn;
                    // Grab the book from Amazon
                    $amazon = $this->amazon->get_amazon_item($book->isbn);
                    // Collect the book information
                    $meta = array(
                        'isbn' => $book->isbn,
                        'title' => strip_slashes($book->title),
                        'publisher' => strip_slashes($book->publisher),
                        'date' => date('F j, Y', strtotime($book->date)),
                        'thumb' => $book->thumb,
                        'file' => $book->filename,
                        'pages' => $book->pages,
                        'rating' => $amazon->Items->Item->CustomerReviews->AverageRating,
                        'raters' => $amazon->Items->Item->CustomerReviews->TotalReviews
                    );
                    // Add the tag to the tags array
                    $tags[] = $book->tag;
                } else {
                    // All we need is the tag
                    $tags[] = $book->tag;
                }
            // If this is the last row
            } else {
                // If this is the first appearance of this book
                if ($counter != $book->isbn) {
                    // Grab the book from Amazon
                    $amazon = $this->amazon->get_amazon_item($book->isbn);
                    // Collect the book information
                    $meta = array(
                        'isbn' => $book->isbn,
                        'title' => strip_slashes($book->title),
                        'publisher' => strip_slashes($book->publisher),
                        'date' => date('F j, Y', strtotime($book->date)),
                        'thumb' => $book->thumb,
                        'file' => $book->filename,
                        'pages' => $book->pages,
                        'rating' => $amazon->Items->Item->CustomerReviews->AverageRating,
                        'raters' => $amazon->Items->Item->CustomerReviews->TotalReviews
                    );
                }
                // All we need is the tag
                $tags[] = $book->tag;
                // Add the combined tag string to the meta array
                $meta['tags'] = implode(', ', $tags);
                // Add the meta array
                $records[] = $meta;
            }
            $i++;
        }

        echo '
';
        print_r($records);
        echo '
';

        if ($sort == 'rating-desc') usort($records, array('browse_model', 'cmp'));

        echo '
';
        print_r($records);
        echo '
';
        return $records;
    }

    private function cmp($a, $b) {
        if ($a['rating'] == $b['rating'])
            return strcasecmp($b['title'], $a['title']);
        return $b['rating'] - $a['rating'];
    }

}

A: Your array is sorted, both by rating and by title.  The problem is that you're sorting case-sensitively, and 'a' comes after 'Z'.
Try using strcasecmp instead of strcmp when comparing titles.
Also, if the rating will always be a number, you should probably be comparing ratings numerically rather than stringwise.  Use $b['rating'] - $a['rating'] instead of strcmp.
EDIT:
I took the same function you had originally, and the same data, and whipped up a test script.  With the function in a class and marked private, PHP warned that the callback to usort was invalid, but continued to run (not touching the array).  With the function marked public, though, it works as expected.  This leads me to believe that either PHP hates your callback being to a private function, or the class name is wrong.
If you want to be able to use a private function, the call to usort apparently needs to be in a function in the same class.  Otherwise usort complains about the callback being invalid and refuses to run.
class Stuff
{
    public function sort(&$arr)
    {
        usort($arr, array('Stuff', 'cmp'));
    }

    private function cmp($a, $b)
    {
        $ratingCmp = $b['rating'] - $a['rating'];
        if ($ratingCmp == 0) {
            return strcasecmp($a['title'], $b['title']);
        } else {
            return $ratingCmp;
        }
    }
}

Stuff::sort($records);
print_r($records);

For me, this prints out the books sorted descending by rating, then ascending by title.  If this doesn't work for you, something's funky.

A: Use simple boolean comparison operators for comparing numeric fields such as rating, rather than strcmp:
private function cmp($a, $b) {
    if ($b['rating'] == $a['rating'])
       return strcmp($b['title'], $a['title']);
    return $b['rating'] - $a['rating'];
}

It also looks like you're sorting descending by both rating and title; change your strcmp to return strcmp($a['title'], $b['title']) to sort by rating(descending) and title(ascending).

A: You could alternatively use array_multisort()
deleted code
Creates a couple extra arrays, but gets the job done; if you put the code into a function or a method as you're doing (pass $records by reference) those will get destroyed on function exit.
Edit: I see you've put into your question that you've tried this. How doesn't it work?
Edit: This works for me:
foreach ($records as $rec) {
    $rating[] = $rec['rating'];
    $title[] = strtolower($rec['title']);
}

array_multisort($title, SORT_DESC, $rating, SORT_ASC, $records);

print_r($records);

Another edit:
Given this array:
$records = array(
  0 =>
  array (
    'isbn' => '1847199488',
    'title' => 'CodeIgniter 1.7',
    'rating' => 3.5,
  ),
  1 =>
  array (
    'isbn' => '1847199488',
    'title' => 'CodeIgniter 1.7',
    'rating' => 3,
  ),
  2 =>
  array (
    'isbn' => '1847199488',
    'title' => 'CodeIgniter 1.7',
    'rating' => 3.2,
  ),
  3 =>
  array (
    'isbn' => '1847199488',
    'title' => 'CodeIgniter 1.7',
    'rating' => 4.5,
  ),
  4 =>
  array (
    'isbn' => '059615593X',
    'title' => 'CSS Cookbook, 3rd Edition (Animal Guide)',
    'rating' => 3.5,
  ),
  5 =>
  array (
    'isbn' => '0321637984',
    'title' => 'Essential Facebook Development: Build Successful Applications for the Facebook Platform',
    'rating' => 3.5,
  ),
  6 =>
  array (
    'isbn' => '0980576857',
    'title' => 'jQuery: Novice to Ninja',
    'rating' => 4.5,
  ),
  7 =>
  array (
    'isbn' => '0596157134',
    'title' => 'Learning PHP, MySQL, and JavaScript: A Step-By-Step Guide to Creating Dynamic Websites (Animal Guide)',
    'rating' => 4.5,
  ),
);

This code:
foreach ($records as $rec) {
    $rating[] = $rec['rating'];
    $title[] = strtolower($rec['title']);
}

array_multisort($rating, SORT_DESC, SORT_NUMERIC, $title, SORT_ASC, SORT_STRING, $records);

var_export($records);

Will produce this:
array (
  0 =>
  array (
    'isbn' => '1847199488',
    'title' => 'CodeIgniter 1.7',
    'rating' => 4.5,
  ),
  1 =>
  array (
    'isbn' => '0980576857',
    'title' => 'jQuery: Novice to Ninja',
    'rating' => 4.5,
  ),
  2 =>
  array (
    'isbn' => '0596157134',
    'title' => 'Learning PHP, MySQL, and JavaScript: A Step-By-Step Guide to Creating Dynamic Websites (Animal Guide)',
    'rating' => 4.5,
  ),
  3 =>
  array (
    'isbn' => '1847199488',
    'title' => 'CodeIgniter 1.7',
    'rating' => 3.5,
  ),
  4 =>
  array (
    'isbn' => '059615593X',
    'title' => 'CSS Cookbook, 3rd Edition (Animal Guide)',
    'rating' => 3.5,
  ),
  5 =>
  array (
    'isbn' => '0321637984',
    'title' => 'Essential Facebook Development: Build Successful Applications for the Facebook Platform',
    'rating' => 3.5,
  ),
  6 =>
  array (
    'isbn' => '1847199488',
    'title' => 'CodeIgniter 1.7',
    'rating' => 3.2,
  ),
  7 =>
  array (
    'isbn' => '1847199488',
    'title' => 'CodeIgniter 1.7',
    'rating' => 3,
  ),
)


text:
Q: Why would browsers not give complete API control over HTTP2 frames from JavaScript?
But gRPC cannot be used properly inside browsers, because they don't (and probably will not) provide sufficient API to control HTTP2 frames from JavaScript.
(https://medium.com/@denis.zhbankov/grpc-web-via-http2-b05c8c8f9e6)

I don't understand why this would be the case? Is it cause of some security issue or some technical challenges? All the documentation for gRPC-Web just says you can't do it, but no one really explains why browsers might never give complete control over HTTP2 on JavaScript. So am hoping someone could explain why?


text:
Q: Does Visual Studio 2015 GIT use 3-way merge? When I use Visual Studio 2015's merge tool to fix conflicts, it seems like it is performing worse than when I use P4Merge with GIT's command line (which finds almost no conflicts at all).
Is this because of the tool itself? Does Visual Studio 2015's merge/diff tool provide 3-way merge for GIT?

A: TL;DR: Visual Studio does three-way merges, both when merging your Git repository and when trying to resolve the conflicts that arise.  It's not immediately clear why VS would be inferior to P4Merge while resolving that conflict, but without knowing anything else, I suspect that P4Merge is better about inconsistent line ending configurations.
There are two stages to the merge process:  first, performing the merge and producing a combined tree that includes new changes from both branches and (possibly) conflicts, and second, a conflict resolution stage.
In Visual Studio, the first stage is a regular git merge, which is indeed a three way merge.  The "merge base" is found, which is the last commit that exists in both branches; this is the last time your two branches were merged, or the point at which one branch was created from the other.
Then a three way merge is performed at the tree level by determining which files have changed in each branch, comparing them to the common ancestor.  If a file has changed in one branch, then that branch's changes will be included in the new tree.  If a file has changed in both branches, then we need to do a three way merge at the file level, which is very similar and compares the files in each branch to their common ancestor.  Now, if any region of the file has changed in one branch, relative to the common ancestor, then we'll include that changed region in the merged file.  But if both branches have changed the same region, then a conflict will be produced.
Git will produce a file in the working directory with conflict markers, but it will also record the two files and their common ancestor so that you can use a merge tool (like Visual Studio or P4Merge).
(Note that when you perform a merge using Visual Studio, it uses the libgit2 library, though it produces the same results as Git itself.)
Once you have a merge conflict, your merge tool can take the three files and provide you a graphical experience to resolve the conflicts.  Typically, the first step in each of these tools is to try to do the file-level merge again, and will create a new "result" file (often shown in the middle pane of three panes, with the two branches on either side, or less commonly above or below the two branch files).
This result will typically include any regions that were not overlapping automatically merged in, and the UI will generally prompt you to resolve the overlapping regions that couldn't be automerged.  Generally speaking, my experience is that there isn't a lot of difference here, but certainly there could be variations.  In particular:

*

*Some tools may be more aggressive about joining small conflicts that are near to each other together, which may give fewer but larger conflicts that may be easier to resolve - for example, if you had several conflicts that were one-line each it may be preferable to squash those into a single, larger conflict.

*Some tools may do encoding translations, so that you can correctly merge a file that was UTF-8 in the common ancestor, UTF-16 in one branch and Latin1 in the other branch and get an intelligent output in one of those encodings (or even a different one altogether).

*Some tools may elide whitespace changes.  I have a hunch that this might be where you're seeing differences between Visual Studio and P4Merge; line ending configuration is notoriously difficult to setup across an entire team in Windows Git clients.  A merge tool that simply ignored line ending differences could produce a much nicer experience than one that did not.
You could even use a tool that understood the structure of your document:  for example, merging two XML files typically doesn't try to understand the structure of the XML, but you could use a tool that understood XML to avoid things like whitespace changes that don't actually matter to the meaning of the file.


text:
Q: Linq lambda not working but delegate does OK, this is doing my head in - I'm not even sure how to search for this.
Here is the first part of my function:
var rules = context.Rules.Include(r => r.CreatedBy).Include(r => r.ModifiedBy);

IUserManager um = GetUserManager();
var currentUser = um.GetCurrent();

Can someone tell me why this works:
return rules.Where(delegate(Rule r)
{
    return r.CreatedBy.CompanyID == currentUser.CompanyID;
});

but this doesn't:
return rules.Where(r => r.CreatedBy.CompanyID == currentUser.CompanyID);

*

*It's EF Code first and CreatedBy and ModifiedBy are both virtual properties.

*r.CreatedBy and currentUser are both instances of the same class (if you didn't already work this out)

*What the second snippet is returning is an empty list.  It's as though the eager loading isn't working and the lambda doesn't cause a lazy load.

Note:  I've just discovered that if I change the first line to
var rules = context.Rules.Include(r => r.CreatedBy)
    .Include(r => r.ModifiedBy).ToList()

then the lambda works.  The question still stands though.  Why to I have to use the ToList() or the delegate.  I'm doing the same thing elsewhere in the same class and it works as I'd expect.
Thanks

A: This is because lambdas can be implicitly converted to delegates or to expression trees.  In the first case, the delegate is converted to an expression tree because rules is IQueryable<> and overload resolution chooses Queryable.Where.  When you use the anonymous function, however, that can't be converted to an expression tree, so overload resolution has to choose Enumerable.Where.
When you make rules into a List<>, that forces overload resolution to choose Enumerable.Where, because List<> does not implement IQueryable<>.  You could use AsEnumerable() to achieve the same effect without the overhead of creating the list.
As to why this doesn't work when you're "doing the same thing elsewhere in the same class and it works as I'd expect," we might be able to help if you give an example of code that does work.


text:
Q: verdana font on linux I'm trying to use the verdana.ttf font to create a RTF report with Java, but it isn't working on Linux.
Does anybody know how I do this?
     String contextPath = FacesUtil.getServletContext().getRealPath("\\");
     try {
          FontFactory.register(contextPath + "WEB-INF\\Fonts\\verdana.ttf");
     } catch (Exception e) {
          e.printStackTrace();
     }

     if (negrito) {
          font = FontFactory.getFont("Verdana", 8, Font.BOLD, new Color(0, 0, 0));
     }
     cell = new Cell(new Paragraph(paragraph, font));
            cell.setBackgroundColor(new Color(255, 255, 255));
            cell.setBorderColor(new Color(255, 255, 255));
            if (center)
                cell.setHorizontalAlignment(Cell.ALIGN_LEFT);

            cell.setRowspan(1);
            cell.setColspan(1);
            return cell;

A: I guess if it's not working on Linux it's because you hard-code file separator...
\\ is only for Windows. Replace those with a field made from System.getProperty("file.separator").
Example :
String separator  = System.getProperty("file.separator");
FontFactory.register(contextPath + "WEB-INF"+separator+"Fonts"+separator+"verdana.ttf");


text:
Q: Python make oneliner for multiline text in sqlnet.ora I have following text:
SQLNET.CRYPTO_CHECKSUM_TYPES_SERVER=(MD5,SHA1)
WALLET_LOCATION=
(SOURCE=
(METHOD=FILE)
(METHOD_DATA=
(DIRECTORY=/oracle/.wallets)
)
)
SQLNET.WALLET_OVERRIDE=TRUE

and want to get that as a result:
SQLNET.CRYPTO_CHECKSUM_TYPES_SERVER=(MD5,SHA1)
WALLET_LOCATION=(SOURCE=(METHOD=FILE)(METHOD_DATA=(DIRECTORY=/oracle/.wallets)))
SQLNET.WALLET_OVERRIDE=TRUE

What is most effective way to do that with native Python (without additional external packages)?
There can be others multi-line parameters. And I don't know in advance how many parenthesis they can have.
Edit1. I don't need exact solution. At least just an algorithm.

A: One way you can do is to use the line number for start and end and then concatenate all lines between them. Btw, I saved your text in a file but you can directly feed it to the code as well.
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()

count = 0
lineNumStart, lineNumEnd = 1, 7
outStringJoined = ""
for line in Lines:
    if count>=lineNumStart and count<lineNumEnd:
        outStringJoined += line.strip()
    else:
        outStringJoined += line
    count+=1
print(outStringJoined)

To make it more flexible, you can use the pair such as ("(", ")"). If the first element of the pair is found then the code would continue concatenating until its matching pair is found!

A: with open('sqlnet.ora', 'r') as file:
    sqlnetora = file.read()
sqlnetora = re.sub(r' +', '', re.sub(r'\n+', '\n', sqlnetora))\
                .replace(' \n','\n')
text_list = sqlnetora.splitlines()
is_mvar = False # flag if we are working with multiline parameter
oneliner = []   # list with one-line parameters
mvar = []       # list for multiline parameter
for line in text_list:
    po = line.count('(')
    pc = line.count(')')
    # this is not multiline parameter
    if not is_mvar:
        if line[-1:] == ')' and po == pc:
            oneliner.append(line)
        elif line[-1:] != '=' and po == pc:
            oneliner.append(line)
        # we've found start of multiline parameter
        else:
            mpo = line.count('(')
            mpc = line.count(')')
            is_mvar = True
            mvar.append(line)
    # this is multiline parameter
    else:
        mpo += po
        mpc += pc
        # if this is last line for multiline parameter?
        if mpo == mpc:
            mvar.append(line)
            oneliner.append(('').join(mvar))
            mvar.clear()
            is_mvar = False
        # this is not last line of multiline parameter
        else:
            mvar.append(line)
print(*oneliner, sep='\n')


text:
Q: Qual a diferença entre DI, factories e locators? Já perguntei sobre injeção de dependência. Ele é muito usada. Na minha opinião é até abusada.
Mas vi que no lugar dela pode-se usar factories ou locators. O que seriam eles, quais as vantagens e desvantagens de usar cada um?

A: Injeção de dependência e service locator (estou assumindo que com locator você quis dizer Service Locator) são maneiras de se realizar a inversão de dependência. Factories, por sua vez, se preocupam em instanciar objetos sem que seu chamador se preocupe com seus detalhes de instanciamento (http://www.oodesign.com/factory-pattern.html).
Dependências e inversão de controle
Ao usar inversão de dependência, se você souber qual o objeto chamado em bootstrap time (mais nesse tópico em parágrafos mais a frente), então você não precisa se preocupar em delongar até o último momento para usar a dependência. Nesses casos, a injeção de dependência vai tornar seu trabalho muito fácil. Um exemplo de onde se pode usar uma injeção de dependência é em usos especiais de multitons ou mesmo singletons, que se conhece a priori/estaticamente qual a necessidade.
Teve um projeto grande que eu trabalhei de unificação de código. Na empresa, existiam dois produtos que deveriam fazer a mesma coisa, um webapp em GWT (com iBatis gerenciando acesso ao banco) e uma aplicação mobile em TotalCross. Devido à incompatibilidades entre os recursos de banco TotalCross e JDBC, e também que existem API Java que o iBatis usava que não existem no TotalCross, não havia como compartilhar código que fazia o resgate de informações nem o que fazia a persistência. Então, a solução foi ter uma interface cujas implementações acessariam o banco e deixar o ambiente que subia a aplicação inserir a classe apropriada. No webapp, o Spring tomou conta disso usando as interfaces @Component e @Autowired. No TotalCross, era mais rápido fazer a injeção na mão usando uma classe para realizar o bootstrap da aplicação.
Sobre o ciclo de vida da aplicação, eu mencionei o bootstrap time. Normalmente não é o termo mais comum, mas eu precisei diferenciar o tempo em que a aplicação está se preparando para subir do tempo em que ela realmente está ativamente rodando. Essa separação temporal se encontra muito, por exemplo, quando você está trabalhando na Unity, em que você prepara a cena usando o MonoBehaviour.start para tratar de algumas conformações do ambiente que precisa ter antes de começar o jogo, porém que não é possível informar no tempo de construção do objeto/é mais prático resolver programaticamente do que no editor de cena; eu gosto de imaginar que o bootstrap time é análogo à montagem de um jogo de tabuleiro, como a distribuição de territórios e objetivos no War.
Ambientes de uma aplicação
De modo geral, toda aplicação tem os seguintes ambientes:

*

*compile time, em que o compilador consegue decidir com o que se está trabalhando; se você consegue prender o valor de uma variável em compile time, então significa que você como programador deve colocar os valores de modo imperativo;

*static code time, no caso do Java, processamento de anotação acontece nesse ponto; de certo ponto de vista, é como uma continuação do compile time;

*bootstrap time, esse é o tempo entre apertar o botão run e a aplicação estar de fato rodando, o tempo de setup; injeção de dependência do Spring via XML se encaixa aqui (também creio que a injeção via @Autowired também); normalmente é uma parte do run time, mas neste caso em específico creio que seja notório destacá-lo;

*run time, o ambiente em que o código está realmente funcionando e a aplicação no ar; qualquer coisa que exclusivamente só pode ser decidida aqui é completamente dinâmica, vindo de fontes alheias ao código.

Um exemplo de service locator bem utilizado é no SQuirreL, onde o programa não sabe (nem tem como saber) a priori em que SGBD vai se conectar, dependendo do serviço de conexões cadastradas no JDBC para conseguir realizar o contato com sucesso.
Injeção de dependência pode ocorrer também na criação de objetos (como no caso do Spring tendo a dependência no construtor). Essa injeção pode ocorrer sob demanda, não necessariamente a priori. Neste caso, a injeção funciona como se estivesse no bootstrap do componente, antes dele estar em seu run time propriamente dito.
Factories
Factories são objetos que criam objetos, então a inversão de dependência aqui ocorre em outro nível. Por exemplo, para criar conexões de socket para passar adiante para a classe que lida com conexões HTTP, de modo que quem fala HTTP não precise se preocupar em falar _socket_ês, precisa apenas que passem um construtor de sockets que faça isso. Vide SocketFactory do Java, que faz exatamente isso.
O padrão de injeção de dependência pode ser usado de maneira a usar/precisar de factories.
Quais as vantagens e desvantagens de cada um deles?
De modo geral, eu sempre prefiro onde possível usar injeção de dependência, porque com ela eu deixo o fluxo do programa mais previsível. Sem falar que ela é fácil de aplicar tendo um framework que faça isso. Eu sempre ponho previsibilidade e facilidade como primeiras escolhas.
Locators são para quando você consegue consultar de um registro comum o que você precisa naquele momento. Eu acho particularmente feio, mas funcional. Também permite hotswaps para uma melhor performance ou estabilidade. Por exemplo, se tiver uma thread em paralelo checando se foi colocada uma biblioteca de processamento de imagem mais nova e trocando o retorno para a requisição de leitor de JPG para o mais novo desejado.
Factories normalmente são usadas para uma delayed creation do objeto, para ele de fato ser criado no ponto em que ele será usado.

UPDATE: DAGGER
Recentemente, em uma requisição de um cliente no trabalho, tive acesso ao injetor de dependência dagger.
Eis aqui algumas fontes sobre o assunto:

*

*considerações e elucidações feitas pela equipe TotalCross (eu incluso): https://gitlab.com/totalcross/TotalCross/wikis/dagger

*página oficial: https://google.github.io/dagger/

*fonte: https://github.com/google/dagger
Basicamente, o dagger escreve o trabalho do bootstrap time em código Java, transformando as operações desse para o momento de static code time. A ideia do dagger é remover o peso extra devido ao modo de se gerar a injeção de dependência no Spring ou no Guice, transformando o trabalho que normalmente é feito por introspecção (o que normalmente é impossível em compile time) para uma análise que é feita em código estático (ou seja: durante a compilação).
Supostamente, o dagger tem como resultado final o mesmo que a injeção de dependência feita à mão, porém ele gerencia isso para você de uma maneira muito boa.


text:
Q: Provide access to user based on rule in a organisation website I have a website with user login and dB describing his / her roles .
All the pages in the website are not accessible to everyone . The accessibility of each page should be based on the user role .
Ie the accessibility a manager of the organisation has will be different from that of a technician and both will be different from the accessibility of a trainee .
How can I implement this in my website easily ?

A: You should check Angular Acl (Access Control List)
Documentation:
https://github.com/mikemclin/angular-acl


text:
Q: Audio file not playing entirely in voice channel With a bot, I'm trying to play an audio file (mp3) within an audio channel, using discord.js, ffmpeg and opusscript.
Basically, that's how it works :
bot.on('message', msg => {
    if (msg.author.bot) return;
    if (msg.content.substring(0,3) == "fp!") {
        var audioID = msg.content.substring(3,msg.length);
        var channel = msg.member.voiceChannel;

        if (!channel) msg.channel.send("T'es pas dans un vocal, con.");
        else {
            msg.member.voiceChannel.join()
            .then((connection) => {
              connection.playFile(`./audios/${audioID}.mp3`);
            });
        }
      }
        return;

});

So, the audio plays, but it stops before its end (for a 5s audio file, it stops after 3s for example). The bot stays in the channel, I can play again, but for all my files it stops before the end.
How can I fix that ?

A: This is a know bug, there are not really any fixes for it exept installing discord.js master wich has a full voice rewrite by doing: npm i discordjs/discord.js


text:
Q: ORA-00911 Error when trying to insert through JDBC in Oracle I do have a system that changes a placeholder by its value before sending the request to the database.
INSERT INTO MYAPP.LOGPRODUCAO
(NOMERECURSOCONJUNTO, ORDEMPRODUCAO, OPERACAO, QTDEBOAS, INICIO, FIM, MATRICULAFUNCIONARIO, STATUS)
VALUES(
    {nomeRecursoConjunto},
    CAST({ordemProducao} as VARCHAR(100)),
    {operacao},
    TO_NUMBER({qtdeBoas}),
    TO_TIMESTAMP({inicio}, 'YYYY-MM-DD"T"HH24:MI:SS.FF3'),
    TO_TIMESTAMP({fim}, 'YYYY-MM-DD"T"HH24:MI:SS.FF3'),
    {matriculaFuncionario},
    {status})

After replacing, it becomes something like this:
INSERT INTO MYAPP.LOGPRODUCAO
(NOMERECURSOCONJUNTO, ORDEMPRODUCAO, OPERACAO, QTDEBOAS, INICIO, FIM, MATRICULAFUNCIONARIO, STATUS)
VALUES(
    'NAME',
    CAST(43267 as VARCHAR(100)),
    10,
    TO_NUMBER('0.0'),
    TO_TIMESTAMP('2020-07-20T14:40:43.819', 'YYYY-MM-DD"T"HH24:MI:SS.FF3'),
    TO_TIMESTAMP('2020-07-20T15:28:28.359', 'YYYY-MM-DD"T"HH24:MI:SS.FF3'),
    2389,
    'I')

When I take the query above and execute through DBeaver, it works. The row is inserted.
When I'm running through a JDBC it returns the following error:
Caused by: java.sql.SQLSyntaxErrorException: ORA-00911: caractere inválido
    at
...
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
    ...
Caused by: java.sql.SQLSyntaxErrorException: ORA-00911: caractere inválido
    at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:494)
    at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:446)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1054)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:623)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:612)
    at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:213)
    at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:37)
    at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:896)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1119)
    at oracle.jdbc.driver.OracleStatement.executeUpdateInternal(OracleStatement.java:1661)
    at oracle.jdbc.driver.OracleStatement.executeLargeUpdate(OracleStatement.java:1626)
    at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:1613)
    at oracle.jdbc.driver.OracleStatementWrapper.executeUpdate(OracleStatementWrapper.java:282)
    ... 52 more
Caused by: Error : 911, Position : 137, Sql = INSERT INTO MYAPP.LOGPRODUCAO
(NOMERECURSOCONJUNTO, ORDEMPRODUCAO, OPERACAO, QTDEBOAS, INICIO, FIM, MATRICULAFUNCIONARIO, STATUS)
VALUES(
    'NAME',
    CAST(43267 as VARCHAR(100)),
    10,
    TO_NUMBER('0.0'),
    TO_TIMESTAMP('2020-07-20T14:40:43.819', 'YYYY-MM-DD"T"HH24:MI:SS.FF3'),
    TO_TIMESTAMP('2020-07-20T15:28:28.359', 'YYYY-MM-DD"T"HH24:MI:SS.FF3'),
    2389,
    'I'), OriginalSql = INSERT INTO MYAPP.LOGPRODUCAO
(NOMERECURSOCONJUNTO, ORDEMPRODUCAO, OPERACAO, QTDEBOAS, INICIO, FIM, MATRICULAFUNCIONARIO, STATUS)
VALUES(
    'NAME',
    CAST(43267 as VARCHAR(100)),
    10,
    TO_NUMBER('0.0'),
    TO_TIMESTAMP('2020-07-20T14:40:43.819', 'YYYY-MM-DD"T"HH24:MI:SS.FF3'),
    TO_TIMESTAMP('2020-07-20T15:28:28.359', 'YYYY-MM-DD"T"HH24:MI:SS.FF3'),
    2389,
    'I'), Error Msg = ORA-00911: caractere inválido
    at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:498)
    ... 66 more


text:
Q: Request to use token, but token was unavailable to the client. - DiscordJS Error I'm trying to make a bot that sends a message every day at 5 am EST so I'm trying to create a Cron job. This is what I have but every time I run it, it sends a message straight away instead of the time I want it to send at. Here's my code. I have it at 5 am in the code but I change the time when I'm testing it out.
Thank you.
const e = require('express')
const client = new Discord.Client()

const config = require('./config.json')
const privateMessage = require('./private-message')

const cron = require('node-cron');
const express = require('express');

client.on('ready', () => {
    console.log('running');
})

cron.schedule('0 5 * * *', function() {
    console.log('cron is working');
}, {
    scheduled: true,
    timezone: "America/New_York"
});

    client.login(config.token).then(() => {

        console.log('sending');
        client.users
            .fetch('749097582227357839').then((user) => {
                user.send(`hello`,);
            })

        console.log("nope");

        client.destroy();

});

client.login(config.token)

A: You have two client.login functions for some reason, please remove the first one.
You dont seem to use cron in the correct way - the cron.schedule function is where you put the code to repeat, not below it.
That is why your bot is sending the message immediately - the code is simply doing what you are asking it to do right after it schedules a cron job.
If you have everything else correct, your bot will actually log cron is working to the console at 5am every morning with your current code - the below code should achieve what you need.
To sum up:
//declare packages here

cron.schedule('0 5 * * *', function() {
   console.log('sending');
   client.users.fetch('749097582227357839').send('hello');
}, {
    scheduled: true,
    timezone: "America/New_York"
});

client.login(config.token); //only ever use one of these events, it causes issues if you use multiple

there is also no need to do client.destroy - it shouldn't make any difference