text:
Q: Make page mobile friendly I made 5 stars for a page that I am working on, now I am realizing that its not mobile friendly and when I make the screen narrower it adds the stars in a vertical line, is there an easy way I can make this mobile friendly while still keeping the stars horizontal ?
I tried adding more divs in attempts keep the stars horizontal no matter the size of the screen.

body {
  background-color: #FFFFFF;
}

.flex {
  display: flex;
  /*14vm*/
  width: 16vw;
  margin: 0 auto;
  justify-content: space-between
}

.rate {
  position: relative;
  /*46vm*/
  height: 65vm;
  padding: 0 10px;
}

.rate:not(:checked)>input {
  position: absolute;
  top: -9999px;
}

.rate:not(:checked)>label {
  float: right;
  width: 1em;
  overflow: hidden;
  white-space: nowrap;
  cursor: pointer;
  font-size: 35px;
  color: #ccc;
}

.rate:not(:checked)>label:before {
  content: '★ ';
}

.rate>input:checked~label {
  color: #9d0505;
}

.rate:not(:checked)>label:hover,
.rate:not(:checked)>label:hover~label {
  color: #9d0505;
}

    <input type="radio" onclick="rate1_scr5();" id="star10" name="rate1" value="1" />
    5 stars
    <input type="radio" onclick="rate1_scr4();" id="star9" name="rate1" value="2" />
    4 stars
    <input type="radio" onclick="rate1_scr3();" id="star8" name="rate1" value="3" />
    3 stars
    <input type="radio" onclick="rate1_scr2();" id="star7" name="rate1" value="4" />
    2 stars
    <input type="radio" onclick="rate1_scr1();" id="star6" name="rate1" value="5" />
    1 star

A:
is there an easy way I can make this mobile friendly while still keeping the stars horizontal?

Yes you can, you just have to set the parent container's width to max-content to prevent wrapping. See the snippet below:

body {
  background-color: #FFFFFF;
}

.flex {
  display: flex;
  /*14vm*/
  width: max-content;
  margin: 0 auto;
  justify-content: space-between
}

.rate {
  position: relative;
  /*46vm*/
  height: 65vm;
  padding: 0 10px;
}

.rate:not(:checked)>input {
  position: absolute;
  top: -9999px;
}

.rate:not(:checked)>label {
  float: right;
  width: 1em;
  overflow: hidden;
  white-space: nowrap;
  cursor: pointer;
  font-size: 35px;
  color: #ccc;
}

.rate:not(:checked)>label:before {
  content: '★ ';
}

.rate>input:checked~label {
  color: #9d0505;
}

.rate:not(:checked)>label:hover,
.rate:not(:checked)>label:hover~label {
  color: #9d0505;
}

    <input type="radio" onclick="rate1_scr5();" id="star10" name="rate1" value="1" />
    5 stars
    <input type="radio" onclick="rate1_scr4();" id="star9" name="rate1" value="2" />
    4 stars
    <input type="radio" onclick="rate1_scr3();" id="star8" name="rate1" value="3" />
    3 stars
    <input type="radio" onclick="rate1_scr2();" id="star7" name="rate1" value="4" />
    2 stars
    <input type="radio" onclick="rate1_scr1();" id="star6" name="rate1" value="5" />
    1 star

This SO post might help you understand more of max-content value.

A: Modify your flex class. It's a good start, but you should change the width to make it mobile-friendly. 16vw is going to be really small on mobile. You could do something like 300px or you can use @media screen queries (like @media screen and (min-width: 900px) { ... } to set the width of the class based on the width of the screen. The suggestion to set the width to max-content is also a good idea.


text:
Q: How to extract only files and not directory heirarchy How to extract only files and not directory heirarchy.
Suppose I have a myarchive.tgz file which has many directories in it and inside each directory their are files.
 eg.myarchive.tgz/folder1/file1.txt
                 /folder2/folder2.1/file2.txt

Now whenever I extract it gets in directory with the same heirarchy it's in archive.
I want to extract like
myarchive/file1.txt
         /file2.txt

like this.
How to do it? Please help!

A: You could unpack the tarball to a temporary folder:
rm -rf /tmp/foo && mkdir /tmp/foo # make sure the folder exists and is empty
tar xf foo.tgz -C /tmp/foo

Then copy over the files to the final location:
rm -rf unpacked && mkdir unpacked # make sure the folder exists and is empty
find /tmp/foo -type f -exec cp -v {} unpacked \;

Note: tar -C is specific to GNU tar. If your tar doesn't understand -C use:
cd /tmp/foo
tar xf foo.tgz

redpajama_set_name: RedPajamaStackExchange


text:
Q: SMB-shared printer visible, but can no longer connect to it I have a Brother HL-L2300D printer, connected by USB to a Raspberry Pi serving as a print server for a LAN segment somewhere. The Pi runs Raspbian, and has a samba server and a CUPS server running - the exact configuration of which I had forgotten about - and it was happily humming along for a couple of years, printing as requested.
Then about a week ago, users of several Windows 10 machines on the LAN started complaining about print failures. I was telling people to try removing the printer, then re-connecting to it (which in some cases seems to work for printers); but - they were unable to connect to the printer.
We checked that the printer itself works when directly connected one of those Windows boxes (via USB); and that, on the CUPS web interface, the printer is enabled and a test page prints correctly. The printer's CUPS management page says:
brother-hl-l2300d (Idle, Accepting Jobs, Shared, Server Default)

The error message people get when trying to connect the printer is:

Windows couldn't connect to the printer. Check the printer name and try again. If this is a network printer, make sure that the printer is turned on, and that the printer address is correct.

I should mention that \\1.2.3.4\ is browseable (where 1.2.3.4 is the print server's IP), and shows the printer. It's just the connection that fails.
My question: What could cause this failure, and what can I do to overcome it?
Additional information (ask if anything is missing):

*

*I've tried uninstalling the Windows print driver for the printer, then adding a printer with the new driver. This gets me to the "Can't Connect" error before the dialog in which I can provide the new driver.

*iptables --list on the Pi print server yields empty lists.

*The version of Samba is: 4.5.16

*The Raspbian version is 9.

*When I try to Open rather than Connect to the printer, I get an Error 0x709.

*cupsd.conf: here (pastebin.com)

A: tl;dr: Uninstall Windows updates KB5006670 and/or KB5005565.
(Credit to @harrymc for this answer.)
On October 12th, computers running Windows 10 received an automatic update from Microsoft, KB5006670. It has been reported that (emphasis mine):

The recently released ... update is just the latest in a long
string of updates that have led to problems for Windows 10 users.
People whose systems have been negatively affected by the update
report being unable to connect to network printers while seeing
0x00000709 and Element not found errors.

See also an item on the BleepingComputer website's MS news channel:
New Windows 10 KB5006670 update breaks network printing
based on a long thread on their forum, with sysadmins ranting about this prob. In the future, you may want to consult that forum if you don't find an issue addressed here on SU.
This follows a similar problem last month, with Windows Update KB5005565, released September 14th.
In my case, the users' computers had the later update (6670). Uninstalling it allowed connecting to the network printer and printing seems to work (have not tried all machines yet).

A: Summary of the above discussion:
On the face of it, a working setup suddenly stopped working,
where the Windows 10 computers were suddenly unable to connect
to the network
printer.
After some verification, the only explanation left was Windows
update, which is after all one of the greatest dangers for
system stability.
The candidate updates were KB5005539 and KB5006670.
A search found the article
KB5006670 is the latest Window update to cause printer problems,
which said:

People whose systems have been negatively affected by the update report being unable to connect to network printers

The removal of KB5006670 did fix the problem and network connectivity
was restored to the printers.
For hiding unwanted Windows updates, see the article
How to Hide or Show Windows Updates in Windows 10,
which also provides a download of the Microsoft Troubleshooter
(which Microsoft does not provide any more).


text:
Q: npm gives error when installing module not specified by me I am trying to install the modules needed by my application using
npm install

When I do this, I get the following error:
npm ERR! Error: No compatible version found: gulp-util@'^3.0.0'
npm ERR! Valid install targets:
npm ERR! ["0.0.1","1.0.0","1.1.0","1.1.1","1.2.0","1.3.0","2.0.0","2.1.1","2.1.2","2.1.3","2.1.4","2.2.0","2.2.1","2.2.2","2.2.3","2.2.5","2.2.6","2.2.7","2.2.8","2.2.9","2.
2.10","2.2.11","2.2.12","2.2.13","2.2.14","2.2.15","2.2.16","2.2.17","2.2.18","2.2.19","2.2.20","3.0.0","3.0.1","3.0.2","3.0.3","3.0.4","3.0.5","3.0.6"]

However, I never require this module into my project.
I'm assuming it's an issue internal of npm or node.
Furthermore, also strange is that when I run
npm list -g

I get the following output rather than seeing the versions of npm which are installed.
├── node@0.0.0

My package.json file is:
{
  "name": "myProject",
  "version": "0.0.1",
  "dependencies": {},
  "scripts": {
    "test": "gulp test"
  },
  "devDependencies": {
    "browserify": ">=9.0.7",
    "gulp": ">=3.8.11",
    "gulp-concat": ">=2.6.0",
    "gulp-html-replace": ">=1.5.1",
    "gulp-react": ">=3.0.1",
    "gulp-streamify": ">=1.0.2",
    "gulp-uglify": ">=1.2.0",
    "gulp-util": ">=3.0.6",
    "reactify": ">=1.1.1",
    "vinyl-source-stream": ">=1.1.0"
  },
  "engines": {
    "node": ">=0.10.0"
  }
}

A: Your version of npm is so old that it doesn't support version ranges specified using ^. You are not using that syntax but it is quite likely one of the modules you are specifying is using that syntax for it's dependencies, and so when it tries to run npm install gulp-util@'^3.0.0' it throws that error.
If you update your npm either by updating node or by installing the latest npm with npm install -g npm then you should be able to proceed.


text:
Q: Java Swing MVC architecture How is a Java Swing application organized to achieve MVC architecture?

A: See: A Swing Architecture Overview

A: i would categorize my classes:

*

*object classes: to represent objects

*functionality classes: to provide functionality. for instance, methods to read/write files or methods to make calculations possibly using some object classes

*and GUI classes (using Swing) which will be what the user will see. these classes will do what the functionality classes provide.

A: Your project must be consist at least of three entities: your model, your view and yor controller.Your model represents your data, view is a view for your data and controller is something that creates both view and controller.
Let's suppose you've a rectangle and want to build a GUI that shows the area of the rectangle when user types its side.
Your model must extends Observable class, in this way you mark class Square as model in your MCV architecture.
public class Square extends Observable {ecc....}

when you set the side, you have to set the state of the model as changed and notify observers which are listening on your model, such as:
public void setSide(double side) {
  this.side=side;
  setChanged();
  notifyObservers();
}

PS: setChanged() and notifyObservers() are provided by Observable class.
Now the second step, your View must implement Observer interface, so you mark this as listener for model's change. Implementing Observer forces you to write update method.
public class Square_View implements Observer {
    JLabel area;
    ......
    @Overried
    public void update (Observable o, Object arg1) {
        Square square=(Square)o;
        area.setText(square.getArea());
    }

Well, as soon as your square's side changes, a notification is triggered and update method is invoked.
Now the controller, the mind of MVC architecture:
public class MyProgram extends JFrame {
      ... somewhere in your class
      Square s=new Square();
      Square_View sv=new Square_View();
      s.addObserver(sv);
}

As I said before, you create both model and view and register the view as observer for your model.


text:
Q: Problems with using Thread.Sleep for short times I have an app with 2 threads (now), but it seems that function Thread.Sleep() doesn't work very good. It sleeps threads but it takes much more time (for example- I want to sleep it for 5ms and it sleeps for 0,3s or more). Here is code:
int vlakien = 2;
Thread[] vlakna;
vlakna = new Thread[vlakien];

for (int i = 0; i < vlakien; i++)
{ try { vlakna[i] = new Thread(new ThreadStart(utok)); vlakna[i].Start(); } }

private void utok()
{
  //some code
  Thread.Sleep(5);
  //some code
}

Also I tried to sleep it with Stopwatch in the function utok and it also takes more time:
Stopwatch SW = new Stopwatch(); SW.Start();
while(SW.ElapsedMilliseconds < 5000) ;

Please help.

A: 15ms is the thread time slice on windows ( you can actually mess with windows and change that.... not at all recommended).  Things can give their time slices up early, but anything could take their full time slice.
So its really hard to get any better than that, in fact, realistically 20 or 30 ms is more likely.    I used to do real time processing which had a hard real time limit of 50ms.   That worked well on windows if you obeyed certain rules ( it was in C++)

A: As others have indicated, the default resolution of Sleep is 10 or 15 milliseconds, depending on the edition of Windows.
However, you can reprogram the timer to use a 1 millisecond resolution by issuing a
timeBeginPeriod(1);
timeEndPeriod(1);

where
[DllImport(WINMM)]
internal static extern uint timeBeginPeriod(uint period);

We do this in our serial communications services where being able to accurately space out sends in time is important. Some people are reluctant to do this because it causes Windows to do other things that are based off of the timer more frequently as well. In reality this has caused no discernible issues for us, and we have hundreds of installs each with hundreds of serial devices connected.

A: Sleep in Microsoft C# guarantees a minimum amount of time. It sleeping less than 5 milliseconds is definitely a problem. Also Stopwatch may not be very precise measurement, try the high precision media timers.

A: It is affected by resolution of the system clock. It is around 15ms...you cannot go below resolution of the system clock. Take a look at this link (it is C++ but you will get idea about timer resolutions).

A: The parameter passed into Thread.Sleep is a minimum time to sleep, not an exact time.

A: This is a Platform Dependent Wait you can use in any project that works by suspending the Thread for the amount of time you specify with the lowest possible resolution that can be achieved by your system, which will likely be 1ms
It won't use more CPU than a normal Thread.Sleep
/*
*MIT License
*
*Copyright (c) 2023 S Christison
*
*Permission is hereby granted, free of charge, to any person obtaining a copy
*of this software and associated documentation files (the "Software"), to deal
*in the Software without restriction, including without limitation the rights
*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*copies of the Software, and to permit persons to whom the Software is
*furnished to do so, subject to the following conditions:
*
*The above copyright notice and this permission notice shall be included in all
*copies or substantial portions of the Software.
*
*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*SOFTWARE.
*/

using System.Runtime.InteropServices;

namespace System.Threading
{
    ///
    /// Platform Dependent Wait
    /// Accurately wait down to 1ms if your platform will allow it
    /// Wont murder your CPU
    public static class Delay
    {
        internal const string windowsMultimediaAPIString = "winmm.dll";

        [DllImport(windowsMultimediaAPIString)]
        internal static extern int timeBeginPeriod(int period);

        [DllImport(windowsMultimediaAPIString)]
        internal static extern int timeEndPeriod(int period);

        [DllImport(windowsMultimediaAPIString)]
        internal static extern int timeGetDevCaps(ref TimerCapabilities caps, int sizeOfTimerCaps);

        internal static TimerCapabilities Capabilities;

        static Delay()
        {
            timeGetDevCaps(ref Capabilities, Marshal.SizeOf(Capabilities));
        }

        ///
        /// Platform Dependent Wait
        /// Accurately wait down to 1ms if your platform will allow it
        /// Wont murder your CPU
        ///
        /// <param name="delayMs"></param>
        public static void Wait(int delayMs)
        {
            timeBeginPeriod(Capabilities.PeriodMinimum);
            Thread.Sleep(delayMs);
            timeEndPeriod(Capabilities.PeriodMinimum);
        }

        ///
        /// The Min/Max supported period for the Mutlimedia Timer in milliseconds
        ///
        [StructLayout(LayoutKind.Sequential)]
        public struct TimerCapabilities
        {
            /// Minimum supported period in milliseconds.
            public int PeriodMinimum;

            /// Maximum supported period in milliseconds.
            public int PeriodMaximum;
        }
    }
}

This will work with any version of .NET and if your platform doesn't support this then it is the same as a normal Thread.Sleep


text:
Q: Get SCNGeometry from Model I/O I am trying to import a Mesh into a SCNGeometry. I do want to manipulate the vertices individually from the CPU. Therefore, I want to do it according to the following post: https://developer.apple.com/forums/thread/91618 .
So far I have imported it into the Model I/O Framework and created a MTLBuffer.
    let MDLPositionData = mesh?.vertexAttributeData(forAttributeNamed: "position", as: .float3)

    let vertexBuffer1 = device.makeBuffer(bytes: MDLPositionData!.dataStart,
                                          length: MDLPositionData!.bufferSize,
                                          options: [.cpuCacheModeWriteCombined])
    let vertexSource = SCNGeometrySource(
           buffer: vertexBuffer1!,
           vertexFormat: vertexFormat,
           semantic: SCNGeometrySource.Semantic.vertex,
           vertexCount: mesh!.vertexCount,
           dataOffset: 0,
           dataStride: MemoryLayout<vector_float3>.size)

The SCNGeometry needs index elements to properly show the mesh. Where do I get those?
I have tried to use the submeshes from Model I/O:
    let submesh = mesh?.submeshes?[0]
    let indexBuffer = (submesh as? MDLSubmesh)?.indexBuffer(asIndexType: .uInt32)
    let indexBufferData = Data(bytes: indexBuffer!.map().bytes, count: indexBuffer!.length)
    let indexElement = SCNGeometryElement(
        data: indexBufferData,
        primitiveType: SCNGeometryPrimitiveType.triangles,
        primitiveCount: indexBuffer!.length,
        bytesPerIndex: 32)
    let geo = SCNGeometry(sources: [vertexSource, normalSource], elements: [indexElement])

But this trows the error
[SceneKit] Error: C3DMeshElementSetPrimitives invalid index buffer size and shows the following geometry: The Teapot. It seems like the vertices aren't connected properly.
How do I get the correct Index data? Thank you!


text:
Q: How to retrieve an SKDownload of an already purchased content The standard in app purchase flow when there is hosted content is:

*do the transaction

*when the transaction enters in "purchased" state, retrieve the SKDownload and start downloading

*when downloading is done, then we can declare the transaction as "finished"

This is fine.
Imagine we want to restore all purchased contents, this is because we delete and re-installed our app or simply because we installed it in another device. Now, and this is confirmed by WWDC 2012 session on the subject, when you restore all purchases you will get the full list of contents to restore but probably you don't want to download all of them. In such case you should offer the user the choice of which content to download and then queue the SKDownload of the chosen product; once the the download terminates and the content is successfully installed, you can declare the transaction finished.
What the session video didn't say instead is what you should do with the rejected or delayed downloads. As far as I know there is no way to save the SKDownload somewhere and retrieve it later and there is no API to ask iTunes a thing like this "give me the SKDownload of this already purchased product".
So according to me there are two options to walk-around this case:

*
you will ask to restore the non-purchased stuff again; this is not elegant but it works

*
you start the procedure and then you pause it; this will be resumed later. But this solution has several drawbacks: you have no control of how the system manages the SKDownload and it could cancel if after a certain amount of time. I never tried this solution.

Did someone else faced this issue and found a better solution? does it make sense to open an enhancement request with Apple?

A: I always do it is as you suggested, and just "rebuy" the purchased items so it goes through the normal purchase flow.  You can't mark the transaction as finished until your done with the download.  So if you pause it and the app dies when your app is launched again the queue will go off and try to finish the purchase which would start your download logic again.  That seems more annoying as a user constantly having this thing popup when I open the app to finish the purchase.
The SKDownload docs say;

Your app never directly creates a SKDownload object. Instead, after a payment is processed, your app reads the transaction object's downloads property to retrieve an array of SKDownload objects associated with the transaction.


text:
Q: Java8 Stream: using if/else condition inside a stream I've been using the Java 8 Streams for a while. I came across a situation where I need to use if/else condition while iterating a stream. I have a list like this. I want to create an object of MetricForAccount class for each item of the list
private List<String> metricNames = ImmutableList.of("ReadConsumedCapacity",
            "WriteConsumedCapacity", "SuccessfulRequestLatency", "ReturnedItemCount");

List<Dimension> dimensions = new ArrayList<>();

metricNames.stream()
                .map(metricName -> new MetricForAccount().withAccountId(subscriberId)
                        .withMetricName(metricName)
                        .withStat(SUM)
                        .withPeriod(PERIOD)
                        .withNamespace(AWS_DYNAMO_DB_NAMESPACE)
                        .withRegion(region)
                        .withDimensions(dimensions)
                        .withRange(range))
                .collect(Collectors.toList());

I want add different item to the dimensions list based on the metric name. I am not sure how can I use if else inside the map. Any suggestion?

A: You can simply extend the callback and use and if/else statement inside this callback.
Like this:
List<Dimension> dimensions = new ArrayList<>();

metricNames.stream()
    .map(metricName - > {
        if (matches(metricName)) return new MetricForAccount().withAccountId(subscriberId)
            .withMetricName(metricName)
            .withStat(SUM)
            .withPeriod(PERIOD)
            .withNamespace(AWS_DYNAMO_DB_NAMESPACE)
            .withRegion(region)
            .withDimensions(dimensions)
            .withRange(range);
        else return new MetricForAccount().withAccountId(subscriberId)
            .withMetricName(metricName)
            .withStat(SUM)
            .withPeriod(PERIOD)
            .withNamespace(AWS_DYNAMO_DB_NAMESPACE)
            .withRegion(region)
            .withDimensions(otherDimensions)
            .withRange(range);
    })
    .collect(Collectors.toList());


text:
Q: Bootstrap site is printing links When I try to physically print a page from my bootstrap site it prints the relevant links too. I've never seen this behavior before. I looked it up online but can't seem to find a working solution.
For example I have a link:
Link to another page
(example.php)

I'm really not sure what to do and it's quite annoying. Any help would be great.

A: Bootstrap comes with many default styles (obviously), one of them being the ability to print the URL next to links. In the Bootstrap CSS file you'll find:
@media print {
...
    a[href]:after {
        content: " (" attr(href) ")"
    }
...
}

This takes the URL and appends it to the link within parenthesis. One easy way to kill this behavior is to override Bootstrap's rule with your own (loaded after the Bootstrap CSS) and for content use content:none:
a[href]:after {
    content: none;
}

A: To not have the links printed, use CSS:
a:link:after, a:visited:after{
    content: "";
}


text:
Q: Cross-Reference with custom text Is there a way to make a cross reference to a label of a header with custom text? That is, its text should differ from the Header text, or its number or page (not like the predefined formats in Lyx). Something like the the hyperlinks or bookmarks in MS word, and in such a way that I can write the different text for each cross-reference individually. I'm not looking to define a new format for the references.
For example, if the header text is "State and Path functions", I want to make a cross reference to it with the text "state function".

A: With the package hyperref you can use the optional argument of \hyperref to reference a \label with arbitrary text:
\documentclass{article}
\usepackage{hyperref}
\begin{document}
\section{Hello World}
\label{sec:hello}
Reference to \hyperref[sec:hello]{this section}.
\end{document}

A: In LaTeX Beamer the hyperref usage gave me problems so I solved it using hyperlink.
To create a link to a label with a custom text for the clickable link, you can use the \hyperref package and the \hyperlink command. Here's an example:
\usepackage{hyperref}

...

\hyperlink{labelname}{clickable link text}

This will create a clickable link with the text "clickable link text" that will take the reader to the location of the label with the name "labelname".

Here is a full example with Beamer:
\documentclass{beamer}
\mode<presentation> {\usetheme{CambridgeUS}}
\usepackage{hyperref}

\begin{document}
    \begin{frame}
        \begin{figure}[!htbp]
            \centering
            \includegraphics[width=0.2\linewidth]{myimage.png}
            \caption{My Image}
            \label{fig:myimage}
        \end{figure}
    \end{frame}

    \begin{frame}
        Example 1: Reference to \hyperlink{fig:myimage}{clickable link text}.\\~\\
        Example 2: Reference to \hyperlink{fig:myimage}{clickable link text at pag \pageref{fig:myimage}}.
    \end{frame}
\end{document}

And this is the visual result:


text:
Q: Why does this code work? I thought if statements weren't supposed to contain assignment operators but rather the comparison operators (==, ===) but this works perfectly. Why?
var foo = true,
    bar = true;
if (foo = true) {
    console.log('foo is true');
}

I was taught that this wouldn't work but I just found out that it does.

A: What you're actually doing, is still comparing:
if ((foo = true) == true) ...

This is an 'abbreviation' for:
foo = true;
if (foo == true) ...

So it does make sense =)!

A: From the ES5.1 specification (12.5)
IfStatement :
    if ( Expression ) Statement  else Statement
    if ( Expression ) Statement

Any valid expression can be placed inside an if.
foo = true is an expression and it evaluates to true.
To avoid bugs like writing = instead of == in the future write it like
if (true = foo) {

}

Which will throw a assignment error since you can't assign values to literal values like true

A: The assignment is evaluated to true, beacuse JavaScript returns the value that it sets the variable to.
var foo = true,
    bar = true;
if (foo = true) {
    console.log('foo is true');
}

becomes:
var foo = true,
    bar = true;
if (true) {
    console.log('foo is true');
}

which passes the if. Note that setting to false would not work, because the conditional would evaluate to false which does not pass the if.
Specification about if:

if ( Expression ) Statement

You are using the assignment expression:

AssignmentExpression :
  ConditionalExpression LeftHandSideExpression AssignmentOperator AssignmentExpression

The = is specified as:

Simple Assignment ( = )
The production AssignmentExpression : LeftHandSideExpression = AssignmentExpression is evaluated as follows:
...
2 . Let rref be the result of evaluating AssignmentExpression.
3 . Let rval be GetValue(rref).
...
6. Return rval.

A: Tragically, you are in fact assigning foo to true. :)


text:
Q: How can I allow other users to deploy to my Azure cloud services? I created an empty Azure cloud service and I want to allow other developers to deploy to it.  So far the only route I can see is adding the developers as Azure subscription administrators.  I would rather give them more specific access to the cloud services only.

A: No such functionality exist today which will allow you to grant/revoke permissions at the cloud service level. Once a developer is provided access to the subscription, they would have access to all the resources under that subscription.
There's a REST API behind cloud service deployments and all the tools (including Windows Azure Portal and Visual Studio) consume this API for creating deployments. One possible solution would be to build your own solution consuming this API. In this solution you will implement access control based on your requirements so that when your user use this service, they will only see the cloud service they're assigned to and can only manage that cloud service. There's a managed library for consuming this API. You can find more information here: http://www.bradygaster.com/post/getting-started-with-the-windows-azure-management-libraries.

A: It seems that if the original developer downloads the publish profile from Azure (it's an xml file that with a .PublishSettings extension), you can copy the userPWD from that file, give it to another developer and they can paste it into the password field in the Connection section of the Publish dialog.
The userPWD is a string that looks something like this:
EFFCLfDqDKHlXcA2YDZPvX4BZXWFaobxaLN0aPJd4HCfa8WxlqEkt2yywBsx


text:
Q: jQuery Float Number I have problem with following calculation:
$result = $a + $b + ($c * $d - $e) * $f + $g;

The formula may more complicated.  I found some variables are treated as String instead of Number, therefore the result is wrong.
For the following code:
$result = parseFloat($a) + parseFloat($b) + (parseFloat($c) * parseFloat($d) - parseFloat($e)) * parseFloat($f) + parseFloat($g);

It seems right.  However, is there any good way to do it, instead of write parseFloat() function for each of the variable?

A: Try to use +
http://jsfiddle.net/2yrMc/
var $b = "0.785";

alert(typeof +$b);


text:
Q: Twig loop in array stucked How to loop in array like this in twig.
var_dump($array) , array was formed by fetchAll() (PDO)
array (size=3)
            0 =>
    array (size=4)
      'comment' => string 'Labas' (length=5)
      0 => string 'Labas' (length=5)
      'user_name' => string 'Qler' (length=4)
      1 => string 'Qler' (length=4)
  1 =>
    array (size=4)
      'comment' => string 'asdg' (length=4)
      0 => string 'asdg' (length=4)
      'user_name' => string 'Qler' (length=4)
      1 => string 'Qler' (length=4)
  2 =>
    array (size=4)
      'comment' => string 'adf' (length=3)
      0 => string 'adf' (length=3)
      'user_name' => string 'Qler' (length=4)
      1 => string 'Qler' (length=4)

I like to have something like this to display comment: username;
Also accept advices for simplify this array in PHP (i am using PDO).

A: http://twig.sensiolabs.org/doc/tags/for.html
Downvoted for doing no research on your own.
Quote:
Loop over each item in a sequence. For example, to display a list of users provided in a variable called users:

Members

    {% for user in users %}

{{ user.username|e }}

    {% endfor %}

You should also switch to either using only associative or only indexed fetch mode.
http://www.php.net/manual/en/pdostatement.setfetchmode.php


text:
Q: How to read data from META/MANIFEST.MF in Spring Boot MVC Web Application? I have a requirement to read information that is available in the META/MANIFEST.MF file of Spring Boot MVC web application and use this info to perform some business logic. I'm using gradle to build the application as war file and deploying it into the external tomcat.
I have tried the following:
@Configuration
public class AppConfig
{
    @Bean("manifest")
    public java.util.jar.Manifest getManifest() throws IOException
    {
        InputStream inputFile = this.getClass().getClassLoader().getResourceAsStream("META-INF/MANIFEST.MF");
        Manifest manifestObj = new Manifest(inputFile);
        return manifestObj;
    }
}

AppService.java
@Service
public class AppService
{
    @Autowired
    @Qualifier("manifest")
    private Manifest manifest;

    @PostConstruct
    public String init()
    {
        Attributes mainAttributes = manifest.getMainAttributes();
        String buildNum = mainAttributes.getValue("Build-Number");
        String customPropInfo= mainAttributes.getValue("customPropInfo");
        String systemPrp1= buildNum + "_" + "SomeBusinessInfoLogic1";
        String systemPrp2= customPropInfo+ "_" + "SomeBusinessInfoLogic2";
        //Some Business Logic with these attributes systemPrp, systemPrp2
        logger.info("System Props are updated");
    }
}

I'm getting null for both buildNum and customPropInfo.
Note: I have tried creating the Manifest bean something like this which was created by me. As per the @M.Deinum suggestion I'm creating this new question here. I also tried the solutions here which didn't work for me.
@M.Deinum suggested to make use of Spring Boot's Actuator Info endpoint. But this endpoint is useful when we want to access the info outside of the application but my requirement is different as I need the data that is available in MANIFEST.MF file to perform some business operations within the application.
I get the following error when I tried this solution "/META-INF/MANIFEST.MF".
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'manifest' defined in class path resource [com/abc/AppConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.util.jar.Manifest]: Factory method 'getManifest' threw exception; nested exception is java.lang.NullPointerException: Cannot invoke "java.io.InputStream.read(byte[], int, int)" because "this.in" is null

Can someone please help me to read information from META/MANIFEST.MF of the Spring Boot MVC Web Application?.
UPDATE1: I get the following MainAttributes when I try to print MainAttributes. But the problem is when I try to deploy the war into external tomcat.
System.out.println("Manifest MainAttributes = " +manifestObj.getMainAttributes().keySet());

Output:
Manifest MainAttributes = [Manifest-Version, Implementation-Title, Automatic-Module-Name, Implementation-Version, Built-By, Spring-Boot-Jar-Type, Build-Jdk-Spec]

UPDATE2:
I have updated to AppService.java to print the info available in autowired Manifest object. Something like below:
@Configuration
public class AppConfig
{
    @Bean("manifest")
    public java.util.jar.Manifest getManifest() throws IOException
    {
        InputStream inputFile = new ClassPathResource("/META-INF/MANIFEST.MF").getInputStream();
        Manifest manifestObj = new Manifest(inputFile);
        System.out.println("Manifest Manifest-Version = " +manifestObj.getMainAttributes().getValue("Manifest-Version"));
        System.out.println("Manifest KeySet = " +manifestObj.getMainAttributes().keySet());
        return manifestObj;
    }
}
@Service
public class AppService
{
    @Autowired
    @Qualifier("manifest")
    private Manifest manifest;

    @PostConstruct
    public String init()
    {
        Attributes mainAttributes = manifest.getMainAttributes();
        mainAttributes.forEach((k,v) -> {
            System.out.println("AppService.init(): Key = "+k+", Value = "+v);
        });
        String buildNum = mainAttributes.getValue("Build-Number");
        String customPropInfo= mainAttributes.getValue("customPropInfo");
        String systemPrp1= buildNum + "_" + "SomeBusinessInfoLogic1";
        String systemPrp2= customPropInfo+ "_" + "SomeBusinessInfoLogic2";
        //Some Business Logic with these attributes systemPrp, systemPrp2
        logger.info("System Props are updated");
    }
}

I see the following output on the console:
AppService.init(): Key = Implementation-Title, Value = Apache Tomcat Bootstrap
AppService.init(): Key = Implementation-Version, Value = 9.0.12
AppService.init(): Key = Specification-Vendor, Value = Apache Software Foundation
AppService.init(): Key = Specification-Title, Value = Apache Tomcat Bootstrap
AppService.init(): Key = Class-Path, Value = commons-daemon.jar
AppService.init(): Key = Manifest-Version, Value = 1.0
AppService.init(): Key = Main-Class, Value = org.apache.catalina.startup.Bootstrap
AppService.init(): Key = Implementation-Vendor, Value = Apache Software Foundation
AppService.init(): Key = Ant-Version, Value = Apache Ant 1.9.9
AppService.init(): Key = X-Compile-Target-JDK, Value = 1.8
AppService.init(): Key = X-Compile-Source-JDK, Value = 1.8
AppService.init(): Key = Created-By, Value = some xyz
AppService.init(): Key = Specification-Version, Value = 9.0

So just by the above output, I think MANIFEST.MF is not application specific but is from commons-daemon.jar.

A: OK - the problem isn't that you "can't read data from META/MANIFEST.MF in Spring Boot MVC Web Application".  Rather, the problem is that your code happens to be reading the WRONG MANIFEST.MF from some other, random .jar in the classpath.
One solution might be to use JarClassLoader.
Another solution, as M. Deinum suggested, might be to store the properties you wish to retrieve in application.properties (or some other "global" properties file) instead of MANIFEST.MF.
ALSO:
I assume you're probably using an IDE to develop your app (Eclipse, Netbeans, etc).  If you haven't already, I would STRONGLY encourage you to familiarize yourself with your IDE's debugger: the ability to set breakpoints, display variables, single-step through method calls, etc.


text:
Q: Can't open/create .db file with SQLite in Visual Studio (UWP, C++) I have created a blank universal app in Visual Studio 2015 and added just a button to the MainPage. Then, I created the click event handler for the button: myButton_Click(...). There I have the following code:
void MyTestApp::MainPage::myButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    sqlite3 *testDB;
    int result = sqlite3_open("file:///C:/Users/MyName/Downloads/testDB.db", &testDB);
    myButton->Content = result.ToString();
}

As you can see I just try to create a new db file and the result of the sqlite3_open() function is displayed on the button. Unfortunately, I always get Code 14: SQLITE_CANTOPEN.
In Visual Studio I have installed "SQLite for Universal Windows Platform" via Tools -> Extensions and Updates. Under the solutions explorer I added the SQLite for UWP to the References and also included the <sqlite3.h> header.
Do I have to assign any special permissions to the app so that it can create files or what am I doing wrong?

A: UWP apps can't read outside of their own private locations by default - see file access for UWP in MSDN.
You can access locations outside of your private storage area using the StorageFile APIs, but they won't work for SQLite which expects a filename. There is currently no way to do this other than to copy the database to your local storage area first.

A: With Peter Torr's comments it finally worked:
void MyTestApp::MainPage::myButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    Windows::Storage::StorageFolder^ f = Windows::Storage::ApplicationData::Current->LocalFolder;

    sqlite3 *testDB;
    int result = sqlite3_open_v2("C:/Users/MyName/AppData/Local/Packages/538ec661-2ebf-4c45-8845-3a4cb6afd397_4jdacjwc0e74a/LocalState/testDB.db", &testDB, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);

    //This works too:
    //int result = sqlite3_open_v2("C:\\Users\\MyName\\AppData\\Local\\Packages\\538ec661-2ebf-4c45-8845-3a4cb6afd397_4jdacjwc0e74a\\LocalState\\testDB.db", &testDB, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, NULL);

    myButton->Content = result.ToString();
    //myButton->Content = f->Path;

    sqlite3_close(testDB);
}

The testDB.db is now available at the directory you see in the code. I've tried a similar code before, but it did not work. It seems the flags SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE made the difference...


text:
Q: Writing a custom aggregate function Lately I've been practicing and studying PL/pgSQL. I'm stuck on creating a custom aggregate function.
The code below works just fine, but I'm not able to write an aggregate function of this type:
SELECT my_aggregate_function(column) from table;

Here is the code of the "partially working custom aggregate":
CREATE OR REPLACE FUNCTION searchMinValue (numeric[]) RETURNS numeric   AS $$
  DECLARE
     i numeric;
     minVal numeric;
  BEGIN
    minVal := $1[1];
    IF ARRAY_LENGTH($1,1) > 0 THEN --Checking whether the array is empty or not
  <<confrontoMinimo>>
   FOREACH i IN ARRAY $1 LOOP --Looping through the entire array, passed as parameter
       IF minVal >= i THEN
           minVal := i;
       END IF;
   END LOOP confrontoMinimo;
   ELSE
    RAISE NOTICE 'Invalid parameter % passed to the aggregate function',$1;
   --Raising exception if the parameter passed as argument points to null.
   RAISE EXCEPTION 'Cannot find Max value. Parameter % is null', $1
   USING HINT = 'You cannot pass a null array! Check the passed parameter';
END IF;
RETURN minVal;
END;
$$ LANGUAGE plpgsql;

CREATE AGGREGATE searchMinValueArray (numeric)
(
sfunc = array_append,
stype = numeric[],
finalfunc = searchMinValue,
initCond = '{}'
);

 with w(v) as (select 5 union all select 2 union all select 3)
 select min(v) "Normal Aggregate", searchMinValueArray(v) "My Customed Aggregate" from w;

As I said before, I'd like to call my custom aggregate function in this way:
SELECT my_aggregate_function(column) from table;

where the table is Customers and the column is salary of type numeric.

A: You are fundamentally doing the right thing, but there are still some problems with your implementation:

*

*Your aggregate will error out if the table is empty. Rather, it should return NULL.

*If the first value you are aggregating is NULL, your aggregate will do the wrong thing. if
minVal := $1[1];

sets minVal to NULL, then all future comparisons minVal >= i will not be TRUE, and the end result will be NULL, which is not what you want.

*You collect all values in an array, which will become quite big if you aggregate many rows. First this puts you in danger of running out of memory with the array, and then the performance of the aggregate will not be as good as it could be.
It is much better to perform the comparison in SFUNC: start with INITCOND = NULL, use STYPE = numeric and perform the aggregation whenever a you process a new value. The relevant part of SFUNC would look like this:
IF $1 IS NULL OR $1 > $2
    RETURN $2;
ELSE
    RETURN $1;
END IF;

That way you don't need a FINALFUNC at all.


text:
Q: Do we need to install SQL Server 2008 SP2 after installing SQL Server 2008 R2 RTM? I have installed SQL Server 2008 R2 RTM (Express) with Management Studio. But I am confused, do I need to install SQL Server 2008 (Express) Service Pack 2?
Is there SQL Server 2008 R2 Service Pack 2?

A: The answer is no. If you just installed it, you it probably came with SP1 included: http://www.microsoft.com/download/en/details.aspx?id=12847
Service Pack 2 is only for SQL Server 2008, not R2.
If you don't already have it, you should be able to get it with your Microsoft Updates automatically.


text:
Q: How can I convert the values is an NSDictionary into an NSString? I have a method in Objective-c that takes in an NSDictionary and returns the values as a space-separated NSString. This application is cross-platform, and as such I cannot use fast enumeration. This is what I have so far, followed by the output (which shows that the String is never created):
-(NSString *)stringValuesFromDict:(NSDictionary *map)
{
    NSArray *values = [map allValues];
    NSString *params = [NSString string];
    NSLog(@"values length: %d", [values count]);
    NSLog(@"values = %@", [values description]);
    for (int i = 0; i < [values count]; i++)
    {
        [params stringByAppendingString:[values objectAtIndex:i]];
        [params stringByAppendingString:@" "];
    }
    NSLog(@"params = %@", params);
    return params;
}

The NSDictionary:
{"arg1"="monkey"}

The output:
values length: 1
values = (
    monkey
)
params =

What am I doing wrong? How can I get params to be set to monkey?

A: If I read the question correctly, all you need is
[[dict allValues] componentsJoinedByString:@" "]

A: You need a mutable string. Change this:
NSString *params = [NSString string];

to this:
NSMutableString *params = [NSMutableString string];

Then change these:
[params stringByAppendingString:[values objectAtIndex:i]];
[params stringByAppendingString:@" "];

to these:
[params appendString:[values objectAtIndex:i]];
[params appendString:@" "];

A: stringByAppendingString: returns a new string. So you would have to do something like this:
params = [params stringByAppendingString:[values objectAtIndex:i]];

But the disadvantage is, that every time a new string is created, which is wasting memory
You should propably use a NSMutableString instead. And then you can just call
[params appendString:[values objectAtIndex:i]];


text:
Q: How do I create/edit a user profile for a Stream react-native app? Is there a builtin UI component in the Stream for react-native library to edit a user's profile?
I have the feeds and activities working and integrated with my user id and token server side api, but users obviously show up as the default "Unknown" with no photo. I don't have profile storage yet in this new application so I'm wondering if there is a quick drop-in for a Profile screen and editing of that profile or if I have to build that and add the metadata to the stream User API.

A: There is no profile component, but you can access the information and create your own.
Firstly, set the profileImage field of the user in getstream like so (example shown server side but you can use do client side with a token):
const client = stream.connect('xxx', 'xxxxxxxxxxxxxx', 'xxxxxx');
let clientData = await client.user(userId).get();

if (!clientData.data) return null;

clientData.data.profileImage = 'https://cdn.com/profile.png';
await client.user(context.params.userId).update(clientData.data);

Then you can access it like so on client: (example shows feed with a custom header.):
const CustomActivity = (props) => {
    return  <Activity {...props}
    Header={
      <View style={styles.avatarView}>
            <Avatar
              source={props.activity.actor.data.profileImage}
              size={36}
              noShadow
            />
            <View style={styles.actorView}>
              <Text style={styles.actorName}>{props.activity.actor.data.name}</Text>
              <Text style={styles.metaData}>{formatRelative(new Date(props.activity.time), new Date())}</Text>
            </View>
      </View>
    }>
      </Activity>

        <StreamApp apiKey={STREAM_API_KEY} appId={STREAM_APP_ID} token={user.activity.token}>
          <FlatFeed feedGroup="timeline" notify  Activity={CustomActivity} />
        </StreamApp>


text:
Q: Apache httpd - adding new server alias with a new alias path <VirtualHost :80>
    DocumentRoot "/study/data"
    ServerName example.com
    ServerAlias www.example.com
    <Directory "/study/data">
        Options Includes FollowSymLinks
        AllowOverride All Options FileInfo
        Order allow,deny
        Allow from all
    </Directory>

        Alias /science-rsch /study/data/www/science
        <Directory /study/data/www/science>
            Options Includes FollowSymLinks
            AllowOverride All
            Order allow,deny
            Allow from all

            RewriteEngine on
            RewriteBase /science-rsch/
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_URI} !=/favicon.ico
        RewriteRule ^ index.php [L]
        </Directory>

        <Directory /study/data/www/science/sites/default/files>
            AllowOverride None
            Order allow,deny
            Allow from all
        </Directory>
</VirtualHost>

Above works for www.example.com with the alias /science-rsch:
www.example.com/science-rsch -> /study/data/www/science
How to make the above virtual host ***also* work for a new ServerAlias(www.newdomain.com) with the Alias /content/science-rsch**:
www.newdomain.com/content/science-rsch -> /study/data/www/science


text:
Q: VBA : How to set the value to a textarea in an object type of internetexplorer.application I've been trying to write some text into a textarea element of an aspnet form using the object internetexplorer.application in a macro using VBA
When I add a watch to the object after setting the "Value" attribute, i get the text that i am setting (using a MsgBox), but the browser doesnot seem to get the text when i submit it.
Im using IE 8.0.6001  and Office 2003.
Any help / comment will be very much appreciated.
Thanks
Sub Test2()

Dim Title As String
Dim Comments As String

Set wb = CreateObject("internetexplorer.application")
wb.navigate2 "http://tudrintra01/ads/Lists/Tasks1/NewForm.aspx?RootFolder=%2Fads%2FLists%2FTasks1&ContentTypeId=0x01030062FE73EDFA7DA644A27CE244EA983DA4&Source=http%3A%2F%2Ftudrintra01%2Fads%2FLists%2FTasks1%2FMyItems%2Easpx"

wb.Visible = True

 Title = "TITULO PRUEBA"
 Comments = COMENTARIO PRUEBA" '"Comentario"

Do Until wb.readyState = 4 ' wait for page to load
 DoEvents
 Loop

    'Si el objeto es el Titulo del task
    wb.Document.getElementByID("ctl00_m_g_c0644918_3730_4e2c_8434_7b760939e3d4_ctl00_ctl04_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").Value = Title

    'Si el objeto es el Comment
    wb.Document.getElementByID("ctl00_m_g_c0644918_3730_4e2c_8434_7b760939e3d4_ctl00_ctl04_ctl14_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").Value = Comments

    ' Clean up
    Set wb = Nothing

End Sub

A: You have not got an answer for days, so I comment on your question now. I successfully automated IE via the WebBrowser object, not via an Internetexplorer.Application object. Webbrowser will not open an IE application instance but just a "document window" in a Webbrowser control in a form in your Access application. So if you don't use Access or for some other reason this might not be a valuable hint for you.
This is not an answer to your question, that's why I waited some time to give my comment, but it's my best comment and I did everything possible with the DOM model through a wb object and never experienced a problem like yours that I could not solve. So you might want to try and rewrite your sub to using a Webbrowser.


text:
Q: Limit to HtmlPage.Window.Eval() I was wondering if there was a limit to HtmlPage.Window.Eval().
I am currently defining a url to create a mailto link, the content is auto generated by the silverlight application and then passed over for the user. However, when I call HtmlPage.Window.Eval("location.href='mailto:?Subject=my%20Application%20-%20Spot%2FOutright%20deal&body=Please%20find%20attached%20the%20following%20trade%20details...';");
The email is fairly large, however it is below the limit for the mailto uri. I was wondering if there was a limit to the size of the Eval method which may be causing me an issue, if I pass through a reduced message I am not getting any problems.
Is there an alternative way of doing this? I have tried HtmlPage.Window.Navigate, however this always opens a new window, even if I specify to use self.

A: You want to make sure you are encoding the text, I use:
string email = "mailto:" + "?subject=" + HttpUtility.HtmlEncode(subject) + "&body=" + HttpUtility.HtmlEncode(body);
HtmlPage.Window.Navigate(new Uri(email));

I think the character limit on a url is 2048.

A: Thanks Rob,
I have been running my url through encoding before sending it through to the function. From what I have read it appears that the mailto link when used in InternetExplorer struggles with a characterset exceeding around 512 characters. Whilst it is possible to extend this with settings I don't have the access to do this currently.
I ended up using the following script:
HtmlPage.Window.Eval("OpenEmailLink(" + uri + ")");

function OpenEmailLink(uri) {

        var win = window.open(uri, '_blank', 'scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no,width=0,height=0,left=-1000,top=-1000');
        if (win && win.open && !win.closed) win.close();
    }

There were some issues with the win object being null (this was due to the application treating it as a cross domain item and therefore not returning an object for me to then close. As such I have had to use a popup to launch the email client, it is far from the solution I had hoped for but limitations meant that I had to make do for the time being.


text:
Q: Kotlin - Retrofit request using RxJava gives null response I'm trying to get news from Guardian API. I'm getting null response, everything is below. I'm using Kotlin, Retrofit and RxJava. I know that there are some miscalled variables/objects but I will change them when I will get rid of that problem.
Retrofit interface
@get:GET("search?api-key=test")
    val news:Observable<News>

Retrofit client
val instance : Retrofit
    get() {
        if (myInstance == null) {
            myInstance = Retrofit.Builder()
                    .baseUrl("https://content.guardianapis.com/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build()
        }
        return myInstance!!
    }

And function where I'm loading data
private fun loadUrlData() {
        compositeDisposable.add(jsonApi.news
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe{news -> displayData(news)})
    }

JSON example
{
   response:{
      status:"ok",
      userTier:"developer",
      total:2063064,
      startIndex:1,
      pageSize:10,
      currentPage:1,
      pages:206307,
      orderBy:"newest",
      results:[
         {
            id:"politics/2018/sep/24/keir-starmer-labour-does-not-rule-out-remaining-in-eu",
            type:"article",
            sectionId:"politics",
            sectionName:"Politics",
            webPublicationDate:"2018-09-24T18:57:48Z",
            webTitle:"Keir Starmer: Labour does not rule out remaining in EU as option",
            webUrl:"https://www.theguardian.com/politics/2018/sep/24/keir-starmer-labour-does-not-rule-out-remaining-in-eu",
            apiUrl:"https://content.guardianapis.com/politics/2018/sep/24/keir-starmer-labour-does-not-rule-out-remaining-in-eu",
            isHosted:false,
            pillarId:"pillar/news",
            pillarName:"News"
         }
      ]
   }
}

Model class
data class News( val status: String, val userTier: String, val total: Int, val startIndex: Int, val pageSize: Int, val currentPage: Int, val pages: Int, val orderBy: String, val results: List<Result>)

I suppose that the problem is with the last function or with the interface but I can't find the solution.

A: The issues lies within your data model class.
Your JSON has an outer node (response) and if you're trying to return a News you won't get it, because Retrofit can't map the JSON to the News class. Add an outer class called Response that holds a field called response that is of type News, that should fix it.
Like so:
class Response(val response: News)

Note: I haven't added data in front of the class as you don't necessarily need it. The data keyword just adds some extra things for you automatically, like toString(), equals() and hashCode(), but unless you're actually using them for anything I wouldn't recommend adding the data keyword as it's pretty useless then.


text:
Q: Why are my data model values undefined after data is stoed in Angular? I'm building a notes app, fetching data from a local api that I made.
Thing is, when I load data into my NoteModel in my component, values under the second "level" of models are undefined.
The data comes as a JSON obviously, that I want to save into my Model:

[
    {
        "id": 1,
        "note": [
            {
                "id": 1,
                "title": "Test1",
                "description": "Testing testing",
                "completed": false
            },
            {
                "id": 2,
                "title": "Test2",
                "description": "Testing testing",
                "completed": false
            },
            {
                "id": 3,
                "title": "Test3",
                "description": "Testing testing",
                "completed": false
            }
        ]
    }
]

This is my NoteModel

import { NoteContent } from "./note-content-model"

export interface NoteModel {
    Id: number;
    NoteContent: NoteContent[];
}

And this is my NoteContent model:

export interface NoteContent {
    Id: number;
    Title: string;
    Description: string;
    Completed: boolean;
}

As I understand it, it should load everything into both models when I save the JSON into the model object, as I try in my home.component.ts, that should load my list of components

import { Component, OnInit } from '@angular/core';
import { NoteService } from '../services/note.service';
import { NoteModel } from '../note-model';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  notes?: NoteModel;

  constructor(private noteService: NoteService) { }

  ngOnInit(): void {
    this.noteService.getNotes()
      .subscribe(response => {
        if (response.length >= 0) {
          this.notes = response[0];
          console.log(this.notes.NoteContent)
        }
      });
  }
}

Then I try to get the stored data in my html component using ngFor but I dont get anything.

A: Your interfaces have properties that are named in PascalCase.
The received JSON has properties that are named in cammelCase.
Equally important is that your received JSON has a property name note, but in your NoteModel interface you named the property NoteContent.
Replace your interfaces with the following and your code should work.
export interface NoteModel {
  id: number;
  note: NoteContent[];
}

export interface NoteContent {
  id: number;
  title: string;
  description: string;
  completed: boolean;
}

A: Javascript is case sensitive. 'title' and 'Title' are different things. You need to unify your model and the json


text:
Q: inverse of symmetric matrix is not symmetric in Julia I am using Julia version 0.6.2 and I am facing this problem.
mat = zeros(6, 6)
for i = 1 : 6
    for j = 1 : 6
        mat[i, j] = exp(-(i - j)^2)
    end
end
issymmetric(mat)
issymmetric(inv(mat))

And the output is
Main> issymmetric(mat)
true
Main> issymmetric(inv(mat))
false

I also tried the following Matlab code
mat = zeros(6, 6);
for i = 1 : 6
    for j = 1 : 6
        mat(i, j) = exp(-(i - j)^2);
    end
end
issymmetric(mat)
issymmetric(inv(mat))

And the output is
logical 1
logical 1

A: Apart from manually making the matrix symmetric as you propose, e.g. taking the average of matrix and its transpose like
A = inv(mat)
(A+A.')/2

probably a cleaner way is
smat = Symmetric(mat)
B = inv(smat)

now B (as well as smat) passes issymmetric. Moreover, the fact that it is symmetric is ensured on type level (Symmetric) - some functions might take advantage of this additional information. This is exactly what inv does for smat.
EDIT: the question was also posted on Discourse, where you can find additional discussion about the performance of Symmetric.


text:
Q: Are foreign keys required when using SQLAlchemy relationships Reading the following pages, I can see that I can setup relationships between tables using the orm relationship() function.
https://docs.sqlalchemy.org/en/13/orm/basic_relationships.html
https://docs.sqlalchemy.org/en/13/orm/backref.html#relationships-backref
Using this example:
class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    addresses = relationship("Address", backref="user")

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    email = Column(String)
    user_id = Column(Integer, ForeignKey('user.id'))

Do I need to have an explicit user_id = Column(Integer, ForeignKey('user.id')) statement for the Address class?
Wont the relationship(backref=...) is User provide an Address.user attribute?
If the ForeignKey column is needed in Address, then why isn't it needed in User?

A: First:
You use foreign key in three circumstances:

*

*You have a multi-key reference to another table.

*You want to name the foreign key reference.

*You want to add additional features, such as cascading deletes.

A fourth reason is also plausible: because local coding standards require the use of an explicit constraint.
Second:
According to SQLAchemy documents
In fact, the relationship.backref keyword is only a common shortcut for placing a second relationship() onto the Address mapping, including the establishment of an event listener on both sides which will mirror attribute operations in both directions.
but it's better use back_populates because is explicitly.
we add a .user relationship to Address explicitly. On both relationships, the relationship.back_populates directive tells each relationship about the other one, indicating that they should establish "bidirectional" behavior between each other.
class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String)

    addresses = relationship("Address", back_populates="user")

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    email = Column(String)
    user_id = Column(Integer, ForeignKey('user.id'))

    user = relationship("User", back_populates="addresses")


text:
Q: Activitate Voice Dictation from Bluetooth Keyboard Getting to know my new iPad and I really like the voice dictation, but I can't figure out how to activate it from my Apple Bluetooth Keyboard. My workaround is to turn off the keyboard so I get the onscreen version. Is there a better way?

A: As of iOS 5.1, Voice Dictation is not capable of being started from external keyboards.
There is a workaround.  The solution is that when you want to dictate, press the ⏏ key (eject) on your external keyboard.  This should bring up the virtual keyboard on the screen, from which you can then start dictation.
Note: This key doesn't work like other function keys until you have tapped into a text entry field and have the flashing cursor.

A: press the keyboard tab (first line) when you want to switch between keyboards. They mic will work after that. I have a Logitech bluetooth keyboard on my Ipad Air 2. I hope it helps.


text:
Q: Picasso doesn't load images from HTTP links in API 28 So I've recently faced the problem where only images from HTTPS links load successfully, and all other images don't. This happened when I switched to API 28. It never did this before 28. It fails silently on all images that it fails to load, or only says "Unsatisfiable request". This is on version 2.71828

A: Turns out that according Network Security Configuration page, Starting with Android 9 (API level 28), cleartext support is disabled by default.
The solution is to include android:usesCleartextTraffic="true" inside the application tag in AndroidManifest.xml, and that's it.
This is the issue, although using Glide in Api level 28 and trying to access the same image will actually let you know that this is the issue in LogCat, while Picasso fails silently, but that's fine.


text:
Q: Word doc mail merge with sql server using VB.NET(Needed support to replace images,data in placeholders) Iam looking for a solution to mail merge word document with the data in the sql server(say like fields fname,address,lname etc.,). I am also looking to merge images in the common template with the  image from server and should also save different copies of the word document for each record in the database.
I found the nearest solution in VB at http://blogs.msdn.com/b/bethmassi/archive/2007/12/06/mail-merging-with-word-and-linq-to-xml-in-vb.aspx , but looking for a solution in .NET.
Anyhelp??


text:
Q: Discord.py AttributeError: 'str' object has no attribute 'server' Can you help me why I keep getting this error?
AttributeError: 'str' object has no attribute 'server'
@commands.has_role("customer")
async def email(ctx,count=None,bomb_email=None,*,message=None):
    if message.server is not None:
        await ctx.send("nope")
    else:
        x = int(count)
    if message.server is not None:
        await ctx.send("yes")

    else:
        await ctx.send("nope")

A: If you want to get command's called server you can change message.server with ctx.guild.

A: The problem is, you're trying to access a attribute called server which is not present the the str class. What I think you want is the discord.Message object. And even if you do that, there is no attribute called server for the Message class as well. I think what you need is the guild attribute which returns a discord.Guild object or None.


text:
Q: How to get 3rd level categories in category module opencart 2.0.3 I am trying to get 3rd level category on category page left sidebar but I am unable to get child id, here is my code to get 3rd level category:
$children_lv3_data = array();

if ($child['category_id'] == $data['child_id']) {
    $children_lv3 = $this->model_catalog_category->getCategories($child['category_id']);

    foreach ($children_lv3 as $child_lv3) {
        $filter_data_lv3 = array(
            'filter_category_id'  => $child_lv3['category_id'],
            'filter_sub_category' => true
        );

        $children_lv3_data[] = array(
            'category_id' => $child_lv3['category_id'],
            'name'  => $child_lv3['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data_lv3) . ')' : ''),
            'href'  => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'] . '_' . $child_lv3['category_id'])
        );
    }
}


text:
Q: Xamarin.Forms.Device.StartTimer - Is There a Non-Recurring Version of This? (A Simple Delay) Xamarin.Forms.Device.StartTimer is a convenient method to repeatedly call some code in a certain interval. This is similar to JavaScript's SetInverval() method. JavaScript also has a method to set a single delay, called SetTimeout() - it delays a certain amount of time, then calls the callback code once. Is there a SetTimeout equivalent for Xamarin.Forms, where I simply want the code to be called in the background after a certain delay?
NOTE: I know I can return false to stop the recurrence, and that's easy enough. It just seems like if you're only intending to call the callback once, it's a little semantically misleading to use this recurring timer mechanism.

A: StartTimer will do this

While the callback returns true, the timer will keep recurring.

Simply return false to stop the timer

A: You could start a Task with delay:
async Task DoSomethingOnceWithDelay(TimeSpan delay)
{
    await Task.Delay(delay);
    await MyTask();
}

Official doc.


text:
Q: Combining two covariance matrices I'm calculating the covariance of a distribution in parallel and I need to combine the distributed results into on singular Gaussian. How do I combine the two?
Linearly interpolating between the two almost works, if they are similarly distributed and sized.
Wikipedia provides a forumla at the bottom for combination but it doesn't seem right; two identically distributed distributions should have the same covariance, but the formula at the bottom of the page doubles the covariance.
Is there a way to combine two matrices?

A: This question comes up a lot in various guises.  What is common to them is

How can I combine moment-based statistics that have been computed from disjoint subsets of my data?

The simplest application concerns data that have been split into two groups.  You know the group sizes and the group means.  In terms of these four quantities alone, what is the overall mean of the data?
Other applications generalize from means to variances, standard deviations, covariance matrices, skewnesses, and multivariate statistics; and might involve multiple subgroups of data.  Notice that many of these quantities are somewhat complicated combinations of moments: the standard deviation, for instance, is the square root of a quadratic combination of the first and second moments (mean and mean square).
All such cases are easily handled by reducing the various moments to sums, because sums are obviously and easily combined: they are added.  Mathematically, it comes down to this: you have a batch of data $X = (x_1, x_2, \ldots, x_n)$ that have been separated into disjoint groups of sizes $j_1, j_2, \ldots, j_g$: $(x_1, x_2, \ldots, x_{j_1}; x_{j_1+1}, \ldots, x_{j_1+j_2}; x_{j_1+j_2+1}, \ldots; \ldots; \ldots, x_n)$.  Let's call the $i$th group $X_{(i)} = (x_{j_i+1},x_{j_i+2}, \ldots, x_{j_{i+1}})$.  By definition, the $k$th moment of any batch of data $y_1, \ldots, y_j$ is the average of $k$th powers,
$$\mu_k(y) = \left(y_1^k + y_2^k + \cdots + y_j^k\right)/j.$$
Obviously $j \mu_k(y)$ is the sum of the $k$th powers.  Therefore, referring to our previous decomposition of data into $g$ subgroups, we can break a sum of $n$ powers into groups of sums, obtaining
$$\eqalign{
n \mu_k(X) &= \left(x_1^k + x_2^k + \cdots + x_n^k\right) \\
&= \left(x_1^k + x_2^k + \cdots + x_{j_1}^k\right) + \cdots + \left(x_{j_1+\cdots+j_{g-1}+1}^k + x_{j_1+\cdots+j_{g-1}+2}^k + \cdots + x_n^k\right)\\
&= j_1 \mu_k(X_{(1)}) + j_2 \mu_k(X_{(2)}) + \cdots + j_g \mu_k(X_{(g)}).
}$$
Dividing by $n$ exhibits the $k$th moment of the entire batch in terms of the $k$th moments of its subgroups.
In the present application, the entries in the covariance matrix are, of course, covariances, which are expressible in terms of multivariate second moments and first moments.  The key part of the calculation comes down to this: at each step you will have focused on two particular components of your multivariate data; let's call them $x$ and $y$.  The numbers you are looking at are in the form
$$((x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)),$$
broken up as before into $g$ groups.  For each group you know the average sum of products of the $x_iy_i$: this is the $(1,1)$ multivariate moment, $\mu_{(1,1)}$.  To combine these group values, you will multiply them by the group sizes, add up those results, and divide the total by $n$.
To apply this approach you need to think ahead: it is not possible to combine, say, covariances if you know only the covariances and the subgroup sizes: you also need to know the means of the subgroups (because means are involved in an essential way in all covariance formulas), or something algebraically reducible to the means.  You also might need to take some care concerning any constants that appear in the formulas; the chief trap for the unwary is to confuse a "sample covariance" (which involves a sum of products divided by $n-1$) with a "population covariance" (where the division is by $n$).  This does not introduce anything new; you just have to remember to multiply the sample covariance by $n-1$ (or group covariance by $j_i-1$) to recover the sum, rather than by $n$ (or $j_i$).

Oh, yes: about the present question.  The formula given in the Wikipedia article is given in terms of group means (first moments) and the group sums of products.  As I described above, these will get combined by adding them and then adjusting the results with a division to obtain the covariances.  The final division by $n$ is not shown.


text:
Q: Exchange Managed API determine if email has been anwered - PR_LAST_VERB_EXECUTED Is there a way to determine if a given email in the inbox has been answered (Reply to Sender)
Actually I am using the following code, which does not work correct
ExtendedPropertyDefinition pr_last_verb_executed = new ExtendedPropertyDefinition(0x1081, MapiPropertyType.Integer);
PropertySet psPropSet = new PropertySet(pr_last_verb_executed);

ItemId itemId = new ItemId("<PLACEHOLDER FOR AN Exchange EMail ID>");
EmailMessage serverMail = EmailMessage.Bind(exchangeService, itemId, psPropSet);

int lastState = 0; // should become 102 if email has been answered
serverMail.TryGetProperty(pr_last_verb_executed, out lastState);  // does not return anything to variable lastState

A: As I found out updating Exchange Server to a newer version solves this problem. So this ia a bug in older versions of Microsoft Exchange Server.

A: The best thing to do would be to look at the messages in question with a MAPI editor like MFCMapi or OutlookSpy that will tell you if that property has been set or not (its an optional property set by the client). The property is just an indicator of the last action a client took https://msdn.microsoft.com/en-us/library/ee218425(v=exchg.80).aspx reply is one action but there are many others. PidTagIconIndex https://msdn.microsoft.com/en-us/library/office/cc815472.aspx is another indicator property you can use to do the same thing. EWS also have conversation operations https://msdn.microsoft.com/en-us/library/office/dn610351(v=exchg.150).aspx if you are looking to work with conversation.
Cheers
Glen


text:
Q: How can i search by _id's feature in mongodb For example, I want to update half of data whose _id is an odd number. such as:
db.col.updateMany({"$where": "this._id is an odd number"})

Instead of integer, _id is mongo's ObejectId  which be regard as hexadecimal "string". It is not supported to code as:
db.col.updateMany(
  {"$where": "this._id % 2 = 1"},
  {"$set": {"a": 1}}
)

so, what is the correct format?
And what if molding according to _id?

A: This operation can also be done using two database calls.

*

*Get List of _id from collection.

*Push only ODD _id into an array.

*Update the collection.

Updating the collection:
db.collection.update(
   { _id: { $in: ['id1', 'id2', 'id3'] } }, // Array with odd _id
   { $set: { urkey : urValue } }
)


text:
Q: Issue with generating left click in win32 api?
Below is my code to generate left click using win32 api. The problem is that it gets stuck and does not return to main. When i press Ctrl+c, then it returns to main. BUT when I call it twice, to simulate double click then it is fine. Is there anything wrong with this code?
Thank you.
void LeftClick(void)
{
  INPUT    Input={0};

  // left down
  Input.type      = INPUT_MOUSE; /*The event is a mouse event. Use the mi structure of the union.*/
  Input.mi.dwFlags  = MOUSEEVENTF_LEFTDOWN;
  SendInput(1,&Input,sizeof(INPUT));

  // left up
  ZeroMemory(&Input,sizeof(INPUT));
  Input.type      = INPUT_MOUSE;
  Input.mi.dwFlags  = MOUSEEVENTF_LEFTUP;
  SendInput(1,&Input,sizeof(INPUT));
}

A: If you're not committed to using SendInput, I've had success in the past using SendMessage on the desired hWnd with WM_LBUTTONDOWN then again with WM_LBUTTONUP.
Most buttons also simulate a click with keyboard entry. You can use SendMessage to your desired hWnd with WM_KEYDOWN and wParam VK_SPACE, then WM_KEYUP with VK_SPACE to complete the space bar keypress simulation.


text:
Q: Angular: ng-repeat does not update on view after removing the element I am using ng-repeat to show the list of items in view.
In my controller the array is updating but the view does not update.
 I don't know where I am doing mistake.
Can someone help me to resolve it?
Here is my view part:

      <span class="board-span" tooltip-html-unsafe="Board Name: {{item.name}}
Created by: {{item.createdBy.name}}
Created At: {{item.createdAt}} " tooltip-placement="top">{{item.name}}

And this is my controller code
$scope.reOpenBoard = function() {
            BoardFactory.openBoard(boardId).then(function(data) {
                    $scope.closedBoards.some(function(closed,index){
                        if(closed._id==boardId){
                        $scope.closedBoards.splice(index,1);

                            return true;
                    }else{
                        return false;
                    }
                    });
            }, function(err) {
                console.log(err);
            })
        }

Thank you.

A: If $scope.closedBoards is a jQuery plugin container and .some is a plugin function, you should use $scope.$apply wrapper around your AngularCode:
$scope.reOpenBoard = function() {
            BoardFactory.openBoard(boardId).then(function(data) {
                    $scope.closedBoards.some(function(closed,index){
                            if(closed._id==boardId){
                                $scope.$apply(function(){
                                    $scope.closedBoards.splice(index,1);
                                });
                                return true;
                            }else{
                                return false;
                            }

                    });
            }, function(err) {
                console.log(err);
            })
        }

But i think you have a mistake in your code. $scope.closedBoards - must be an array of data, and it can't contains methods like .some


text:
Q: How can I write several binaries in a json file without using byte[]? I am working in a REST API using Spring Boot, and I need to generate a JSON file with some data, and send that file to the client. Some of this data are simple Strings, but I also need to include some binaries inside it. So, an example of the JSON file generated could be:
{
   "result":"0",
   "message":"",
   "document":{
      "data":{
         "tag1":"String",
         "tag2":"String"
      },
      "binary": {
          "type": "application/pdf",
          "content" ${BINARY_CONTENT}
      }
   }
}

The way I was doing it is by using a Java Object with several properties, and "content" property was a byte[]. However, the files handled can be large (even several GB), so I can not use an array of bytes: the memory will fill up, and also byte[] length is limmited it int_maxSize.
How can I generate the JSON file without using byte[]? For example, handling the InputStream directly. The idea is generate a JSON file (which size can be GB), read it, and then send it as binary to the client. I cannot store the full binary in memory because its size can be large.
Thank you.


text:
Q: Saving an image in MYSQL vs saving to a folder Is there an advantage to either method and/or a risk to either? Looking to upload JPG or PNG files only with a size limit of ~3mb with reduction done before insertion.

A: I would keep them out of the database, store them in the OS's file system and just store a relative path in a database table.
This will allow you to lazy load any images, queries will remain snappy, your database would remain small and image files may be backed up easily. You will have two data stores though and will have to make sure they stay in sync. A modern RDBMS may have solid support for large files so it may be quicker/easier to store them in the database.
So it would depend on your application, how much trust you have in your database and the feature set of your database. And personal preference.


text:
Q: Duplicating pagination on second page Been trying to get this to work and I can get it to show the pagination links but it just duplicates the content from the first page again on page two, can't figure out why?

        <?php query_posts('showposts=10&paged=' . get_query_var('paged'));?>
        <?php $the_query = new WP_Query( 'showposts=12' ); ?>
        <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
        <?php get_template_part( 'partials/loop', 'archive' ); ?>
        <?php endwhile; ?>

        <?php if (function_exists('joints_page_navi')) { ?>
        <?php joints_page_navi(); ?>
        <?php } else { ?>

<?php next_posts_link(__('« Older Entries', "jointstheme")) ?>

<?php previous_posts_link(__('Newer Entries »', "jointstheme")) ?>

        <?php } ?>

A: I found this article and got it to work

    <?php
    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
    $the_query = new WP_Query( 'cat=16&paged=' . $paged );
    ?>
    <?php if ( $the_query->have_posts() ) : ?>
    <?php
    while ( $the_query->have_posts() ) : $the_query->the_post();
    ?>
    <?php get_template_part( 'partials/loop', 'archive' ); ?>
    <?php endwhile; ?>

    <?php
    next_posts_link( 'Older Entries', $the_query->max_num_pages );
    previous_posts_link( 'Newer Entries' );
    ?>

    <?php
    wp_reset_postdata();
    ?>
    <?php else:  ?>

<?php _e( 'Sorry, no posts matched your criteria.' ); ?>

    <?php endif; ?>

the above works but if I out in a link to page navi plugin like:
<?php wp_pagenavi(); ?>

then I get nothing same if I put in a link to the previous page navigation code?
    <?php if (function_exists('joints_page_navi')) { ?>
<?php joints_page_navi(); ?>
<?php } else { ?>

<?php next_posts_link(__('« Older Entries', "jointstheme")) ?>

<?php previous_posts_link(__('Newer Entries »', "jointstheme")) ?>

<?php } ?>


text:
Q: Select 100K+ records quickly I need to select some 100k+ records from a SQL table and do some processing and then do a bulk insert to another table. I am using SQLBulkCopy to to do the bulk insert which runs quickly. For getting the 100k+ records, I am currently using DataReader.
Problem: Sometimes I am getting a timeout error in DataReader. I have increased the timeout to some managable number.
Is there anything like SQLBulkCopy for selecting records in a bulk batch?
Thanks!
Bala

A: It sound like you should do all your processing inside sql server. Or split data into chunks.

A: A quote from this msdn page:

Note
No special optimization techniques exist for bulk-export operations. These operations simply select the data from the source table by using a SELECT statement.

However, on that same page, it mentions the bcp utlity can "bulk export" data from SQL Server to a file.
I suggest you try your query with bcp, and see if it's significantly faster. If it's not, I'd give up and try fiddling with your batch sizes, or look harder at moving the processing into SQL Server.


text:
Q: Is there a simple way to do tiered coin rounding using standard Cocoa libraries? In 2012, Canada abolished the 1¢ penny. To allow cash transactions to be processed at a 5¢ resolution, the following rounding policy was put into place:

The calculation of the Goods and Services Tax (GST) or Harmonized Sales Tax (HST) on purchases, whether for cash or non-cash transactions, will continue to be calculated to the penny and added to the price. It is only the total cash payment for the transaction that will be rounded.

From Royal Canadian Mint.
That is, all calculations should be done as accurately as possible and end up using standard "round half-up tie breaking to achieve hundredths resolution, but when it comes time to make the cash payment, further rounding to the nearest nickel is required.
For internationalization, I need to implement this. I also would like to re-use this for other places where, say, the final cost is rounded to 10¢, 25¢, etc. How do I accomplish this behavior in iOS, using NSDecimalNumbers?
I'd love if it worked like this on Obj-C:
finalCost = [total roundWithResolution:@0.05];

or this in Swift:
finalCost = total.roundWithResolution(0.05);

To clear up any ambiguity above, this is the behavior after having already rounded to the hundredths place using "round half-up" tie breaking:
5¢

*

*$0.98 to $1.02 → $1.00

*$1.03 to $1.07 → $1.05

*$1.08 to $1.10 → $1.10

*And so on

10¢

*

*$0.96 to $1.05 → $1.00

*$1.06 to $1.15 → $1.10

*And so on

25¢

*

*$0.88 to $1.12 → $1.00

*$1.13 to $1.37 → $1.25

*$1.38 to $1.62 → $1.50

*$1.63 to $1.87 → $1.75

*$1.88 to $2.12 → $2.00

*And so on

A: Took me a night's worth of asking around and testing solutions, but I finally came up with this:
@implementation NSDecimalNumber (RoundWithResolution)

- (NSDecimalNumber *)roundWithResolution:(NSDecimalNumber *)resolution
{
    NSDecimalNumber *step1 = [self decimalNumberByDividingBy:resolution];
    NSDecimalNumber *step2 = [step1 round:0];
    NSDecimalNumber *step3 = [step2 decimalNumberByMultiplyingBy:resolution];
    NSDecimalNumber *step4 = [step3 round:2];
    return step4;
}

- (NSDecimalNumber *)round:(NSUInteger)decimalPlaces
{
    NSNumberFormatter *formatter = [NSNumberFormatter new];
    formatter.roundingMode = NSNumberFormatterRoundHalfUp;
    formatter.numberStyle = NSNumberFormatterNoStyle;
    formatter.maximumFractionDigits = decimalPlaces;
    return [NSDecimalNumber decimalNumberWithString:[formatter stringFromNumber:self]];
}

@end

This is based off this formula on Math.SE by kccu, Milo Brandt, and Eric Towers:


text:
Q: Warning messages with list and fine without list in R, Why? Suppose I have this matrix:
Matrix <- c(5, 2, 3, 1, 4,
                 0, 2, 3, 4, 1,
                 0, 0, 3, 4, 1,
                 0, 0, 0, 4, 1,
                 0, 0, 0, 0, 1)
      Matrix <- matrix(Matrix, 5, 5)
fam <- list()
for (i in 1:3){
fam[i] <- array(0, dim = dim(Matrix))
}

Then I got this warning messages:
Warning messages:
1: In fam[i] <- array(0, dim = dim(Matrix)) :
  number of items to replace is not a multiple of replacement length
2: In fam[i] <- array(0, dim = dim(Matrix)) :
  number of items to replace is not a multiple of replacement length
3: In fam[i] <- array(0, dim = dim(Matrix)) :
  number of items to replace is not a multiple of replacement length

Then the result is not as accepted:
> fam
[[1]]
[1] 0

[[2]]
[1] 0

[[3]]
[1] 0

However, without list it is work fine!!
> fam
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    0    0
[3,]    0    0    0    0    0
[4,]    0    0    0    0    0
[5,]    0    0    0    0    0

Where it is my mistake??

A: Instead of fam[i] try fam[[i]].

A: [[ selects a single element of a list

for (i in 1:3){
  fam[[i]] <- array(0, dim = dim(Matrix))
}

http://stackoverflow.com/questions/1169456/the-difference-between-and-notations-for-accessing-the-elements-of-a-lis


text:
Q: Does VB.Net have an equivalent to #pragma warning disable/restore? I've found a way to disable warnings for an entire VB.NET project, but that is very undesirable. I would like to disable a certain warning for the scope of one method at most. A line-by-line disable and restore would be better. For example, C# has #pragma warning disable (and restore). Does VB.NET have anything like this?

A: If you are using Visual Studio 2015, the answer is yes, yes it does.   The syntax is #Disable Warning BC40000 and #Enable Warning BC40000
https://github.com/dotnet/roslyn/wiki/Languages-features-in-C%23-6-and-VB-14

A: Unfortunately the answer is no, the VB.NET compiler doesn't support suppression of warnings in such a manner.
You would have to re-factor your VB.NET code or look at some other alternative like writing some of the code in C#.


text:
Q: Is it possible to control a latching (bistable) relay with a single MCU pin? Controlling a latching relay, like HFD2/012-S-L2 (datasheet [PDF]) with two MCU pins is straightforward:

And here is the corresponding code:
void switchRelayTx() {
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_SET);
    HAL_Delay(10);
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_RESET);
}

void switchRelayRx() {
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_SET);
    HAL_Delay(10);
    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_15, GPIO_PIN_RESET);
}

But when you need >= 10 relays in the project you end up out of MCU pins very soon. Thus I wonder if it's possible to control such a relay with only one MCU pin, maybe by utilizing a High-Z pin state, and without too many additional external components? Off the top of my head, I couldn't come up with the schematic.
Simply putting an "I2C pin number extender" like PCF8574 is possible of course, but I'm curious if there is a little less brute-force solution. Using a regular relay is not an option in the project because of the extra current such relays consume. Using a single-coil latching relay could be an option though.

A: Using a 3-state pin is a workable approach. Use a pair of comparators to detect when the pin is below 1/3 VCC for one coil and above 2/3 VCC for the other coil. Then your code defines 3 states: drive low, drive high or no drive. The I/O would be tied to a midpoint voltage.
The LM339 has an open-collector output with enough current for the coil, so it would replace the transistor.

A: Using discretes you can use N+1 pins since you can multiplex if you want the set coils engaged or the reset coils engaged.
Common negative all set coils into an P-channel and all reset coils into an N-channel. If you drive the set/reset high, n-channel will conduct. if you pull it low the p-channel will conduct.
The you enable the common high side switch for the relay you want to change. This could be done with a CD4010 for example.
Or if you can afford to change the relays to 5V and can afford a +5V and -5V power supply sufficient to switch the relay you can do the above in a tri-state buffer chip or shift register. As hacktastical and lundin already hinted.
Using other chips you can use h-bridges or some MAX4820.

A: It possible, but inconvenient. You could consider using chips such as 74HC138 to control one relay at a time. For example 2 chips would allow you to control 8 relays with 5 control pins- 3 address plus S/R strobes. Or 7 pins to control 16 relays (that could be reduced).
You would use PNP rather than NPN transistors since that chip has inverted outputs. Ask if this is not clear how to implement.

A: I did it with a single coil latching relay as shown in the circuit below. Using dual comparator chip with push-pull output that supports enough current for the relay coil rating (here it is AZV3002). Here we actually have a full-bridge switching circuit.
To operate the below circuit: (for STM32F03 MCU)

*

*MCU in push-pull mode: high or low will drive the relay in either direction.

*MCU in open-drain mode: low will keep the state, i.e. no drive.

The input to both comparators at IN+ will be either 1/2*Vcc, 1/3*Vcc, or 2/3*Vcc. The middle resistor of the reference voltage divider needs to be slightly less than the other two so we guarantee that the upper reference is slightly less than 2/3*Vcc and the lower is slightly more than 1/3*Vcc, so the circuit is guaranteed to work as expected.
Hope this helps


text:
Q: How to avoid unused-variable warning for threadprivate variable with gcc? Consider the following fragment compiled with gcc /openmp /Wall:
static __attribute((unused)) int zzzz;
#pragma omp threadprivate(zzzz)

It gives this error message

error: 'zzzz' declared 'threadprivate' after first use

Just removing the attribute gives:

warning: 'zzzz' defined but not used [-Wunused-variable]

To me that looks like a clear compiler-defect, as if "unused" sets "used-flag" and then threadprivate trips on that.
The error message is the same as in openMP C++ error with threadprivate vector - so I suppose it has a similar underlying cause, however, this is C-code not C++ and thread_local as storage class seems C++-specific.
Are there any good work-arounds for this?
(I know the obvious solution of removing or using the variable.)


text:
Q: how can I construct a list of NumPy arrays from these two arrays? I have two arrays which are column and row values in PDF coordinate space:
x = array([111, 303, 405, 513]
y = array([523, 546 , 569 , 603 ])

Here's a visual:

I need to convert this into a list of numpy arrays, where each array is the boundary coordinates (four points that define the box). For example, a list of the lower left and upper right boxes would be
all_boxes =
    [array([[111, 523],
            [303, 523],
            [303, 546],
            [111, 546]], dtype=int64),
    array([[405, 569],
            [513, 569],
            [513, 603],
            [405, 603]], dtype=int64)]

And so on for nine boxes. How can I achieve this? I would guess some kind of NumPy multiplication but I can't see it. Thank you.

A: Short and simple:
import numpy as np
x = np.array([111, 303, 405, 513])
y = np.array([523, 546 , 569 , 603 ])

def coupler(lst): return [[c1,c2] for c1,c2 in zip(lst,lst[1:])]

x_couples,y_couples=coupler(x),coupler(y)

boxes=[]
for x1,x2 in x_couples:
    for y1,y2 in y_couples:
        boxes.append(np.array([[x1,y1],[x2,y1],[x2,y2],[x1,y2]]))

The output:
[array([[111, 523],
        [303, 523],
        [303, 546],
        [111, 546]]),
array([[111, 546],
        [303, 546],
        [303, 569],
        [111, 569]]),...]

A: First, try generating the x and y coordinates for each box. You will have 3 coordinate sets for x and for y respectively. Then, compute the cartesian product of the said x and y coordinate sets.
import numpy as np

x = array([111, 303, 405, 513]
y = array([523, 546 , 569 , 603 ])

# generate grid points
xs = np.repeat(x, 4)[2:-2].reshape(-1, 4)
xs = np.roll(xs, -1,  axis=1)
ys = np.repeat(y, 4)[2:-2].reshape(-1, 4)

# cartesian product
xx = np.tile(xs, ys.shape[0]).reshape(-1, 4)
yy = np.tile(ys.reshape(1,-1), xs.shape[0]).reshape(-1, 4)
boxes = np.hstack((xx, yy)).reshape(-1, 2, 4)

More info about cartesian product:
Cartesian product of sets
How to implement the cartesian product in numpy efficiently