text:
Q: Materialized View returns more results than the query itself Oracle I am facing such a strange behavior in our database (Oracle 12c):
There is a query than contains a few partition by clauses and subqueries. After we converted it into a materialized view, we are receiving different results than when running a query in isolation.
The code generated by SQLDeveloper to create the object is:
CREATE MATERIALIZED VIEW  {MV_name}.{columns}
 ORGANIZATION HEAP PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
 NOCOMPRESS LOGGING
  STORAGE(INITIAL 163840 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE {our_tablespace}   NO INMEMORY
  BUILD IMMEDIATE
  USING INDEX
  REFRESH COMPLETE ON DEMAND START WITH sysdate+0 NEXT SYSDATE + 1
  USING DEFAULT LOCAL ROLLBACK SEGMENT
  USING ENFORCED CONSTRAINTS DISABLE QUERY REWRITE
  AS
{query}

The query is:
select process_number, status, LASTCHANGEUSER, date_time,
rank() over (partition by cos.process_number order by cos.date_time desc) rank
from (

    select  process_number,
             status,
             grp,
             LASTCHANGEUSER,
             min(jn_datetime) over (partition by process_number, grp order by jn_datetime) as date_time,
             rank() over (partition by process_number, grp order by jn_datetime) as aux_rank
    from     (select process_number,
                     jn_datetime,
                     status,
                     process_jn.LASTCHANGEUSER,
                     row_number() over (partition by process_number order by jn_datetime)
                       - row_number() over (partition by process_number, status order by jn_datetime) grp
              from   process_jn
            )
    ) cos where aux_rank = 1;

Anyone has an idea what might have happened there, please??


text:
Q: How do I stop a bokeh server / app started by panel in my jupyter lab or notebook? (without killing my kernel) I've created an interactive app in my jupyter lab and called .show() on my panel object, so it started a bokeh server, as in the example below. It looks nice, but now I want to stop the server. How do I do that without stopping jupyter notebook or killing my python kernel? I don't want to restart my notebook kernel because I don't want to lose other variables present in my current notebook.
I just want to stop/kill that bokeh server that was initiated by .show()
import numpy as np
import pandas as pd
import hvplot.pandas
import holoviews as hv
import panel as pn

df = pd.DataFrame(np.random.normal(size=[50, 2]))
hv_plot = df.hvplot()

pn.panel(hv_plot).show(port=12345)

A: Maybe it's just best to declare the bokeh server as such:
bokeh_server = pn.panel(hv_plot).show(port=12345)

This way you have right away control over the server without having to look in your globals() to see where the server is.
You can stop the server as follows:
bokeh_server.stop()

The strange thing is, the address localhost:12345 can still be reached when you stop the server like this, and you can still use the app when you already had it open in your browser. However when you refresh the page it's gone and you can use the port again for a different app. It just takes quite a while before the server is completely stopped.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scanning a complete line from a external file in C++ For scanning a complete line from a file in c++:
when I am using inFile >> s; where s is a string and inFile is an external file, it is just reading the first first word from the line.
Full code:  (I am just trying to scan the file line by line and print the length of lines. )
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ifstream inFile;
inFile.open("sample.txt");
long long i,t,n,j,l;
inFile >> t;
for(i=1;i<=t;i++)
{
    inFile >> n;
    string s[n];
    for(j=0;j<n;j++)
    {
        getline(inFile,s[j]);
        l=s[j].length();
        cout<<l<<"\n";
    }
}
return 0;
}

Sample.txt
2
3
ADAM
BOB
JOHNSON
2
A AB C
DEF

First integer is test case followed by no of words to come.

A: Use the std::getline function; it was made for this exact purpose. You can read about it here. In your specific case, the code would be:
string s;
getline(infile, s);
// s now has the first line in the file.

To scan the complete file, you can put the getline() in a while loop since it returns false at the end of file (or if a bad bit is read). Thus you could do:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    ifstream inFile;
    inFile.open("sample.txt");
    int lineNum = 0;
    string s;
    while(getline(infile, s) {
        cout << "The length of line number " << lineNum << " is: " << s.length() << endl;
    }
    return 0;
}


text:
Q: WP_Query orderby not work with meta_key I want to order the post by 'leasenum' in my archive-shop.php.
I want to filter the specific 'mall' .
The result set is correct but the order is wrong.
The orderby only works if I remove the 'meta_key' &  'meta_value'.
$args = array(
        'post_type'     => 'shop',
        'meta_key'      => 'mall',
        'meta_value'    =>   $getvalue,
        'posts_per_page'=>-1,
        'order'       => 'ASC',
        'orderby'     => 'leasenum',
    );
    $the_query = new WP_Query( $args );

How to make both meta_key & orderby works?

A: As you can see in the documentation, neither leasenum nor an arbitrary meta key is a valid value for orderby.
If you want to sort by a single meta value, you should set meta_key to that key, and then you can set orderby to meta_key (or meta_value_num if the value is numeric) to sort by that key. This is also described in the documentation:

Note that a meta_key=keyname must also be present in the query. Note
also that the sorting will be alphabetical which is fine for strings
(i.e. words), but can be unexpected for numbers (e.g. 1, 3, 34, 4, 56,
6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect).
Use meta_value_num instead for numeric values. You may also specify
meta_type if you want to cast the meta value as a specific type.
Possible values are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME',
'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED', same as in $meta_query.
When using 'meta_type' you can also use 'meta_value_*' accordingly.
For example, when using DATETIME as 'meta_type' you can use
'meta_value_datetime' to define order structure.

You are currently already using the meta_key property to filter the results by a value, but this can be moved to a meta_query so that you can use meta_key for sorting:
$args = array(
    'post_type'      => 'shop',
    'posts_per_page' => -1,
    'order'          => 'ASC',
    'orderby'        => 'meta_value_num',
    'meta_key'       => 'leasenum',
    'meta_query'     => array(
        array(
            'key'   => 'mall',
            'value' => $getvalue,
        ),
    ),
);

$the_query = new WP_Query( $args );


text:
Q: Error while compiling a rust file generated by c2rust. using rustc I have a rust program named hello.rs.
The program is I'm unable to compile it using rustc. I generated the hello.rs using c2rust online transpiler. But if I use cargo run hello.rs the program runs smoothly.
When using rustc it shows the following error. How to fix it?
The original hello.c file:
    void main() {
       // printf() displays the string inside quotation
       printf("Hello, World!");

    }

The hello.rs file.
    #![allow(dead_code, mutable_transmutes, non_camel_case_types, non_snake_case,
             non_upper_case_globals, unused_assignments, unused_mut)]
    #![register_tool(c2rust)]
    #![feature(main, register_tool)]
    extern "C" {
        #[no_mangle]
        fn printf(_: *const libc::c_char, _: ...) -> libc::c_int;
    }
    unsafe fn main_0() {
        // printf() displays the string inside quotation
        printf(b"Hello, World!\x00" as *const u8 as *const libc::c_char);
    }
    #[main]
    pub fn main() { unsafe { main_0() } ::std::process::exit(0i32); }

The error message:
┌──(pegasus㉿pegasus)-[~/Documents/Rust_testing]
└─$ rustc hello.rs -o test2
error[E0557]: feature has been removed
 --> hello.rs:4:12
  |
4 | #![feature(main, register_tool)]
  |            ^^^^ feature has been removed

error: cannot find attribute `main` in this scope
  --> hello.rs:13:3
   |
13 | #[main]
   |   ^^^^
   |
   = note: `main` is in scope, but it is a function, not an attribute

error[E0433]: failed to resolve: use of undeclared crate or module `libc`
 --> hello.rs:7:21
  |
7 | fn printf(_: *const libc::c_char, _: ...) -> libc::c_int;
  |                     ^^^^ use of undeclared crate or module `libc`

error[E0433]: failed to resolve: use of undeclared crate or module `libc`
 --> hello.rs:7:46
  |
7 | fn printf(_: *const libc::c_char, _: ...) -> libc::c_int;
  |                                              ^^^^ use of undeclared crate or module `libc`

error[E0433]: failed to resolve: use of undeclared crate or module `libc`
  --> hello.rs:11:52
   |
11 | printf(b"Hello, World!\x00" as *const u8 as *const libc::c_char);
   |                                                    ^^^^ use of undeclared crate or module `libc`

warning: `#[no_mangle]` has no effect on a foreign function
 --> hello.rs:6:1
  |
6 | #[no_mangle]
  | ^^^^^^^^^^^^ help: remove this attribute
7 | fn printf(_: *const libc::c_char, _: ...) -> libc::c_int;
  | --------------------------------------------------------- foreign function
  |
  = note: `#[warn(unused_attributes)]` on by default
  = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
  = note: symbol names in extern blocks are not mangled

error: aborting due to 5 previous errors; 1 warning emitted

Some errors have detailed explanations: E0433, E0557.
For more information about an error, try `rustc --explain E0433`.

When using cargo it compiles and runs perfectly.
└─$ cargo run hello.rs
   Compiling Rust_testing v0.1.0 (/home/pegasus/Documents/Rust_testing)
warning: crate `Rust_testing` should have a snake case name
  |
  = note: `#[warn(non_snake_case)]` on by default
  = help: convert the identifier to snake case: `rust_testing`

warning: `Rust_testing` (bin "Rust_testing") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.17s
     Running `target/debug/Rust_testing hello.rs`
Hello, world!

When removing the #[] this code runs in the playground.
here's the new.rs code:
extern "C" {
    fn printf(_: *const libc::c_char, _: ...) -> libc::c_int;
}
unsafe fn main_0() {
    // printf() displays the string inside quotation
    printf(b"Hello, World!\x00" as *const u8 as *const libc::c_char);
}
pub fn main() { unsafe { main_0() } ::std::process::exit(0i32); }

But it still shows the three error[E0433]: failed to resolve: use of undeclared crate or module libc.
Here's my Cargo.toml file:
[package]
name = "Rust_testing"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
libc = "0.2"

A: It doesn't work for me either, even with cargo run. I'm unsure, maybe this requires an old version of nightly Rust?
Either way, if you remove the questionable code, it works without a problem:
extern "C" {
    fn printf(_: *const libc::c_char, _: ...) -> libc::c_int;
}

unsafe fn main_0() {
    // printf() displays the string inside quotation
    printf(b"Hello, World!\n\x00" as *const u8 as *const libc::c_char);
}

pub fn main() {
    unsafe { main_0() }
    ::std::process::exit(0i32);
}

Hello, World!

You mention that it doesn't work with rustc directly. That is true, because rustc is a compiler, it is not a dependency manager. You need to link the dependencies manually if you don't want to use cargo. I highly recommend using cargo, though.
If you run cargo run -vv (of course run cargo clean before, otherwise you won't see anything), you can see how cargo adds the dependencies.


text:
Q: Not to work right column in chrome and safari I made a site http://0334.ru/test/
and i have some problems with column. in the firefox is all right. but in the chrome is all bad((

A: As I understand, bottom cell of right column goes to first column.
Maybe you should use table instead divs...
(Так сказать, по-старинке, перейти от блоковой разметки к табличной? Либо установить в CSS привязку блоков друг к другу. Ищите в сети информацию по теме "многоуровневое раскрывающееся меню". Да, это не то, что отображено на странице. Но решения в плане CSS будут очень похожи.)

A: try this use float left comment display:inline-block
may be its help you
div.home-service-item {
background: none repeat scroll 0 0 #f6f6f6;
border-radius: 0 0 4px 4px;
margin-bottom: 20px;
margin-right: 20px;
width: 300px;
/* display: inline-block; */
float: left;
margin-top: 20px;
}


text:
Q: How to enable thin server for faye in production in rails3 for private_pub gem with apache2 I am using private_pub gem for live chat in my rails 3.2 application and it is working perfectly on development mode but I am stuck at how to do it on production.
I am using apache2 in production. When I ran this command on server

RAILS_ENV=production bundle exec rackup private_pub.ru -s thin -E production

It starts the thin server but my app keeps on waiting for response from

http://www.example.com:9292/faye.js

It doesn't do anything. I am unable to connect with faye in prodution
Thanks for help in advance

A:
Thin and Apache need to be set up running on different ports.
The default settings for both should work, but you should double
  check. Ensure apache is running under port 80 and thin is using port
  9292. These numbers should be visible when the servers start up.
In the end you should be able to access faye.js at
  http://yoursite.com:9292/faye.js and your site at http://yoursite.com/

Source: https://stackoverflow.com/a/6667347/539075


text:
Q: HTTP: When redirecting, does the server send response immediately? I was curious how HTTP redirects work and was wondering whether the client has to request once or twice.
When the client requests the url http://example.com/foo and the server response with a 301 (permanent redirect) to http://example.com/bar, does the server also send the response of the /bar url? Or does the client has to request /bar?
I've tried to express my thought in graphics:
1:

2:

A: HTTP/1.1
deceze's answer is completely correct for HTTP/1.1 and earlier, i.e. the server must wait for the client to process the 301 and request the new URL, or defer to its cache.
HTTP/2: Server Push
In HTTP/2, the server can send both the 301 for /bar and the 200 for /bar.html at (more or less) the same time, using a feature called Server Push. Server Push is described in RFC 7540, section 8.2. Basically, while the server is sending the 301 for /bar, it sends another stream with the 200 for /bar.html, along with information on what the client request for /bar.html would have looked like (the method, resource, HTTP headers in the request, etc.).
Server Push does require that both client and server support HTTP/2, that they both support Server Push, and that the client has not requested that Server Push be disabled by setting the SETTINGS_PUSH_ENABLED parameter to 0. Any proxies or other intermediaries between the server and client are also free to choose not to pass on the server's pushed content to the client.
So if your server supports HTTP/2, graphic #1 is possible, but you cannot guarantee that it will happen, though most modern browsers do support HTTP/2 with Server Push.

A: The server can only send one response, it cannot answer with a 301 and a 200. The client has to make another request for the new resource. This also allows the client to make use of their cache, perhaps there's no actual need for the client to request the resource.


text:
Q: Convert String to Enum?
Possible Duplicate:
Java - Convert String to enum

I have a method that uses an enum:
mymethod(AnotherClass.MyEnum.PassedEnum);

And I want to nest this within a class that receives a String which becomes MyEnum:
public static void method(String toPass){

 mymethod(AnotherClass.toPass.PassedEnum);

}

The passed variable has to be a String but I need to convert it to a Enum to pass to AnotherClass?
TIA

A: Do you mean like ...
MyEnum e = MyEnum.valueOf(text);

or
MyEnum e = Enum.valueOf(MyEnum.class, text);

A: I think the static factory method Enum.valueOf() does what you want.

A: Try doing this in the body of method:
AnotherClass.toPass.PassedEnum.valueOf(toPass);

A: You can use Enum.valueOf(Class<...>, String) to convert a string to the corresponding enum instance:
MyEnum value = Enum.valueOf(MyEnum.class, "ENUM_VALUE");

If the string contains a value that does not exist as an enum constant, this method throws IllegalArgumentException.

A: public static void method(String toPass){

 mymethod(AnotherClass.MyEnum.valueOf(toPass));

}

A: You can use the static method Enum.valueOf to convert a string to a Enum value:
public static void method(String toPass)
{
    AnotherClass.MyEnum eval = Enum.valueOf(AnotherClass.MyEnum.class,toPass);
    mymethod(eval);
}

A: Use AnotherClass.MyEnum.valueOf(toPass)


text:
Q: Apache FOP float text right Im using the Apache FOP to convert Html document to PDF.
In my document I need the right align. I was using http://webcoder.info/downloads/xhtml2fo.xsl stylesheet but the float feature is not working.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <title>W22</title>

          Invoice No : $invoiceId

          Date : $date

          Client Ref : $customerAccount

          Email : $email


text:
Q: Show that $\frac{\sin(mx)}{\sin(x)}=\sum_{j=0, j\equiv 1\pmod 2}^m\binom{m}{j}(1-\sin^2(x))^{(m-j)/2}(-\sin^2(x))^{(j-1)/2}$ Show that $$\frac{\sin(mx)}{\sin(x)}=\sum_{\underset{j\equiv 1\pmod 2}{j=0} }^m\binom{m}{j}(1-\sin^2(x))^{(m-j)/2}(-\sin^2(x))^{(j-1)/2},$$
where $m$ is odd. I did as:
If $z=e^{ix}$, then,
$$\frac{\sin(mx)}{\sin(x)}=\frac{\Im(z^m)}{\Im(z)}=\frac{z^m-\bar z^m}{z-\bar z}=\prod_{k=1}^m(z-\zeta _m^k\bar z),$$
where $\zeta _m$ is a primitive root of $X^m-1$.
Any idea on how to conclude ?

A: Hint
\begin{align}
\sin(mx) &= \operatorname{Im} (e^{ixm}) \\
&= \frac{(e^{ix})^m - (e^{-ix})^m}{2i}  \\
&= \frac{(\cos x + i\sin x)^m - (\cos x - i\sin x)^m}{2i} \\
&= -i\sum \limits_{{\small\mbox{odd}} \ \  j} {m\choose j}(\cos x)^{m-j} (i\sin x)^j\\
&= -i\sum \limits_{{\small\mbox{odd}} \ \  j} {m\choose j}(1 - \sin^x)^{\frac{m-j}{2}} (-\sin^2 x)^{\frac{j}{2}}
\end{align}


text:
Q: Partial not receiving all variables from :locals In my controller I have:
- @items.each do |item|
  = render :partial => 'item', :locals => { :item => item, :draggable => true }

And in the item partial I have:
%span{:id => "item_#{item.id}", :class => 'item'}
  = item.name
  - if defined?(draggable)
    = draggable_element "item_#{item.id}", :revert => true

This is not working, however, because defined?(draggable) returns false. The draggable_element is never rendered.
I know that item is passed through :locals because the rest of the partial renders. If I change the partial to read:
- if defined?(item)
  = draggable_element "item_#{item.id}", :revert => true

Then the draggable_element is rendered.
Any idea why :draggable is not getting passed to the partial?

A: Use local_assigns[:draggable] instead of defined?(draggable).
From the Rails API "Testing using defined? var will not work. This is an implementation restriction."

A: I've solved this problem in the past by throwing this into the top of the partial.
 <% draggable ||= nil %>

That allows me to do
 <% if draggable %>

So long as I don't try to make the distinction between draggable being nil and never being passed.


text:
Q: How can I print Qrcode in vb.net? I made a code that generate a QRcode.
And now I'm trying to print it in thermal paper . But how can i print it specific size of paper? Thank you
Private Sub GraphicPrint(ByVal sender As Object, ByVal e As PrintPageEventArgs)

    Dim x As Integer = 60
    Dim y As Integer = 60
    Dim width As Integer = 100
    Dim height As Integer = 50

    ' e.Graphics.DrawImage(Image.FromFile(GraphicLocation.Text), x, y, width, height, e.Graphics.VisibleClipBounds)
    e.Graphics.DrawImage(Image.FromFile(GraphicLocation.Text), x, y, width, height)
    e.HasMorePages = False
End Sub

Private Sub BeginGraphicPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BeginGraphicPrint.Click
    Try
        AddHandler PrintGraphicControl.PrintPage, AddressOf Me.GraphicPrint
        PrintGraphicControl.Print()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

A: try something like this
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
    Dim g As Graphics = e.Graphics
    ' Draw image to screen.
    g.DrawImage(Piccode.Image, 0, 0, 100, 100)
End Sub


text:
Q: How to create tiled map? How to create a tile based game map in javafx 2.0?
Should I use ImageView elements or there is other method for direct images drawing?

A: Your question is not very specific.
As I understand your issue a possible option is to extend a javafx.scene.layout.Region. So you are free to add other nodes, make some custom drawings, style with css etc. Nearly everything is possible :)
Example Code (Sorry, no SSCCE)
public class Tile extends Region {
    public Tile() {
        //add custom creation code
    }

    //add all required methods for custom drawing, styling etc.
}

Tiles can be placed inside a e.g. TileContainer (another Object extending e.g. a Region) at a specified position (described by x/y-coordinates).
public class TileContainer extends Region {
    private void addTiles() {
        //create your tiles e.g. like this
        double xPositon = 10; //example value
        double yPosition = 20; //example value

        Tile tile = new Tile();
        tile.setLayoutX(xPosition);
        tile.setLayoutY(yPOsition);

        this.getChildren.add(tile);
    }
}

Hope, it helps realizing your ideas.


text:
Q: Status bar still shows in black after hide I have my status bar disappear on a button press and all works fin hiding and un hiding on trees but when I go back to the last view controller the white status bar hides but still leaves a black status bar showing I'm using the same code used on button pressed hide as I am in view Will Disappear.
here are the codes used:
//Pressing a button with works on hiding the white status bar with no black status bar underneath.
@IBAction func onPlayPressed(sender: AnyObject) {
    start()

    isHidden = !isHidden
    UIView.animateWithDuration(0.3) { () -> Void in
        self.setNeedsStatusBarAppearanceUpdate()

}
    self.navigationController?.hidesBarsOnTap = false
    self.navigationController?.setNavigationBarHidden(true, animated: true)

//This section hides the white status bar but leaves a black status bar underneath.
override func viewWillDisappear(animated: Bool) {
    synth.pause()
    vox.pause()

    isHidden = true
    UIView.animateWithDuration(0.3) { () -> Void in
        self.setNeedsStatusBarAppearanceUpdate()

    }
    self.navigationController?.hidesBarsOnTap = false
    self.navigationController?.setNavigationBarHidden(true, animated: true)

Any help will be greatly appreciated.
All the best
Tony Merritt

A: Some terminology
Status Bar:

Navigation Bar:

Navigation and Status Bars:

Try my sample:

ViewController.swift

import UIKit

class ViewController: UIViewController {

@IBOutlet var hideButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    if (self.navigationController?.navigationBarHidden)! {
        hideButton.setTitle("show", forState: .Normal)
    }
}

@IBAction func hideNavigationBar(sender: AnyObject) {
    self.navigationController?.hidesBarsOnTap = false
    self.navigationController?.setNavigationBarHidden(!(self.navigationController?.navigationBarHidden)!, animated: true)
}

@IBAction func goBack(sender: AnyObject) {
    self.navigationController?.popViewControllerAnimated(true)
}
}

Main.storyboard

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15G31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="T9D-e2-4rQ">
<dependencies>
    <deployment identifier="iOS"/>
    <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
    <!--View Controller-->
    <scene sceneID="ZDJ-xV-lml">
        <objects>
            <viewController id="3W3-SS-KDU" sceneMemberID="viewController">
                <layoutGuides>
                    <viewControllerLayoutGuide type="top" id="Mxj-5M-2iY"/>
                    <viewControllerLayoutGuide type="bottom" id="3C4-b8-R1X"/>
                </layoutGuides>
                <view key="view" contentMode="scaleToFill" id="Hr5-jU-7uD">
                    <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
                    <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                    <subviews>
                        <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="DLX-GN-6Nd">
                            <rect key="frame" x="283" y="285" width="34" height="30"/>
                            <state key="normal" title="push"/>
                            <connections>
                                <segue destination="aX5-Sj-vzs" kind="show" id="5hq-PZ-fji"/>
                            </connections>
                        </button>
                    </subviews>
                    <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
                    <constraints>
                        <constraint firstItem="DLX-GN-6Nd" firstAttribute="centerY" secondItem="Hr5-jU-7uD" secondAttribute="centerY" id="hM7-eb-ZcS"/>
                        <constraint firstItem="DLX-GN-6Nd" firstAttribute="centerX" secondItem="Hr5-jU-7uD" secondAttribute="centerX" id="yTt-om-iNF"/>
                    </constraints>
                </view>
                <navigationItem key="navigationItem" id="PzV-EJ-7im"/>
            </viewController>
            <placeholder placeholderIdentifier="IBFirstResponder" id="GKQ-Ot-Zmx" userLabel="First Responder" sceneMemberID="firstResponder"/>
        </objects>
        <point key="canvasLocation" x="865" y="375"/>
    </scene>
    <!--View Controller-->
    <scene sceneID="dHO-Tf-TVb">
        <objects>
            <viewController id="aX5-Sj-vzs" customClass="ViewController" customModule="stackoverflow_39240675" customModuleProvider="target" sceneMemberID="viewController">
                <layoutGuides>
                    <viewControllerLayoutGuide type="top" id="a3I-YL-ZHX"/>
                    <viewControllerLayoutGuide type="bottom" id="EDl-yb-Y7O"/>
                </layoutGuides>
                <view key="view" contentMode="scaleToFill" id="dve-Qr-cm1">
                    <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
                    <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                    <subviews>
                        <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="XYd-b4-iN3">
                            <rect key="frame" x="285" y="285" width="30" height="30"/>
                            <state key="normal" title="hide">
                                <color key="titleColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                            </state>
                            <connections>
                                <action selector="hideNavigationBar:" destination="aX5-Sj-vzs" eventType="touchUpInside" id="8OZ-fj-hkz"/>
                            </connections>
                        </button>
                        <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="KHT-Tm-0Sw">
                            <rect key="frame" x="283" y="323" width="34" height="30"/>
                            <state key="normal" title="back">
                                <color key="titleColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
                            </state>
                            <connections>
                                <action selector="goBack:" destination="aX5-Sj-vzs" eventType="touchUpInside" id="0Gj-6r-RH0"/>
                            </connections>
                        </button>
                    </subviews>
                    <color key="backgroundColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
                    <constraints>
                        <constraint firstItem="XYd-b4-iN3" firstAttribute="centerY" secondItem="dve-Qr-cm1" secondAttribute="centerY" id="4oU-lu-cib"/>
                        <constraint firstItem="KHT-Tm-0Sw" firstAttribute="centerX" secondItem="XYd-b4-iN3" secondAttribute="centerX" id="DHD-BE-uLP"/>
                        <constraint firstItem="KHT-Tm-0Sw" firstAttribute="top" secondItem="XYd-b4-iN3" secondAttribute="bottom" constant="8" symbolic="YES" id="Mfb-X2-i3d"/>
                        <constraint firstItem="XYd-b4-iN3" firstAttribute="centerX" secondItem="dve-Qr-cm1" secondAttribute="centerX" id="UY9-eH-ABh"/>
                    </constraints>
                </view>
                <connections>
                    <outlet property="hideButton" destination="XYd-b4-iN3" id="uLV-9H-ZwF"/>
                </connections>
            </viewController>
            <placeholder placeholderIdentifier="IBFirstResponder" id="taE-x0-pMJ" userLabel="First Responder" sceneMemberID="firstResponder"/>
        </objects>
        <point key="canvasLocation" x="1525" y="376"/>
    </scene>
    <!--Navigation Controller-->
    <scene sceneID="g8h-An-4td">
        <objects>
            <navigationController automaticallyAdjustsScrollViewInsets="NO" id="T9D-e2-4rQ" sceneMemberID="viewController">
                <toolbarItems/>
                <navigationBar key="navigationBar" contentMode="scaleToFill" id="8Zu-zN-61c">
                    <rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
                    <autoresizingMask key="autoresizingMask"/>
                </navigationBar>
                <nil name="viewControllers"/>
                <connections>
                    <segue destination="3W3-SS-KDU" kind="relationship" relationship="rootViewController" id="P8d-UH-2I1"/>
                </connections>
            </navigationController>
            <placeholder placeholderIdentifier="IBFirstResponder" id="8cC-0q-iMj" userLabel="First Responder" sceneMemberID="firstResponder"/>
        </objects>
        <point key="canvasLocation" x="53" y="375"/>
    </scene>
</scenes>
</document>


text:
Q: parent of parent of a .. of a file/folder in python is there a shorter way to find the path of the parent of the parent of the parent of a folder/file.
I am using :
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

A: You coud define a function for this
get_parent(path, n):
    path = os.path.abspath(path)
    for i in range(n):
        path = os.path.dirname(path)
    return path

Then just invoke that function
get_parent(path, 3)

It's much cleaner I think.

A: This should resolve the problem:
print os.path.abspath(os.path.join(__file__, os.pardir))

A: This is only slightly shorter (if at all).
print os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))

A: if you mean 'shorter' as in literally less characters, then you can import diffrerently:
from os.path import dirname, abspath

dirname(dirname(dirname(abspath(__file__))))

If what you really want is to make it more readable and less likely to be incorrect, write a helper method like @laike9m says, or define constants to important directories from some known base path and use those around your project instead.


text:
Q: How to get a static tmap with shiny as show in rstudio? I'm learning shiny and tmap.
I'm able to get the map I want on Rstudio (a static tmap).
But when I try a similar tmap code with shiny, I always get an interactive map.
From this reprex, I try to get the same map I get on Rstudio.
I try to add tmap_mode("plot") after the renderTmap, but it doesn't work.

My question look too simple... but can't find the answer!
Thank for your help.
library(shiny)

data(World)
world_vars <- setdiff(names(World), c("iso_a3", "name", "sovereignt", "geometry"))

ui <- fluidPage(
  tmapOutput("map"),
  selectInput("var", "Variable", world_vars)
)

server <- function(input, output, session) {
  output$map <- renderTmap({
    tmap_mode("plot")
    tm_shape(World) +
      tm_polygons(world_vars[1], zindex = 401)
  })
}

shinyApp(ui, server)

A: tmap_mode() doesn't work inside Shiny for me either, but there's actually a very easy alternative: instead of tmapOutput and renderTmap for interactive maps, you can just use plotOutput and renderPlot.
So the following code creates the exact map from your image and lets the user select a variable to plot:
library(shiny)
library(tmap)

data(World)
world_vars <- setdiff(names(World), c("iso_a3", "name", "sovereignt", "geometry"))

ui <- fluidPage(
  plotOutput("map"),
  selectInput("var", "Variable", world_vars)
)

server <- function(input, output, session) {
  output$map <- renderPlot({
    tm_shape(World) +
      tm_polygons(input$var)
  })
}

shinyApp(ui, server)


text:
Q: How to pass value from custom directive to custom filter? I have a list and want it to filter by my custom filter. But the value to it I want to put from custom directive with it's own scope. How to do it?
Body:

Here is my custom filter:
 .filter('myfilter', function(){
         return function(array, num){
                return array.slice(num, num+1);
         }
})

And here is my custom directive:
 .directive('mydirective', function() {

        return {
            restrict: "E",
            template:"<input ng-model='counter'><button ng-click='getIt(counter)'>PRESS</button>",
            scope:{
                item: '='
            },
            link: function(scope, element, attr){

                scope.getIt = function(counter){
                console.log(counter);
                }
            }
        }
    })

Please see the Example:
JsFiddle Example
P.S. I guess I've already found a solution using "scope.$parent" . But is there a possibility to pass the value straight to a "myfilter: here? "

A: Here it is.

{{num}}

        <mydirective item="list.length" filter-value="howToPutHereFromDirective"></mydirective>

function forExampleController($scope){
  $scope.list = [1,2,3,4,5,6,7,8,9];

    $scope.howToPutHereFromDirective = 3;
}

angular.module('hello', [])
     .filter('myfilter', function(){
         return function(array, num){

             return array.slice(num, num+1);

         }
})
     .directive('mydirective', function() {

        return {
            restrict: "E",
            template:"<input ng-model='counter'><button ng-click='getIt()'>PRESS</button>",
            scope:{
                item: '=',
                filterValue: '='
            },
            link: function(scope, element, attr){

                scope.getIt = function(){
                    scope.filterValue = parseInt(scope.counter);
                }

            }
        }
    });

Doing scope.$parent within isolated scope isn't too good indeed, because the objective of isolated scope is exactly the opposite.
I'm not sure what purpose item="list.length" two-way binding has to serve, but it is a bad idea.


text:
Q: Parse input fields as a Array list to controller via @RequestMapping I want to submit all textfields and radiobuttons from my input fields as an ArrayList and parse it to the controller but I don't know really how.
Any help is really appreciated.
Here's what I tried so far:
@RequestMapping(value = "/formdata", method = RequestMethod.POST)
public String formdata(HttpServletRequest req, @AuthenticationPrincipal User currentUser,
                       @ModelAttribute RegDatas regDatas, Model model) {
    // get values as regDatas[0]?
}

Here's my HTML form:
<form method="post" th:action="@{/formdata}" th:object="${regDatas}">

    <input th:field="*{regDatas[0].gender}" type="radio" value="MALE" name="gender" disabled="disabled" />Mr
    <input th:field="*{regDatas[0].gender}" type="radio" value="FEMALE" name="gender" disabled="disabled"/>Frau

Firstname:

    <input required="required" type="text"  th:field="*{regDatas[0].firstname}" placeholder="Max" disabled="disabled" />

    <input th:field="*{regDatas[1].gender}" type="radio" value="MALE" name="gender" disabled="disabled" />Mr
    <input th:field="*{regDatas[1].gender}" type="radio" value="FEMALE" name="gender" disabled="disabled"/>Frau

Firstname:

    <input required="required" type="text"  th:field="*{regDatas[1].firstname}" placeholder="Max" disabled="disabled" />
    <button type="submit">Speichern</button>

</form>

My wrapper class:
public class RegDatas {

    private List<RegData> regDatas;

    public List<RegData> getRegDatas() {
        return regDatas;
    }

    public void setRegDatas(List<RegData> regDatas) {
        this.regDatas = regDatas;
    }

}

My class to store values:
public class RegData {

    private String email;
    private String firstname;
    private Gender gender;

    public String getEmail() {return email;}

    public void setEmail(String email) {this.email = email;}

    public String getFirstname() {return firstname;}

    public void setFirstname(String firstname) {this.firstname = firstname;}

    public Gender getGender() {return gender;}

    public void setGender(Gender gender) {this.gender = gender;}
}

This is the error I see if I run it like this:
org.springframework.beans.NotReadablePropertyException: Invalid property 'RegDatas[0]' of bean class [de.ciss.aag.model.domain.RegData]: Bean property 'RegDatas[0]' is not readable or has an invalid getter method

A: From your comments, I think the problem is that your model is not populated with a RegDatas object. This Baeldung tutorial - Getting Started with Forms in Spring MVC, particularly section 4 is probably a good resource, if you haven't already seen it, but I think you need something like this (from the tutorial) in your controller:
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
    return new ModelAndView("employeeHome", "employee", new Employee());
}

But you'll need to add a populated RegDatas instance to your model, instead of the employee, so as a very basic example, this seems to work for me, with your code. There are other ways of populating the model, that I'd recommend researching, but this is probably the most straightforward.
@RequestMapping("/your-page-endpoint")
public ModelAndView get() {
    return new ModelAndView("your-view-name", "regDatas", new RegDatas());
}


text:
Q: How to fix: device_list:270: no soundcard found (Ubuntu server 18.04)? I was trying to capture some audio using a usb microphone and I got the error message mentioned in the title.
here is the output some (hopefully relevant) commands:
arecord -l
arecord: device_list:270: no soundcards found...

ls /cat/asound*
ls: cannot access '/cat/asound*': No such file or directory

lspci -v
00:1b.0 Audio device: Intel Corporation 7 Series/C216 Chipset Family High Definition Audio Controller (rev 04)
Subsystem: Hewlett-Packard Company 7 Series/C216 Chipset Family High Definition Audio Controller
Flags: bus master, fast devsel, latency 0, IRQ 29
Memory at f7c30000 (64-bit, non-prefetchable) [size=16K]
Capabilities: <access denied>
Kernel driver in use: snd_hda_intel
Kernel modules: snd_hda_intel

I've tried to remove and install alsa again and when I run
sudo arecord -l

The output is:
**** List of CAPTURE Hardware Devices ****
card 0: PCH [HDA Intel PCH], device 0: ALC221 Analog [ALC221 Analog]
    Subdevices: 1/1
    Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 2: ALC221 Alt Analog [ALC221 Alt Analog]
    Subdevices: 1/1
    Subdevice #0: subdevice #0

I guess meaning Ubuntu is recognising my sound card. The ALSA Info script can be found here.
Any help would be greatly appreciated.

A: I had aplay: device_list:268: No sound card found... after using aplay l. Following the Ubuntu troubleshooting guide below, I installed apt install linux-generic and after reboot it found my soundcard from VirtualBox in Ubuntu Server 20.04 from ova.
https://help.ubuntu.com/community/SoundTroubleshooting


text:
Q: compile a swc in flash for use in flex, with a class written in flex OK,
It sounds complicated, but it's not. Here goes:
I want to use some assets ( buttons, etc. ) I'm creating in flash in a flex actionscript project. Since all my assets are bellow 10K, I'm not planning to load a swf ,wait until it's loaded and create the interface. I want to use a swc and just instance the clips I need. Also, I want my Button class to have some extra properties, and this is where the problem occurs.
If in the Linkage Properties in the Flash IDE I add a reference to a custom Button Class and trace a child of the Button MovieClip, I get the right trace. If then I create a Button, in the Main class in Flex, using the generated swc file and trace the same child of the Button MovieClip, I get null.
Why is that ? Is there anyway to get around this ? I've considered using the Flex Component Kit, but since I'm working on a simple actionscript project and I'm not using the Flex framework, I see no point in using the Component Kit at this point.
Thanks!

A: I think I got it.
My Button MovieClip was linking to a class in the the same src folder as the rest of my actionscript code in the Flex actionscript project. (The as3 classpath was set to "../", from the assets folder where the .fla file lives, one level up to src )
When Flash compiled, the class was found and I got in the .swc file. That is why I got the symbol traced from flash.
When Flex compiled, the class was found in the src directory, so a new version of the same class was compiled, although it already existed in the swc file. Since flex found the .as file, but wouldn't know I had it linked to a symbol in the Flash IDE ( I don't think it can do that ), Flex created its version of the class, but since no symbol was linked to that class, the child of Button I was tracing was null.
I guess using packages and keeping the fla linked classes separate so Flex wouldn't compile the same class twice.
The weird thing is I didn't get any warning or error, so I assumed everything was fine.
A quick and not so dirty workaround was to delete the physical Button class from the filesystem, so that Flash could generate it's version on compile time and have references to the children of the Button symbol. Then in Flex I cread a class that extends Button and added the code I needed. Since the generated class got compiled in the .swc file, Flex could see that and I had no problem extending.
That was it! Bob's you're uncle!
I assumes that what happens, I am not 100% sure. It's something my intuition takes for granted through observation, so I might be technically wrong.
If anyone has any correction they're welcome.

A: I'm not sure if I'm reading your question correctly but are you essestially wanting to embed an image/asset that is available from the start, insted of the image/assets being loaded once the app initilises?
If this is the case then check out this link. It explains how to embed any asset into an actionscript project. http://kennethsutherland.com/2009/04/21/why-flex-why-actionscript-why-flash/
Hope this is what your after.


text:
Q: Vscode extension error, java runtime could not be located on window subsystem for linux I have installed the java runtime in the window subsystem for Linux (Ubuntu), and the Vscode is installed on the windows 10 system.
I did not install java runtime in windows 10 system. When I use vscode to edit java, it usually pop up a notice says the "java runtime could not be located".
I have point the vscode "java.home" to the java jdk directory of window subsystem linux file folder, which is C:\\Users\\Myusername\\AppData\\Local\\Packages\\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\\LocalState\\rootfs\\usr\\lib\\jvm\\. In the folder, it has:

*

*java-8-openjdk-amd64 directory, and three files

*.java-1.8.0-openjdk-amd64.jinfo,

*default-java

*java-1.8.0-openjdk-amd64.

But however, the vscode still pop out the notice that the java.home variable defined in VS Code settings does not point to a JDK.
Can anyone let me know how to set up the vs code properly so that it can locate the JDK file in the window subsystem for Linux (WSL)?
Thanks in advance.

A: It won´t work like this because you are trying to use a jdk builded for linux on windows.
It is the same as if you download the jdk for linux and try to execute on windows.
As for the solution, unfortunately there is no solution right now.
However you can call your java and javac directly on terminal using WSL
wsl javac

You can´t point the java_home using wsl.
Maybe in the future the guys from Microsoft can make the trick. I hope so.


text:
Q: WKHTMLTOPDF configuration in a .NET 5 project I am using a wkhtmltopdf plugin in my .NET 5 MVC project and can't seem to find where to input the configuration.
In the docu it reads that I need to put the params into a command line, however I do not have the program installed and simply just use it in my project via dependency injection.
Here is the Solution Explorer in VS:
Project tree
I use the plugin this way:
Services config in Startup.cs
Inserting the commands into the cmd line in VS does nothing.
Aside from this, the plugin works like a charm!
Thank you for any hints. Cheers!

A: In .NET, you just need to do for example:
 ConvertOptions option = new();
 option.PageMargins.Bottom = 0;
 option.PageMargins.Top = 0;
 option.PageMargins.Left = 0;
 option.PageMargins.Right = 0;
 _generatePdf.SetConvertOptions(option);

To set the options.


text:
Q: Destructuring promise callback There is a promise in my code:
req.getValidationResult()
        .then(result => {
            let errors = result.array();
            if (errors.length) {
                return res.status(400).json({ errors: errors });
            }

            return next();
        });

I'd like to know is there any variants to destructure my 'result' variable on then call (something like .then({result.array(): errors} =>...) and not to make let errors = result.array(); assignment.

A: I believe it's impossible with the native promise. You can change this code a bit:
req.getValidationResult()
        .then(({array}) => array())
        .then(errors => {
            if (errors.length) {
                return res.status(400).json({ errors: errors });
            }
            return next();
        });

Or you can use bluebird. It has a call method:
req.getValidationResult()
        .call('array')
        .then(errors => {
            if (errors.length) {
                return res.status(400).json({ errors: errors });
            }
            return next();
        });

But in the case you need to cast your promise to Bluebird promise


text:
Q: Strategies to protect files inside the "uploads" folder in WordPress I am creating custom giftcard PDF's on a client's site and want to protect them from public access while still being able accessing in the backend. Blocking a specific directory via Apache's .htaccess or nginx' location block rules works fine but now how can I access the files in the backend?

A: Strategy #1
Use cryptic folder and file names
In this case you don't need to block the access to the PDF's via Nginx or Apache (except traversing the directories, but this should be turned on anyway). The path to the PDF's could look like this for example:
/wp-content/uploads/plugin-name/year-month-day/ndLr83nH06Vd63jnbm46Ghied7/giftcard-order-0815-item-8015.pdf
public function generatePDF(){
        (....)
        $upload_dir = ABSPATH . "wp-content/uploads/plugin-name/" . date( "Y-m-d" ) . "/" . $this->randomString(24);
        if ( ! file_exists( $upload_dir ) ) {
            mkdir( $upload_dir, 0775, true );
        }
        $path = $upload_dir . "/giftcard-order-$order_id-item-$item_id.pdf";
        //mpdf is the library I am using to generate custom PDF's
        $mpdf->Output( $path, \Mpdf\Output\Destination::FILE );

        return $path;
}

public function randomString( $length = 4 ) {
    $characters       = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen( $characters );
    $randomString     = '';
    for ( $i = 0; $i < $length; $i ++ ) {
        $randomString .= $characters[ rand( 0, $charactersLength - 1 ) ];
    }

    return $randomString;
}

You can then simply use the path generated by the generatePDF() method to create an attachment for the giftcard post (post_type = shop_coupon in WooCommerce) and then access it through the media library.
public function attachPDF( $pdf_path, $shop_coupon_id, $order_id ) {

    $attachment = array(
        'post_title'  => "Giftcard PDF - Order #$order_id, Coupon #$shop_coupon_id",
        'post_status' => 'private',
        'post_parent' => $shop_coupon_id
    );
    $attach_id  = wp_insert_attachment( $attachment, $pdf_path );

    return $attach_id;

}

Now you only need to setup fail2ban on the server to protect your site from brute force attacks. Or you can use one of the WordPress security plugins (WordFence, WP Cerber etc).
Strategy #2
Deny access to files via Nginx/Apache rules
This strategy makes it very simple to block any unauthorized access to the files you want to protect. On the other hand it's now more difficult to program functions for accessing the files when needed. With this strategy you now can only access the files via PHP code. So if you want to open or download the files you will have to write custom frontend applications for this or use external plugins which offer such functionality.


text:
Q: Count Form Values Equal to 0 with jQuery $("#scorecard").change(function() {
    var total = 0;
    $("#scorecard :checked").each(

    function() {
        total += parseInt($(this).val())
    });
    $("#score").val(total);
}).change();

This function sums the radio checked values in a html form in real-time.
http://jsfiddle.net/hireconor/DDfbf/
How can I modify it, so it will count the checked radio values that are equal to 0? So if checked value is 0 then equals 1, anything else = 0 and sum then minus it by 18 displaying it in the text box with the id="score".

A: Here's a somewhat non-obvious approach:
var total = $('#scorecard :checked').filter(function() {
    return $(this).val() === '0';
}).length;

Here's an updated jsfiddle of it in action.

Edit: I wasn't sure exactly how to interpret minus it by 18... is that 18 - total or total - 18? Anyway, here's an updated fiddle showing the former.

A: Demo: http://jsfiddle.net/DDfbf/3/
$("#scorecard").change(function() {
    var total = 0;
    var checkedTotal = 0;

    $("#scorecard :checked").each(

    function() {
        total += parseInt($(this).val())
        if (this.value == 0) {
            checkedTotal++;
        }
    });
    $("#score").val(total);
    console.log(checkedTotal);
}).change();

A: Fiddle
 $("#scorecard").change(function() {
    var total = 0;
    $("#scorecard :checked").each(

    function() {
        var valu = parseInt($(this).val());
        if(valu === 0){
          total += 1;
        }
        else{
        total += valu;
        }
    });
    $("#score").val(18-total);
}).change();


text:
Q: Multiple bibliographies with bibtexall and LyX I want to know how to include this script
http://wiki.lyx.org/uploads/BibTeX/bibtexall in LyX in order to generate multiple bibliographies for a Master document and its child documents, each one of them having its own BibTeX generated bibliography.
In the above mentioned file there is the sentence "Place this file somewhere in your PATH" I want to know what's meant by "PATH" here?


text:
Q: To check whether given ring is principal ideal domain? Is $\mathbb{Z}_6[x]$ is principal ideal domain ?
no,
we know that polynomial ring $\mathbb{F}[x]$ is field iff $\mathbb{F}$ is field
here  $\mathbb{Z}_6$ is not field.
consider ideal $\langle{x,2}\rangle$ which is not principal ideal in $\mathbb{Z}_6[x]$ hence it is not PID.
please correct me if i am wrong.

A: $\mathbb{Z}_6[x]$ is not a principal ideal domain because it is not even a domain.


text:
Q: PhpStorm "empty path to php" when setting up project through Composer I am following along with a Laracast (https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/21?autoplay) and when I try to set up a new Laravel project using Composer, as taught in the tutorial, I am unable to complete the dialog due to an error message stating "Empty path to php".
I have the path to PHP set properly, and am able to run and debug through PhpStorm. If someone can help me understand what's going on here, I'd appreciate it. I have searched Google and only found one result, which was for Windows, not Mac. (https://devnet.jetbrains.com/thread/475384)

A: As you can see from your screenshot the "New Composer Project" screen does not have any option to select the PHP Interpreter that is required to actually launch composer (that's how PhpStorm works -- the same approach for all supported OS: Linux, Mac and Windows).
The workaround is to choose default PHP Interpreter in Default Settings (settings that would be used for any future new project created on this machine) -- this way you will have PHP Interpreter already pre-selected even for this kind of new project.
You need to use File | Default Settings to set such default PHP Interpreter there (well, that's on Windows/Linux -- on Mac it could be at some different location in menu). If you do not have any projects opened you still can access such Default Settings from Welcome screen.
Note: If you are still seeing same error after setting PHP Interpreter, then try restarting PhpStorm -- should help.

Note that In current 2016.x versions you can also specify what PHP Interpreter to use (and create new one if needed) at the bottom of this New Project screen -- it has Settings section which you can unfold -- just scroll the window down a bit to see it.


text:
Q: Shiny report : Trying to pass an input value as a parameter to an knit an .Rmd document but failing This simple Shiny app has a dropdown of various selectable options (selectInput), each of the options in selectInput have a .Rmd file matching its name. Based on the option selected through the dropdown I'm trying to call its respective .Rmd file, complete code below.
The eventReactive() method seems to get the selected value and is passed as an input to call the respective .Rmd file, however the code executes but does not generate the report.
Alternatively, commenting out eventReactive() and calling out the required .Rmd file as a variable (report_name) generates a downloadable report with the required content. How do I go about fixing this to get the desired functionality?
app.R
library(shiny)

ui <- fluidPage(
  selectInput("select_id",
              "Select an option",
              list(
                " "=" ",
                "apples"='apples',
                "oranges"='oranges')
  ),
  radioButtons('format', 'Document format', c('HTML', 'Word'),
               inline = TRUE),

  downloadButton('downloadReport')
)

server <- function(input, output, session) {

  # download of report selectable format based on button press
  output$downloadReport <- downloadHandler(
    filename = function() {
      paste('my-report', sep = '.', switch(
        input$format, PDF = 'pdf', HTML = 'html'
      ))
    },

    # get selected option from dropdown and use the input value as the name to call the Rmd file
    report_name <- eventReactive(input$select_id, {
      paste(input$select_id,'Rmd', sep =".")
    }),

    # replacing report_name() with report_name [below line] generates report, but is not the desired outcome
    # report_name <- "apples.Rmd",

    content = function(file) {
      cat('The selected fruit report is - - - :',report_name())

      src <- normalizePath(report_name())
      # temporarily switch to the temp dir, in case you do not have write
      # permission to the current working directory
      owd <- setwd(tempdir())
      on.exit(setwd(owd))
      file.copy(src, report_name(), overwrite = TRUE)

      out <- rmarkdown::render(report_name(),
                               switch(input$format,
                                      PDF = pdf_document(),
                                      HTML = html_document()
                               ))
      file.rename(out, file)
    }
  )
}

shinyApp(ui, server)

apples.Rmd
---
title: "This is a report for Apples"
output: html_document
params:
  tbl: NA
  include: NA
---

oranges.Rmd
---
title: "This is a report for Oranges"
output: html_document
params:
  tbl: NA
  include: NA
---

A: A few things to correct:

*

*report_name <- ... should be outside of the downloadHandler.

*You should likely not allow a download if input$select_id is the " " choice. For this, we require it to be something else.

*(Minor) You ::-reference render but not pdf_document, etc.

server <- function(input, output, session) {
  # get selected option from dropdown and use the input value as the name to call the Rmd file
  report_name <- eventReactive(input$select_id, {                       # MOVED
    req(input$select_id != " ")                                         # ADDED
    paste(input$select_id,'Rmd', sep =".")
  })

  # download of report selectable format based on button press
  output$downloadReport <- downloadHandler(
    filename = function() {
      paste('my-report', sep = '.', switch(
        input$format, PDF = 'pdf', HTML = 'html'
      ))
    },
    content = function(file) {
      req(nzchar(report_name()))                                        # ADDED
      cat('The selected fruit report is - - - :',report_name())

      src <- normalizePath(report_name())
      # temporarily switch to the temp dir, in case you do not have write
      # permission to the current working directory
      owd <- setwd(tempdir())
      on.exit(setwd(owd))
      file.copy(src, report_name(), overwrite = TRUE)

      out <- rmarkdown::render(report_name(),
                               switch(input$format,
                                      PDF = rmarkdown::pdf_document(),  # CHANGED
                                      HTML = rmarkdown::html_document() # CHANGED
                               ))
      file.rename(out, file)
    }
  )
}

Follow-on notes:

*

*You might want to test for presence of the report name before trying to render it, to preempt path-related problems where the user may not see the relevant error message. (Or not, depending on how confident you are that paths are being handled correctly.)

*Your templates include params: but you are not passing anything in render(.). I'm assuming it was omitted here for brevity, but make sure you add params=... into the render call.

*Your input$select_id offers "HTML" and "Word", yet your switch statements look for PDF and HTML. The above works when html is selected, but you need to update your selectInput and switch statements to ensure all candidates are referenced correctly.


text:
Q: Exchange on-premise and requirements sets We're trying to determine if some of our customers could use our outlook add-in and we are finding it difficult to determine this information from the web page Outlook JavaScript API requirement sets Documentation
Our add-in uses requirements set 1.5. We have customers using Exchange 2013 and 2016 (on-premise) along with an exchange web portal to access their mailboxes. Is this the same as Outlook on the web or is this different?
Can a customer use Outlook on Android or iOS along with any email account (say gmail) without having to use Office 365? How do roaming settings work in this case?


text:
Q: How to parse a tree structure saved in an Excel file using Apache POI All,
Good Morning!
I have an excel file with data listed as the following, I'm trying to parse down using POI
A
    B
        C
            D1
            D2
        F
            G1
            G2
            G3
        M
            S1
    R
        T
    U
L
    X
        Y
            Z

is it possible to generate an output like the following
A
A-->B
A-->B-->C
A-->B-->C-->D1
A-->B-->C-->D2
A-->B-->F
A-->B-->F-->G1
A-->B-->F-->G2
A-->B-->F-->G3
A-->B-->M
A-->B-->M-->S1
A-->R
A-->R-->T
A-->U
L
L-->X
L-->X-->Y
L-->X-->Y-->Z

I have been trying from quite some time but havent figured out the logic
Thanks

A: Solution in Java, using Apache POI:
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ParseTreeDemo
{
    private static final int NUM_COLUMNS = 4;

    public static void main(String[] args)
    {

        try
        {
            FileInputStream file = new FileInputStream(new File("Test.xlsx"));

            XSSFWorkbook workbook = new XSSFWorkbook(file);
            XSSFSheet sheet = workbook.getSheetAt(0);

            // Use a column marker to save the 'farthest' column so far
            int currColMarker = -1;
            List<String> list = new ArrayList<>();

            //Iterate through each rows one by one
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext())
            {
                Row row = rowIterator.next();

                for(int currCol = 0; currCol < NUM_COLUMNS; currCol++)
                {
                    Cell cell = row.getCell(currCol);
                    if(cell == null)
                        continue;

                    if(cell.getCellType() == Cell.CELL_TYPE_STRING) {

                        if(currCol > currColMarker) {

                            // A farther column, simply append and
                            // update column marker
                            currColMarker = currCol;

                            list.add(cell.getStringCellValue());
                        }
                        else if (currCol == currColMarker) {

                            // At same level as column marker
                            // Remove old value at same level, before appending
                            list.remove(list.size() - 1);
                            list.add(cell.getStringCellValue());
                        }
                        else {

                            // At a 'nearer' column, remove those values beyond
                            // this level before appending
                            currColMarker = currCol;

                            list = list.subList(0, currCol);
                            list.add(cell.getStringCellValue());
                        }
                    }
                }

                // For displaying the current contents
                StringBuilder sb = new StringBuilder();
                for(String s : list) {
                    if(sb.length() != 0) {
                        sb.append("-->");
                    }
                    sb.append(s);
                }
                System.out.println(sb.toString());

            }
            file.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Output:
A
A-->B
A-->B-->C
A-->B-->C-->D1
A-->B-->C-->D2
A-->B-->F
A-->B-->F-->G1
A-->B-->F-->G2
A-->B-->F-->G3
A-->B-->M
A-->B-->M-->S1
A-->R
A-->R-->T
A-->U
L
L-->X
L-->X-->Y
L-->X-->Y-->Z

The idea:

*

*Use a 'column marker' to keep track of the active column

*If the new value is at a column, with a larger column value, append

*If it has the same column value, remove the last value, and append

*If it has a smaller column value, remove all current values beyond the new column value, before appending

Note: Test.xlsx contains the values as stated in the question.

A: If the listed data is in a variable called data, the following will work in Tcl:
proc merge {a b} {
    set res {}
    foreach ac [split $a {}] bc [split $b {}] {
        if {![string is space $ac] && [string is space -strict $bc]} {
            append res $ac
        } else {
            append res $bc
        }
    }
    set res
}

set current {}
foreach line [split [string trim $data] \n] {
    set current [merge $current [string trimright $line]]
    puts [join $current -->]
}

I originally went with a pseudo-stack approach, but it seemed simpler to "merge" each new line with the accumulated line (current) such that non-blank text in the new line would overwrite text in the accumulated line, and that the accumulated line would be truncated if the new line was shorter (after trimming off trailing whitespace from it).
Once I had the merged line, I could take advantage of the fact that (most) strings in Tcl are also lists, and print it as a string formed by joining the words using "-->" tokens.
Documentation: append, foreach, if, proc, puts, set, split, string


text:
Q: Access Denied eror in mySQL I am creating new connection in mySQL workbench but i gives me access denied error please tell me whats the mistake?

A: first ,you should you can connect the system server,maybe system port of 3306 was close;
second ,you should you login user_name was allow your ip of now,if db is reliease,refuse local to connect ;
third ,you need surr your password is true.

A: As the error says the user you used is not allowed to connection. There are usually 2 reasons for this problem (not counting typos):

*

*The user doesn't exist.

*The password is wrong.

Keep in mind that MySQL allows to specify a host from where a user can connect. That means firza@localhost, firza@127.0.0.1 and firza@% are 3 different users!


text:
Q: OpenCV to align images fails when ignoring orientation on gray scale conversion I am using Python and OpenCV to align images using the code found here.  This works fine except that OpenCV is honoring the EXIF image rotation values in the final output.  While the two images are aligned perfectly in the OpenCV viewer the saved image is rotated 180 degrees to the second image.   I am using QGIS to process the data and the OpenCV aligned image is rotated 180 degrees from the image it was aligned to.
Found that I can alter to code  to ignore the image rotation when first opening the images as shown below.
 im1 = cv2.imread(path_to_image_1, cv2.IMREAD_IGNORE_ORIENTATION)

 im1_gray = cv2.cvtColor(im1, cv2COLOR_BGR2GRAY)

This works fine but when I get the the next section of the code that converts the image to gray scale I get error message.
  File "/home/gerry/Python/GeotaggedImageFootprintsToShp/OpenCV_Image_Alignment.py", line 17, in <module>
  im1_gray = cv2.cvtColor(im1,cv2.COLOR_BGR2GRAY)

cv2.error: OpenCV(4.5.1) /tmp/pip-req-build-ms668fyv/opencv/modules/imgproc/src/color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function 'cv::impl:
{anonymous}::CvtHelper<VScn, VDcn, VDepth, sizePolicy>::CvtHelper(cv::InputArray, cv::OutputArray, int) [with VScn = cv::impl::{anonymous}::Set<3, 4>; VDcn = cv::impl::
{anonymous}::Set<1>; VDepth = cv::impl::{anonymous}::Set<0, 2, 5>; cv::impl::{anonymous}::SizePolicy sizePolicy = cv::impl::<unnamed>::NONE; cv::InputArray = const cv::_InputArray&; cv::OutputArray = const cv::_OutputArray&]'
> Invalid number of channels in input image:
> 'VScn::contains(scn)'
> where
> 'scn' is 1

How can I ignore image rotation in the final saved image and still convert the open image to gray scale?


text:
Q: Database schema-related problem I have a kind of theoretical question about databases. To make it more concrete I have thought up an example case.
Suppose I have a store with products. I have lots of different products. Not every product has the same applicable properties. For instance, I could define the size of a harddisk in gigabytes, but cannot use that same property on a CPU, simply because it does not apply. What I want is a database where I can add properties to products dynamically. The only thing I can come up with is the following:
One product table with an ID, a Name and a Description.
One properties table with an ID, Product_ID, Property and a Value.
This way I would potentially get a gigantic, I-suppose-not-so-efficient, table of properties. This has been bugging me for a long time now. Does anyone know a better solution to my problem?

A: This is actually moving towards Sixth Normal Form, it is just that people like you who do not have the academic or experiential background do not know the (a) name for it and (b) the rules and the caveats.  Such people have implemented what is commonly know as Entity-Attribute-Value or EAV.  If it is done properly, it is fine, and there are many thousands of medical system out there carrying diagnostic and dosage info in such tables.  If it is not, then it is one dog's breakfast to use and maintain.

*

*First make sure you have Product in true and full 5NF.

*Always use full Declarative Referential Integrity; CHECK constraints and RULES.

*Never put all that into one table with a VARCHAR() for Value.  Always use the correct (applicable) DataTypes.  That means you will have several tables, one each per DataType, and there is no loss of control or integrity.

*Likewise any Associative tables (where there is a multiple reference to another table [eg. Vendor] ) must be separate.

*

*I am providing a Data Model which has the full control discussed; it includes a simple catalogue which can be used for verification as well as navigation.  You need to add every CHECK Constraint and RULE to ensure that the data and referential Integrity is not lost.  That means, eg:

*

*for the CPUSpeed column, which is stored in ProductDecimal, CHECK that it is in the proper range of values

*for each sub-Product table CHECK that the DataType is correct for the ProductType-ColumnNo combination

*This structure is way better than most EAV, and not quite the full 6NF.
.

*Keep all the mandatory columns in Product; use the sub-Product tables for optional columns only.

*For each such (eg Product) table, you need to create a View (dotted line), which will construct the 5NF rows from the EAV/6NF tables.  You may have several Views: Product_CPU, Product_Disk.

*Do not update via the View.  Keep all your updates transactional, in a stored proc, and insert or update each of the columns (ie. the Product and sub-Product tables which are applicable, for each particular ProductType) together.

*Gigantic ? Commercial databases (not the freeware) have no problems with large tables or joins.  This is actually a very efficient structure, and allows very fast searches, because the tables are in fact column-oriented (not row-oriented).  If the population is gigantic, then it is gigantic, do your own arithmetic.

*You need one more table, a Lookup table for Property (or Attribute).  That is part of the catalogue, and based on ProductType
The better solution is to go for full, formal Sixth Normal Form.  Not necessary if you have only one or a few tables that require optional columns.
To be clear:

*

*Sixth Normal Form is The Row consists of the Primary Key and, at most, one Attribute.

*This is 6NF (for at least the Product table cluster), then Normalised again (Not in the Normal Form sense) by DataType, to reduce the no of tables (otherwise you would have one table per Attribute).

*This retains full Rdb control (FKs, constraints, etc); whereas the common EAV types don't bother with the DRI and control.

*This also has the rudiments of a catalogue.
Link to Product Cluster Data Model
Link to IDEF1X Notation for those who are unfamiliar with the Relational Modelling Standard.
Update
You might be interested in this ▶5NF 6NF Discussion◀.  I will write it up at some point.

A: Initially I'd have suggested you have a productproperty table to model the relationship between products and properties. This would allow you to associate many products with a particular property.
However, I'm not keen on the idea of having a value stored alongside each property as a 1:1. It might be best if you have a propertyvalue table that associates a property with a value. Then, you'd ditch the productproperty table in favour of having a richer productpropertyvalue table which could fully describe the relationship between a product, it's properties and their values.
Perhaps then you could have the following:
product => (ID (unique key), Name, Description)
property => (ID (unique key), Description)
propertyvalue => (ID (unique key), propertyID (foreign key), value)
productpropertyvalue => (ID (unique key), productID (foreign key), propertyValueID (foreign key))

Of course, property values could be complex rather than simple strings or integers, but hopefully this takes you in the right direction.


text:
Q: Can I save the files of all the installations I currently have so that I can install them on an entirely different computer? I know that many programs get installed with paticular hardware in mind, and once apt is used, it automatically selects the program for your hardware. Like the programs installed on a raspberry pi will be very different to ones installed on an x86 processor and I am sure there are many other things like this.
What I want to do is download as much as possible of ubuntu, updates, apps, as much as possible so that I can install them onto a non-wifi connected computer. I think wget would probably be best for this but not sure how to wget updates if thats a thing. Also, when using wget I would be scared of forgetting some dependencies that would normally be installed when apt gets called. This other computer would be absolutely nothing like the one
I am currently using, currently using blade stealth with intel 7200u and trying to install it on an AMD 2700, so drivers and such I would imagine would be an issue as well. Is this possible to do?

A: I have found the solution, in case anyone runs into the same question. Keryx is an open source program that does exactly this very easily. It is an older project but I have found it works flawlessly.


text:
Q: COCOS2d-js view hide by top and bottom bars on iPhone5 [Safari] Im developing full screen browser based game using cocos2d-js.It is working well.
When I test it on iPhone5 safari browser, Game cover by top and bottom bars.Image with top and bottom bars
How to remove this bars or how to set my game to current display area?


text:
Q: CAML query to locate specific SPFolder nested in document library tree It seems like searching with CAML and SPQuery doesn't work properly against custom metadata, when searching for SPFolders instead of files, or when searching for custom content types.  I've been using U2U to test a variety of queries, and just not getting anywhere.  The doc's aren't very complete on the topic, and google isn't helping either.
In one test, I'm trying to locate any SPFolders in the tree that are a specific custom content-type.  If I understand CAML correctly, this should work:
<Query>
    <Where>
        <Eq>
            <FieldRef Name='ContentType' />
            <Value Type='Text'>CustomTypeName</Value>
        </Eq>
    </Where>
</Query>

In another test, I'm trying to locate any SPFolder that has a custom metadata property set to a specific value.
<Query>
    <Where>
        <Eq>
            <FieldRef Name='CustomProp' />
            <Value Type='Text'>SpecificPropValue</Value>
        </Eq>
    </Where>
</Query>

In both cases, I'm setting the root for the search to a document library that contains folders, which contain folders, which contain folders (phew.)  Also, I'm setting the SPQuery to search recursively.
The folder I'm searching for a two steps down are the farthest down in the tree.  I don't want to iterate all the way in to manually locate the folders in question.
EDIT It might also be helpful to know that I'm using both SPList.GetItems with an SPQuery as an argument, and SPWeb.GetSiteData with an SPSiteDataQuery as an argument.  At the moment it appears that folders aren't included in the search-set for either of these queries.
Any help would be greatly appreciated.

A: After more research, I'm answering my own question.
Apparently the methods that I'm using to query don't return SPFolders as items in the result set.  Only list items are returned, basically just documents.
My fix was to execute a CAML query for all the documents with a certain metadata tag/value, and then using the parent folder of the first one as the representative folder for the set.  Works well enough for my needs.

A: Try adding SharePoint Manager and Stramit CAML Viewer to your toolset.
I have found both to be very important for figuring out CAML problems.


text:
Q: java.lang.IllegalArgumentException: Invalid format: "2018-08-24T��:��:��" is malformed at "��:��:��" The front end is sending the date with an invalid time format and I get this exception:

Caused by: java.lang.IllegalArgumentException: Invalid format:
  "2018-08-24T��:��:��" is malformed at "��:��:��"  at
  org.joda.time.format.DateTimeParserBucket.doParseMillis(DateTimeParserBucket.java:187)
    at
  org.joda.time.format.DateTimeFormatter.parseMillis(DateTimeFormatter.java:826)
    at
  org.joda.time.convert.StringConverter.getInstantMillis(StringConverter.java:65)
    at org.joda.time.base.BaseDateTime.(BaseDateTime.java:173)
  at org.joda.time.DateTime.(DateTime.java:257)

Basically I want to check if the timestamp has any malformed data. If yes, I want to set it to 0. For example the datetime is 2018-08-24T��:��:�� I want to set it to 2018-08-24T00:00:00

A: You are already half-way there.
try {
 .. your code that parses the FED input
} catch ( IllegalArgumentException e) {
 .. do further checking

Meaning: that exception is already giving you, well, an exception, when you received bad input from your source. In that case, you could a simply substring() or regex check on the incoming string. And if it goes "4digits dash 2 digits dash 2 digits" ... then you got a date, and can create a corresponding object manually, and fill in the time values to all 0 for example.