text:
Q: Convert Stream, _>> to Stream> Suppose I have a stream of Result<Vec>:
let v = Ok(vec![(), ()]);
let s = stream::once(future::ready(v));

How can I make s be the return value of a function with return type impl Stream<Item = Result<(), _>?

A: The best solution I have is to use flat_map, pattern match the Result, and boxed the streams.
fn units() -> impl TryStream<Ok = (), Error = ()> {
  let v = Ok(vec![(), ()]);
  let s = stream::once(future::ready(v));
  s.flat_map(|x: Result<Vec<_>, _>| match x {
      Ok(x) => stream::iter(x).map(|x| Ok(x)).boxed(),
      Err(x) => stream::once(future::ready(Err(x))).boxed(),
  })
}

Edit:
See Jeff Garrett's comment for a non boxed solution.


text:
Q: Warp with Mongo DB Global Resource Injection I have set up a database connection but I want to share it with my warp API handlers.
my Cargo.toml
[package]
name = "mongo-warp"
version = "0.1.0"
edition = "2021"

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

[dependencies]
dotenv = "0.15.0"
mongodb = "2.2.2"
bson = { version = "2", features = ["chrono-0_4"] }
tokio = "1"
serde = "1"
warp = "0.3"
serde_json = "1.0"

and in main I have the database setup and working along with the routes that I'm importing from auth.rs
mod auth;

use dotenv;
use tokio;
use std::{env, error::Error};
use mongodb::{options::{ClientOptions}, Client, bson::doc};
use warp::Filter;

use crate::auth::auth_filter;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    dotenv::dotenv().ok();
    let client_uri = env::var("MONGODB_URI").expect("You must set the MONGODB_URI .env");
    let options = ClientOptions::parse(&client_uri).await?;
    let client = Client::with_options(options)?;

    // TODO: Do this bit in the join_handler
    let users = client.database("rusty_db").collection("users");
    let user = doc! { "password": "1984", "username": "GeorgeOrwell" };
    let insert_result = users.insert_one(user, None).await?;
    println!("New document ID: {}", insert_result.inserted_id);
    // End

    let apis = auth_filter();
    let welcome = warp::path::end().map(|| "Welcome to my api");

    let routes = apis.or(welcome);
    warp::serve(routes).run(([127, 0, 0, 1], 3000)).await;

    Ok(())
}

and finally, the route which is where I want to have access to the database with join_handler and signin_handler
use serde_json::{json, Value};
use warp::{Filter, reply::Json};

pub fn auth_filter() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
    let join = warp::path("join")
    .and(warp::get())
    .and(warp::path::end())
    .and_then(join_handler);

    let signin = warp::path("signin")
    .and(warp::post())
    .and(warp::body::json())
    .and_then(signin_handler);

    join.or(signin)
}

async fn join_handler() -> Result<Json, warp::Rejection> {
    let user = json!({"username":"GeorgeOrwell", "password": "1984", "id": "62a5108336aaebf431faa522"});
    let user = warp::reply::json(&user);
    Ok(user)
}

async fn signin_handler(data: Value) -> Result<Json, warp::Rejection> {
    let credentials = data;
    let credentials = warp::reply::json(&credentials);
    Ok(credentials)
}

A: I can't really test this without setting up a new database and everything, but if you move your Database client out to a lazy_static, then you can import it into your auth module and use it as if it were a local variable:
use dotenv;
use tokio;
use std::{env, error::Error};
use mongodb::{options::ClientOptions, Client, bson::doc};
use warp::Filter;
use lazy_static::lazy_static;

use crate::auth::auth_filter;

lazy_static! {
    static ref MONGO_DB: mongodb::Database = {
        tokio::runtime::Runtime::new().unwrap().block_on(async {
            Client::with_options(
                ClientOptions::parse(
                    env::var("MONGODB_URI").expect("You must set the MONGODB_URI .env")
                )
                .await
                .unwrap()
            )
            .unwrap()
            .database("rusty_db")
        })
    };
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    dotenv::dotenv().ok();

    let apis = auth_filter();
    let welcome = warp::path::end().map(|| "Welcome to my api");

    let routes = apis.or(welcome);
    warp::serve(routes).run(([127, 0, 0, 1], 3000)).await;

    Ok(())
}

mod auth {
    use mongodb::bson::doc;
    use serde_json::{json, Value};
    use warp::{Filter, reply::Json};
    use crate::MONGO_DB;

    pub fn auth_filter() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
        let join = warp::path("join")
        .and(warp::get())
        .and(warp::path::end())
        .and_then(join_handler);

        let signin = warp::path("signin")
        .and(warp::post())
        .and(warp::body::json())
        .and_then(signin_handler);

        join.or(signin)
    }

    async fn join_handler() -> Result<Json, warp::Rejection> {
        let users = MONGO_DB.collection("users");
        let user = doc! { "password": "1984", "username": "GeorgeOrwell" };
        let insert_result = users.insert_one(user, None).await.unwrap();
        println!("New document ID: {}", insert_result.inserted_id);

        let user = json!({"username":"GeorgeOrwell", "password": "1984", "id": "62a5108336aaebf431faa522"});
        let user = warp::reply::json(&user);
        Ok(user)
    }

    async fn signin_handler(data: Value) -> Result<Json, warp::Rejection> {
        let credentials = data;
        let credentials = warp::reply::json(&credentials);
        Ok(credentials)
    }
}

This way, the database connection is still in your main.rs, but it is not in main itself, which I think is the only part that you were missing when trying to use it in other modules. (I moved your auth module into the same file for testing, but you should be able to put it wherever you had it)

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# trim a certain argument Alright so I have this code and the issue is that when I use this, the findplayer argument is repeated in the text. I'm guessing it's because the text uses args which is all arguments which is a problem because i want the text to be multiple words.
var plr = player.Manager.FindPlayer(args[0]);
string text = string.Join(" ", args);
plr.Manager.Chat.Say(plr, text);

Any ideas to fix this? Thanks...

A: If you want to skip the first argument, you can do:
string text = string.Join(" ", args.Skip(1));


text:
Q: Override VF/Lightning standard action defined We are in the process of migrating to Lightning. In our current solution we use on some objects the Visualforce override to view/edit the object record. For Lightning I would like to switch back the default view/edit actions.
So I was hoping to make both solutions work. VF overrides in classic view, default lightning record page for Lightning Experience.
What I tried so far:

*

*Hoping for the  option to be available in the override section, not the case:

2. Creating a custom component (OpportunityRedirectTest) that uses lightning:navigation to navigate to the record id. But as expected, this just creates a loop.

A: Well the solution was quite easy (if you would know).
Just create a lighting record page (not the default one), and magiclly an extra option pops up that allows you the select the record page to use as an override.


text:
Q: how to remove upload image validation in Django? How can I remove this validation in django?
code in Django is like this:
image = models.ImageField(upload_to="data", null=True, blank=True)

A: If you set the field in a ModelForm, it will no longer be constructed by the corresponding model field, hence it will not take blank=True into account.
What you can do is only override the widget, so work with:
class SomeModelForm(forms.ModelForm):
    # no image = …

    class Meta:
        model = SomeModel
        fields = ['image', 'and', 'other', 'fields']
        widgets = {
            'image': forms.FileInput(attrs={'class': 'file-upload-input', 'id': 'file-selector'})
        }


text:
Q: dpkg: error processing package install-info I tried installing imagemagick package by
sudo apt-get install imagemagick
I'm getting the following error now, how to fix it.
$ sudo apt-get install imagemagick
Reading package lists... Done
Building dependency tree
Reading state information... Done
imagemagick is already the newest version (8:6.9.7.4+dfsg-16ubuntu2.3).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y
Setting up install-info (6.4.90.dfsg.1-1build1) ...
/usr/sbin/update-info-dir: 2: /etc/environment: TESSDATA_PREFIX: not found
dpkg: error processing package install-info (--configure):
 subprocess installed post-installation script returned error exit status 127
Errors were encountered while processing:
 install-info
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: sudo mv /var/lib/dpkg/info/install-info.postinst /var/lib/dpkg/info/install-info.postinst.bad

Fixed the problem.


text:
Q: Why is "wavelength" one word when "wave height" isn't? Why is "wavelength" one word when "wave height" isn't?
As another example, wave speed is two words. But wavelength is only one word.
What is the reason for this?
In Swedish and other contructs, both words are only one word:

*

*våglängd (wavelength)

*våghöjd (wave height)

A: The only full answer is "because it is". There are rarely complete answers to "why" questions in linguistics.
But a clearly relevant factor is that there is a need to talk about wavelength much more often than wave height, because wavelength is a property of all kinds of wave (including sound and electromagnetic radiation), whereas height is a property only of transverse waves in a physical medium, such as water.

A: Wavelength has been adopted as a term for a dimension (of measurement).
The other phrases have their respective terms (wave height: amplitude), as such they are separate individual words.

A: The reason that wavelength is only one word is that humans commonly form new words by combining existing words together. This is called compounding, and is observed over and over by linguists studying the evolution of languages.
The reason that the other terms you mention, "wave height" and "wave speed", have not compounded is that they are different from "wave length" in a significant way.
Online Etymology Dictionary tells us that the compound wavelength was coined in the 1840s when scientists began to explore the properties of light spectra (rainbow colors). As Kaz's answer points out, they needed a technical term for the "distance over which the wave's shape repeats". (Wikipedia)
However, a new word was not coined for light's "wave height" or intensity. Instead, the much older existing term amplitude was used. Nor was "wave speed" used for light's velocity: instead the term speed of light was adopted.
Those choices are just an accident of history. But the consequence is that "wave height" and "wave speed" did not gain currency in the 19th century explosion of literature on the subject of electromagnetic waves.
We can actually see compounding occurring in the chart below. Three similar terms – wave length (purple), wave-length (green), and wavelength (blue) – rapidly gained currency as scientific inquiry progressed. We see that before 1920 the term was almost always spelled using a hyphen or space. During the next three decades, the compound spelling wavelength gradually displaced the other spellings. By 1950 the majority of authors used the compound spelling.

A: Note that wavelength is a noncompositional compound. It does not refer to the length of a wave, but rather to the length of a single oscillation period of the wave: the reciprocal of the frequency. It is technical jargon which does not mean wave length.
Generally we write two words as one when they are used so often and in such a specific way, that the meaning is no longer just the combination of the meanings of the two words.
For example, a blackboard is not a black board. It is not just any board which is black but a tablet for writing with chalk, which may in fact be produced in colors other than black, such as green. Moreover, this is not just an orthographic (written) difference. The word blackboard is phonologically different from black board. It places accent on black and removes it from board.  There can be an accent on black in black board, but it is not integrated into the word. It is used for emphasis, as in "I said bring me the black board, not the white one!". The accent could also be on board: *"I said bring me the black board, not the black cord.".  In blackboard, there is no freedom to play with the relative stress.  An example which shows that this has nothing to do with orthography is (The) White House, which is is written as two capitalized words, yet it is phonetically a unit like blackboard.
Waveheight has not been coined as a technical term probably because English-speaking scientists and engineers adopted the term amplitude instead, which is as precise as wavelength. Amplitude is the degree of displacement of an oscillation from the system's rest position.
If waveheight referred to amplitude, it would be different from wave height, which does not have a clear meaning. Wave height could refer to amplitude, or it could be a peak-to-peak height, which is twice the amplitude. Or it could be something else: the height of shoaling as water waves hit shallow water.

A: The real answer to this question, in my opinion, is that to use the word height to describe a wave displays both a misunderstanding of the actual physical form of many waves and an incomplete understanding of the word height as it relates to mathematics.
First, most people think of waves in terms of the surface of water, or the readout of an oscilloscope, however many waves are not physically shaped like that.
Second, mathematically, height is the third dimension of measurement and it is perpendicular to the plane created by length and width. While a wave travels three-dimensionally, it doesn't actually have that kind of dimensionality, a wave as we measure it is shown to have dimensionality, because we prefer to perceive things as we are, not as they are, but a wave as it is, is actually just energy travelling.
As a quick aside, when I try to think of a wave as it is, I always come back to the word impulse, I kind of feel like that it the closest word we have to describe waves-as-energy-transfer that relates to an identifiable feeling we experience.


text:
Q: Interview: Top N integers in a List over a period of time I was recently asked a interview question to find Top N(10,20) integers in a List over a period of time. The List is dynamically added elements over a period of regular interval like 5 seconds. Could you please tell how to use the correct data structure and algorithm for this problem..

A: Such questions normally are not very sophisticated.
10 highest of last 20 entries: An ArrayList of at most 20 elements, adding at the end may remove one at the beginning. Then add them to a new SortedSet (like TreeSet), and take the first 10 on a reversed order. See @iced
If a Queue would fit, nice. (It does not entirely.) But the most important point is correctness. Seeing you cannot sort that ArrayList. That less than 10 top numbers may appear when many duplicates. Points for adding concurrency guards and such.

A: You can use Java Priority Queue/ Max heap.


text:
Q: Как разместить сайт в поддиректории url на локальном сервере? Есть в локалке сервер на убунте, имеет имя servername и есть на сервере апач, если зайти на servername, то можно увидеть, что апач работает.
Мне нужно, чтобы виртуальные хосты были доступны по url servername/sitename.
Вот такой код в site-available к этому не привел:
<VirtualHost *:80>
ServerName  servername/sitename
ServerAlias /sitename
DocumentRoot /var/www/sitename
<Directory /var/www/sitename>
    Options Indexes FollowSymlinks
    AllowOverride All
    Allow from all
    Require all granted
</Directory>

Если сделать вот так, то ожидаемо на servername вылазит сайтик.
<VirtualHost *:80>
ServerName  servername
DocumentRoot /var/www/sitename
<Directory /var/www/sitename>
    Options Indexes FollowSymlinks
    AllowOverride All
    Allow from all
    Require all granted
</Directory>

ЧЯДНТ?

A: Правильно ли я вас понял, что вы хотите доступ к сайту по URL http://servername/sitename ? Если да, то вам логичней было бы сделать
DocumentRoot /var/www/servername
<Directory /var/www/servername/sitename>
...
</Directory>


text:
Q: JFace add a Text box near a RadioGroupFieldEditor I try to add some preferences in the Eclipse menu and for that I create in JFace a RadioGroupFieldEditor section and near the last radio of the RadioGroupField, I want to have a text area, like in the picture below:

However I am not able to do this. I create a GridLayout with two columns, in one column I want the RadioGroupFieldEditor , in the other I want the text field. The text field is put below the RadioGroupField, not in the second column like I expect.
here is the code:
    protected Control createContents(Composite parent) {
    Composite fieldEditorParent = new Composite(parent, SWT.NULL);
    GridLayout layout = new GridLayout();
    layout.numColumns = 1;
    layout.marginHeight = 0;
    layout.marginWidth = 0;
    fieldEditorParent.setLayout(layout);
    fieldEditorParent.setFont(parent.getFont());

    createAGroup(fieldEditorParent);

    return fieldEditorParent;
  }

  private void createAGroup(Composite parent) {
    Group group = new Group(parent, SWT.NONE);
    group.setText("Group");
    GridLayout layout = new GridLayout();
    layout.numColumns = 1;
    group.setLayout(layout);

    GridData data = new GridData(GridData.FILL_HORIZONTAL);
    data.grabExcessHorizontalSpace = true;
    group.setLayoutData(data);

    GridLayout subLayout = new GridLayout();
    subLayout.numColumns = 3;

    Composite expertUserComposite1 = new Composite(group, SWT.NONE);
    expertUserComposite1.setLayout(subLayout);
    new Button(expertUserComposite1, SWT.RADIO | SWT.LEFT);
    new Label(expertUserComposite1, SWT.BEGINNING).setText("aaa");
    new Text(expertUserComposite1, SWT.BORDER);

    Composite expertUserComposite2 = new Composite(group, SWT.NONE);
    expertUserComposite2.setLayout(subLayout);
    new Button(expertUserComposite2, SWT.RADIO | SWT.LEFT);
    new Label(expertUserComposite2, SWT.BEGINNING).setText("bbb");

    Composite expertUserComposite3 = new Composite(group, SWT.NONE);
    expertUserComposite3.setLayout(subLayout);

    new RadioGroupFieldEditor(IExportCSVPreferences.DELIMITER_NAME_CURRENT,
        "RadioGroup", 1,
        new String[][] { { "line1", "line1" }, { "line2", "line2" }, { "line3", "line3" } },
        expertUserComposite3);
    new Text(expertUserComposite3, SWT.BORDER);

    Composite expertUserComposite4 = new Composite(group, SWT.NONE);
    expertUserComposite4.setLayout(subLayout);

    new RadioGroupFieldEditor(IExportCSVPreferences.DELIMITER_NAME_CURRENT, "RadioGroup", 1,
        new String[][] { { "line1", "line1" }, { "line2", "line2" }, { "line3", "line3" } }, expertUserComposite4,
        true);
    new Text(expertUserComposite4, SWT.BORDER);
  }

Here is the result:


text:
Q: Agent can't be in several flowcharts at the time. At least two flowchart blocks are in conflict: Suppose I have the following supply chain model see model model1

*

*Agents are communicating with each other through a defined network and send messages to each other through ports. for example, demand is generated for customers through their ports and send as "orders" upstream to facilities. Upstream facilities send "shipments" to downstream facilities
and stats are collected at each node.

*The model seems to work for 2 echelons but when one facility is connected to two facilities downstream as desired I get the following error "Agent can't be in several flowcharts at the time. At least two flowchart blocks are in conflict"  see error. Based on the description it seems the agent "shipment" is sent to two facilities at the same time.
My question is how could I avoid this conflict?
more information about each node:

*

*Agents' "orders" enter through each node's port and are capture as Enter. take(msg), follow a flowchart, and exit as Agent "shipment" to each destination. Each agent "order" has a double amount and port destination. see facility node
any suggestions please?

A: You must make sure that you do not send agents into a flowchart that is already in another flow chart, correct. This is bad model design.
One way to debug and find the root issue: before sending any message agent, check currentBlock()!=null and traceln the agent and the block. Also pause the model.
You can then see where you want to (re)send that agent that is already in some other flowchart block.
You probably send message agents out that are still somewhere else.
PS: For messages, you probably do not want to use flow charts at all but normal message passing. This avoids these pains here as you can easily send the same message to several agents. Check how message passing is done in the example agent models


text:
Q: Spring boot application not reading environment specific yaml file when running on external tomcat as war I am working on a Spring boot application which I am running on external Tomcat as a war packaging, passing the spring active environment during Tomcat startup using -Dspring.profiles.active which is being accepted by the Spring application(visible in logs) but when I am trying to read any properties defined in application-dev.yaml application is not able to read any of the properties defined in dev yaml.
I have setup external Tomcat and after building the war file I am placing it in tomcat and starting up the tomcat. In tomcat catalina.bat I have set the set "JAVA_OPTS=%JAVA_OPTS% -Dspring.profiles.active=dev".
Logs:
2019-07-21 17:16:50.472  INFO 26228 --- [ost-startStop-1] c.f.purge.PurgeServiceApplication        : Starting PurgeServiceApplication v1.0.0 on BLR-LT-101133 with PID 26228 (C:\Users\skumar8\Documents\Tomcat\apache-tomcat-8.5.41\webapps\purge-service\WEB-INF\classes started by SKumar8 in **C:\Users\skumar8\Documents\Tomcat\apache-tomcat-8.5.41\bin)
2019-07-21 17:16:50.481  INFO 26228 --- [ost-startStop-1] c.f.purge.PurgeServiceApplication        : The following profiles are active: dev**
2019-07-21 17:16:53.626  INFO 26228 --- [ost-startStop-1] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-21 17:16:53.715  INFO 26228 --- [ost-startStop-1] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 60ms. Found 0 repository interfaces.
2019-07-21 17:16:54.922  INFO 26228 --- [ost-startStop-1] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$ac299624] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-07-21 17:16:55.244  INFO 26228 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4652 ms
2019-07-21 17:16:58.855  INFO 26228 --- [ost-startStop-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
        name: default
        ...]
2019-07-21 17:16:59.223  INFO 26228 --- [ost-startStop-1] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.9.Final}
2019-07-21 17:16:59.228  INFO 26228 --- [ost-startStop-1] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-07-21 17:16:59.702  INFO 26228 --- [ost-startStop-1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-07-21 17:17:01.641  INFO 26228 --- [ost-startStop-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.InformixDialect
2019-07-21 17:17:01.779  INFO 26228 --- [ost-startStop-1] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
2019-07-21 17:17:02.556  INFO 26228 --- [ost-startStop-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-07-21 17:17:03.399  INFO 26228 --- [ost-startStop-1] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-21 17:17:03.609  WARN 26228 --- [ost-startStop-1] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-07-21 17:17:04.300  INFO 26228 --- [ost-startStop-1] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2019-07-21 17:17:04.397  INFO 26228 --- [ost-startStop-1] c.f.purge.PurgeServiceApplication        : Started PurgeServiceApplication in 15.37 seconds (JVM running for 61.826)
2019-07-21 17:16:50.472  INFO 26228 --- [ost-startStop-1] c.f.purge.PurgeServiceApplication        : Starting PurgeServiceApplication v1.0.0 on BLR-LT-101133 with PID 26228 (C:\Users\skumar8\Documents\Tomcat\apache-tomcat-8.5.41\webapps\purge-service\WEB-INF\classes started by SKumar8 in C:\Users\skumar8\Documents\Tomcat\apache-tomcat-8.5.41\bin)
2019-07-21 17:16:50.481  INFO 26228 --- [ost-startStop-1] c.f.purge.PurgeServiceApplication        : The following profiles are active: dev
2019-07-21 17:16:53.626  INFO 26228 --- [ost-startStop-1] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-07-21 17:16:53.715  INFO 26228 --- [ost-startStop-1] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 60ms. Found 0 repository interfaces.
2019-07-21 17:16:54.922  INFO 26228 --- [ost-startStop-1] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$ac299624] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-07-21 17:16:55.244  INFO 26228 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4652 ms
2019-07-21 17:16:58.855  INFO 26228 --- [ost-startStop-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
        name: default
        ...]
2019-07-21 17:16:59.223  INFO 26228 --- [ost-startStop-1] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.9.Final}
2019-07-21 17:16:59.228  INFO 26228 --- [ost-startStop-1] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-07-21 17:16:59.702  INFO 26228 --- [ost-startStop-1] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-07-21 17:17:01.641  INFO 26228 --- [ost-startStop-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.InformixDialect
2019-07-21 17:17:01.779  INFO 26228 --- [ost-startStop-1] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
2019-07-21 17:17:02.556  INFO 26228 --- [ost-startStop-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-07-21 17:17:03.399  INFO 26228 --- [ost-startStop-1] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-21 17:17:03.609  WARN 26228 --- [ost-startStop-1] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-07-21 17:17:04.300  INFO 26228 --- [ost-startStop-1] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2019-07-21 17:17:04.397  INFO 26228 --- [ost-startStop-1] c.f.purge.PurgeServiceApplication        : Started PurgeServiceApplication in 15.37 seconds (JVM running for 61.826)

**Properties defined in application-dev.yaml**
spring:
  cache:
    jcache:
      config: classpath:ehcache.xml
**Error log**
java.lang.IllegalArgumentException: Cannot find cache named 'akamaiSecretCache' for Builder

**Debug Option tried**

I do have tried with some simple one line property defined in application-dev.yaml but no luck with that also.

A: Could you confirm if the application-***.yml files are packaged in the war files generated?
You can simply extract the war file on your computer to check. If its not included, use this to include
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    <warName>${app.jvm}</warName>
    <webResources>
        <resource>
            <directory>${basedir}/src/main/resources/config</directory>
            <targetPath>WEB-INF</targetPath>
            <filtering>true</filtering>
        </resource>
    </webResources>
</configuration>
</plugin>


text:
Q: From time to time Ubuntu 16.04 left and top menu bars disappear and system freezes I have dual boot: Windows 10 and Ubuntu 16.04 on my Dell XPS 15 9550.
Sometimes while Ubuntu is running, left and top menu bars disappear and system freezes. Keyboard does not work, I can't run command line but mouse can still move. In this case I restart system by pushing power button.  I can't catch when this happens, it always happens suddenly. After exit from standby or log in everything works.

Any help and advice would be really appreciated. Thanks in advance!.


text:
Q: How to animate a CIFilter with CoreAnimation in iOS? I want to add a filter to a Layer using CABasicAnimation. I'd like to animate some properties of this filter. I read from documentation that the filters property is animatable, but in the same documentation, it seems to be really hard to find a way to do that!
So, how can I refer to a single filter property from a CABasicAnimation with animationWithKeyPath ?
[CABasicAnimation animationWithKeyPath:@"filters._FILTER_._PROPERTY_"];

This is a full example just to show you how I'm trying to get it working:
//Define the filter
CIFilter *filterOne = [CIFilter filterWithName:@"CISepiaTone"];
[filterOne setDefaults];

//Attach it to the Layer
self.layer.filters = [NSArray arrayWithObject:filterOne];

//HERE THE PROBLEM ---------------------------------------
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"filters.???????.inputIntensity"];
//EOF HERE THE PROBLEM -----------------------------------

//Define the Animation settings
animation.delegate = self;
animation.fromValue = [NSNumber numberWithInt:0];
animation.toValue = [NSNumber numberWithInt:1];
animation.duration = 0.3;
...etcetc...

A: I don't think the layer filters property works at all in iOS. There was a discussion about this recently in the Apple Core Animation forum on Apple's site, and an Apple engineer who goes by "Rincewind" posted that the layer filters feature is not implemented for iOS at all.
The documentation says:

iOS Note: While the CALayer class in iOS exposes the filters property,
  Core Image is not  available. Currently the filters available for this
  property are undefined.

As far as I know you can only use CI filters by calling them directly and getting back a CIImage as output. You then have to use the CIImage through code.


text:
Q: What to do when a bootable USB stick doesn't work properly? Currently I have Ubuntu 11.10 as an OS and I want Ubuntu 12.04 LTS. I made a bootable USB stick with the program Startup disk creator. Everything went well (I chose the language, and then I chose 'Install'), the purple screen with the title 'Ubuntu' came up and it started loading too.
After some time black screen came up with white letters. Last sentence was something like:

Panic occurred, switching back to text.

I tried it several times, the same thing happens. I tried clicking on Try Ubuntu from USB too but it didn't work either.

A: When you've downloaded an .iso image for Ubuntu and written it to a USB flash drive, and then you successfully boot it but experience problems during installation, the first things you should always do (if you haven't already) are:

*

*MD5 test the .iso image. (It can be corrupted during download or afterwards.)

*Check the USB flash drive for defects. (It can be corrupted during write or afterwards, or you could have bad hardware.)
Both the above steps apply to:

*

*all versions of Ubuntu

*both CD/DVD/Bluray and USB media

A: I've had similar problems before with defective USB keys. The best would be to download a new iso image from the Ubuntu site and use a different USB key.
Good luck!


text:
Q: Serial Fields in Informix for ORM framework We use a VERY old version of Informix (SE). I am trying to make an ORM type framework in C# to handle CRUD procedures. I am having a hard time trying to come up with a way of dealing with tables containing SERIAL fields.
Basically I would like to either somehow create a unique value that I can be reasonably sure will still be unique when I insert a record or at least get the value of a record I just inserted. This must work if many users are using the table at the same time (so a database wide scheme).
I know newer versions have 'sequence' objects that can be set up but SE does not.

A: FYI: Informix ODBC driver and .NET Driver do not officially support SE; it may still work though.
My knowledge about SE is limited too; the information that I list below may more relevant on IDS than SE.
The driver that you are trying is .NET Framework Data Provider for ODBC; it does not work well with Informix serial data type.
The Informix native .NET Provider has support for serial in IDS, but this driver has never been tested against SE. If you are willing to take risk then chance of getting success may be higher with this.
I don't think that you have to use any complex algorithm to make serial value unique at server.
The following example will explain it better.
    CREATE TABLE tab ( c1 SERIAL );
    INSERT INTO tab VALUES ( 0 );
    INSERT INTO tab VALUES ( 4 );
    INSERT INTO tab VALUES ( 0 );
    INSERT INTO tab VALUES ( 3 );
    INSERT INTO tab VALUES ( 3 );
    INSERT INTO tab VALUES ( 0 );
    SELECT * FROM tab;

     1
     4
     5
     3
     3
     6

DROP TABLE tab;
CREATE TABLE tab ( c1 INT, c2 SERIAL PRIMARY KEY );
INSERT INTO tab VALUES ( 11, 0 );
INSERT INTO tab VALUES ( 12, 0 );
INSERT INTO tab VALUES ( 13, 0 );
INSERT INTO tab VALUES ( 14, 0 );
INSERT INTO tab VALUES ( 15, 0 );
SELECT * FROM TAB;

c1          c2

11           1
12           2
13           3
14           4
15           5

If you are trying for a serial type value generated at client side such as entries added to DataTable etc then the following properties on DataColumn may be useful:
AutoIncrement,
AutoIncrementStep,
AutoIncrementSeed.


text:
Q: Java GUI shows blank until resize I have written a java gui code for many options available on it. the gui is also set visible true but it doesn't show until I pick its border and drag them to resize the gui window. After manually resizing it, it shows everything. Also, the textlabels and the textfields and buttons are not in new lines, they are placed one after one. Please tell me whats wrong with that: here is a part of code:
public static void initGUI(){
        JFrame fr = new JFrame();
        Container cont = fr.getContentPane();
        cont.setLayout( new FlowLayout( ) );
        FlowLayout layout = new FlowLayout();
        cont.setLayout(layout);
        frame.setSize(200,300) ;
        frame.setVisible(true) ;

        JTextField tName = new JTextField(30);
        JTextField tCNIC = new JTextField(15);

        JLabel nameLabel = new JLabel("Name:");
        JLabel cnicLabel = new JLabel("CNIC #:");

        cont.add(nameLabel);
        cont.add(tName);
        cont.add(cnicLabel);
        cont.add(tCNIC);

        JButton Cancel = new JButton ("Canel" );
        JButton OK = new JButton ("OK" );
        savebtn.setPreferredSize(new Dimension(150, 50));
        retbtn.setPreferredSize(new Dimension(150, 50));
        cont.add(savebtn);
        cont.add(retbtn);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

A: frame.setVisible(true) ;

The above statement should be invoked AFTER all the components have been added to the frame. So it should be the last statement in your method.
Also, you should be invoking:
frame.pack();

instead of setSize(), before making the frame visible so all the components are displayed at their preferred size.

A: frame.setVisible(true);

This Statement should be invoked in the last of adding other components to the Frame.


text:
Q: How does one design a database to be able to view state of data at any given place in time? Are there accepted best practices/database features to solve the general problem of being able to view/query the state of a system at any given point in time? To describe the problem, using the following canonical example:
Suppose you have a sequence of events that happen in time:

*

*Employees get hired

*Employees leave the company

*Employees get changes in pay

These events arrive as tuples:

*

*employee_id, first_name, start_name, pay, status = (hired|terminated|paychange)

If we want run descriptive statistics on the database that reflect the state of the organizations at a given point in time. Queries of the sort:

*

*select count(*) from employees

*select count(*) from employees where pay > 10000

*select median(pay) from employees

One way to solve this problem is to keep all the events in an employee_events table and then just build snapshot employee tables for each date you want to analyze by applying the event in chronological order up to the data in question.
Is there a standard / better approach to handle this design challenge?


text:
Q: sizeof aligned empty struct I found, that aligned empty struct have a size strictly equal to its alignment (live example):
#include <iostream>
#include <utility>

#include <cstdlib>

template< std::size_t i >
struct alignas(1 << i) aligned_storage
{

};

template< std::size_t ...I >
constexpr
void
test(std::index_sequence< I... >)
{
    static_assert(((sizeof(aligned_storage< I >) == (1 << I)) && ...));
}

int
main()
{
    test(std::make_index_sequence< 29 >{});
    return EXIT_SUCCESS;
}

Is it well formed code (especially placement news) (?):
#include <iostream>
#include <algorithm>

#include <cstdlib>

template< std::size_t argument, std::size_t base = 2, bool = (argument < base) >
constexpr std::size_t log = 1 + log< (argument / base), base >;

template< std::size_t argument, std::size_t base >
constexpr std::size_t log< argument, base, true > = 0;

template< typename ...types >
struct alignas(2 << std::max({log< sizeof(types) - 1 >...})) aligned_storage
{

};

struct A
{
    int j;
    A(int i) : j(i) { std::cout << j << ' ' << __PRETTY_FUNCTION__ << std::endl; }
    ~A() { std::cout << j << ' ' << __PRETTY_FUNCTION__ << std::endl; }
};

struct B
{
    short j;
    B(short i) : j(i) { std::cout << j << ' ' << __PRETTY_FUNCTION__ << std::endl; }
    ~B() { std::cout << j << ' ' << __PRETTY_FUNCTION__ << std::endl; }
};

int
main()
{
    aligned_storage< A, B > storage;
    auto a = ::new (&storage) A{1};
    a->~A();
    auto b = ::new (&storage) B{2};
    b->~B();
    return EXIT_SUCCESS;
}

Is it permittable in C++ to use above struct instead of std::aligned_storage_t?

A: http://en.cppreference.com/w/cpp/language/sizeof

When applied to a class type, the result is the size of an object of
that class plus any additional padding required to place such object
in an array.
When applied to an empty class type, always returns 1.

An equivalent interpretation is sizeof(type[N])==sizeof(type)*N is required by standard to be always true. This will cause the result of sizeof to be always the greater one of the actual memory representation size and the alignment.


text:
Q: Matlab choose linear direct sparse solver I need to solve a sparse linear system in Matalab using the QR solver of SuiteSparse. How can I choose it? I know that, depending on the matrix structure, the QR solver is used when calling the "\" operator. But I haven't find any way to directly use it. Is there any documentation?
Cheers

A: From Matlab manual, the least squares approximate solution to A*x = b can be found as:
      R = qr(A);
      x = R\(R'\(A'*b));
      r = b - A*x;
      e = R\(R'\(A'*r));
      x = x + e;


text:
Q: convert rows into columns - Bigquery I have a table like as shown below

As shown, I have two rows for the same subject. each row indicating a day
However, I wish to convert them into a single row like as shown below

Can you help? I did check this post but unable to translate it?

A:
I did check this post but unable to translate it?

Let's first transform your original data into form that we then can pivot
Below does this:
#standardSQL
SELECT subject_id, hm_id, icu_id, balance,
  DATE_DIFF(day, MIN(day) OVER(PARTITION BY subject_id, hm_id, icu_id), DAY) + 1 delta
FROM `project.dataset.table`
-- ORDER BY subject_id, hm_id, icu_id, delta

If to apply to sample data from your question - result is
Row subject_id  hm_id   icu_id  balance delta
1   124         ab      cd      2       1
2   124         ab      cd      5       2
3   321         xy      pq      -6      1
4   321         xy      pq      1       2

So, now we need to pivot this based on delta column - balance for delta = 1 will go to day_1_balance, balance for delta = 2 will go to day_2_balance and so on
Let's for now assume that there are just two deltas (as in your sample data). In this simplified case  - below will make a trick
#standardSQL
SELECT subject_id, hm_id, icu_id,
  MAX(IF(delta = 1, balance, NULL)) day_1_balance,
  MAX(IF(delta = 2, balance, NULL)) day_2_balance
FROM (
  SELECT subject_id, hm_id, icu_id, balance,
    DATE_DIFF(day, MIN(day) OVER(PARTITION BY subject_id, hm_id, icu_id), DAY) + 1 delta
  FROM `project.dataset.table`
)
GROUP BY subject_id, hm_id, icu_id
-- ORDER BY subject_id, hm_id, icu_id

with result
Row subject_id  hm_id   icu_id  day_1_balance   day_2_balance
1   124         ab      cd      2               5
2   321         xy      pq      -6              1

Obviously, in real case you don't know how many delta columns you have so you need to build above query dynamically - and that is exactly where post you referenced - will help you
You can try again by yourself - or see below for final solution
Step 1 - generating query
#standardSQL
WITH temp AS (
  SELECT subject_id, hm_id, icu_id, balance,
    DATE_DIFF(day, MIN(day) OVER(PARTITION BY subject_id, hm_id, icu_id), DAY) + 1 delta
  FROM `project.dataset.table`
)
SELECT CONCAT('SELECT subject_id, hm_id, icu_id,',
   STRING_AGG(
      CONCAT(' MAX(IF(delta = ',CAST(delta AS STRING),', balance, NULL)) as day_',CAST(delta AS STRING),'_balance')
   )
   ,' FROM temp GROUP BY subject_id, hm_id, icu_id ORDER BY subject_id, hm_id, icu_id')
FROM (
  SELECT delta
  FROM temp
  GROUP BY delta
  ORDER BY delta
)

Result of step 1 is the text that represent final query that you need to run as step 2
Step 2 - run generated query
#standardSQL
WITH temp AS (
  SELECT subject_id, hm_id, icu_id, balance,
    DATE_DIFF(day, MIN(day) OVER(PARTITION BY subject_id, hm_id, icu_id), DAY) + 1 delta
  FROM `project.dataset.table`
)
SELECT subject_id, hm_id, icu_id,
  MAX(IF(delta = 1, balance, NULL)) AS day_1_balance,
  MAX(IF(delta = 2, balance, NULL)) AS day_2_balance
FROM temp
GROUP BY subject_id, hm_id, icu_id
-- ORDER BY subject_id, hm_id, icu_id


text:
Q: Input incorrect Assembly x86 NASM I have been looking at this for hours and can't figure out why after my second input my string stored from the first input changes.
When I run sample run like this:
Please enter the id: 12
Please enter the name: jay
When I run this part of the code for just standard inputing and output gdb shows that id1Buf has value "12\n" after first read. Then it prompts to enter name so when I enter jay id1Buf value changes to "12\njay" for some reason. Cant figure it out, it would be great if someone could help.
SECTION .text                               ;.text section

global _start                               ;start section

_start:                                     ;start
    main:
        ;;write out
        mov eax, SYSCALL_WRITE              ;write function
        mov ebx, STDOUT                     ;write value
        mov ecx, id                         ;address of message
        mov edx, lenid                      ;length of message
        int 80h                             ;interrupt

        ;;read user input
        mov eax, SYSCALL_READ               ;read function
        mov ebx, STDIN                      ;read in value
        mov ecx, id1Buf                     ;store read value in id1Buf
        mov edx, IDBUFLEN                   ;length of idbuf
        int 80h                             ;interrupt

        ;;write out
        mov eax, SYSCALL_WRITE              ;write function
        mov ebx, STDOUT                     ;write value
        mov ecx, name                       ;address of message
        mov edx, lenname                    ;length of message
        int 80h                             ;interrupt

        ;;read user input
        mov eax, SYSCALL_READ               ;read function
        mov ebx, STDIN                      ;read in value
        mov ecx, name1Buf                   ;store read value in name1Buf
        mov edx, NAMEBUFLEN                 ;length of namebuf
        int 80h                             ;interrupt

        mov [name1readlen], eax             ;store length of name

This is some of the other code for reference.
;;constants
%define STDIN 0                             ;read function
%define STDOUT 1                            ;write function
%define STDERR 2                            ;error function
%define SYSCALL_EXIT 1                      ;exit
%define SYSCALL_READ 3                      ;read
%define SYSCALL_WRITE 4                     ;write
%define IDBUFLEN 3                          ;length of id buffer
%define NAMEBUFLEN 500                      ;length of name buffer

;;given data
SECTION .data
    id db "Please enter the id: "           ;prompt for id
    lenid equ $-id                          ;length of id prompt

    name db "Please enter the name: "       ;prompt for name
    lenname equ $-name                      ;length of name

    idlabel db "ID:    "                    ;used for printing end data
    lenidlabel equ $-idlabel                ;length of id label

    namelabel db "NAME: "                   ;used for printing end data
    lennamelabel equ $-namelabel            ;length of name label

    printline db "", 10                     ;new line character

;;unintialized data
SECTION .bss
    id1Buf:        resb IDBUFLEN             ;buffer for id 1
    name1Buf:      resb NAMEBUFLEN           ;buffer for name 1

A: Ahhh, let me make this an "answer" (although I'm not sure it is one). What you're seeing is expected behavior. You've got a three-byte buffer, you've filled it with '1', '2', and '\n'. Immediately following that you've got another (longer) buffer in which you put 'J', 'a', 'y', and '\n'.
Notice that sys_read terminates your input with a linefeed (\n), not a zero. It won't return until "enter" is hit. (this applies to STDIN - other files differ) You've got a bigger problem if the pesky user enters "12345(enter)", The first buffer will get '1', '2', '3' - it won't overflow - but after the "name" prompt, it won't pause but '4', '5', '\n' will be put into the name buffer. The solution is to make sure you have the linefeed!

; your sys_read
int 80h
push eax ; probably want to save the original length
checkLF:
cmp byte [ecx + eax - 1], LF
jz goodread
mov ecx, dummybuf ; to be thrown away
mov edx, 1
mov ebx, STDIN ; still in there, probably
mov eax, SYSCALL_READ
int 80h
jmp checkLF
goodread:
pop eax  ; get original length back

You may wish to zero-terminate the string(s). (maybe should have saved original ecx too) sys_write doesn't expect a zero-terminated string, but we can find the length and put it in edx.

mov ecx, buffer ; maybe a parameter?
xor edx, edx
getlen:
cmp byte [ecx + edx], 0
jz gotlen
inc edx
jmp getlen
gotlen:
; rest of your sys_read

You ask in a comment how to handle multiple inputs. I'd consider an array of pointers to name strings and an array of pointers to id strings. Possibly an array of lengths (for each?). Take small steps...

idarray dd id1buf, id2buf, id3buf, id4buf...
namearray dd name1buf, name2buf, name3buf...
; ...
mov edi, which customer we want
mov esi, [namearray + edi * 4]
; send it off for manipulating
inc edi ; next customer
; find his id?
mov ecx, [idarray + edi * 4]
; send it off to print

Something like that, maybe?


text:
Q: Notation for answer to basis of image (or kernel) problem? For a certain transformation T, I was suppose to find the basis for the image and kernel for T. My question is how you would state the answer to such a problem.
Is it okay to say that the basis for the ker(T) = {[v1], [v2], ...} and basis for the im(T) = {[v1], [v2], ...}?
Or do I have to specifically state that basis for the ker(T) = spans{[v1], [v2], ...} and likewise for the image?


text:
Q: How to extract list elements outside the loop? My code
import matplotlib.pyplot as plt

with open('spec.out') as infile:
    for line in infile:
        nums = [float(i) for i in line.split()]
        a1=nums[1]
        a2=nums[2]

plt.plot(a2,a1,'r--')
plt.xlabel('frequency')
plt.ylabel('MTM Spectrum value')
plt.show()

The problem is that a1 and a2 are not visible for plotting.How to solve this?

A: Try this:
import matplotlib.pyplot as plt

a1 = []
a2 = []
with open('spec.out') as infile:
    for line in infile:
        nums = [float(i) for i in line.split()]
        a1.append(nums[1])
        a2.append(nums[2])

plt.plot(a2,a1,'r--')
plt.xlabel('frequency')
plt.ylabel('MTM Spectrum value')
plt.show()


text:
Q: Blank parargraph HTML elements not shown Is there a way to get the browser to show a paragraph element even if it is empty?
I am finding that if a p element has no text in it then the browser doesn't show it.
I know that this is probably a good thing most times, but I am parsing & displaying HTML2 code from people who are using HTML badly(using blank p elements as vertical spacers instead of br elements) so I have a need to show these blank paragraph elements to get the display the same as on the users old version.
Is there a CSS setting or HTML setting that will make the browser draw/show blank paragraph elements? Maybe I need to set the HTML DTD?

A: Use min-height:1em. See http://jsfiddle.net/kcU5R/ for a demo.

A: If it has no text inside, the height of the element is set to ZERO. That is why it disapears. You will have to style it so that it occupies the space you intend, or add an   inside it.
You can set the min-height of the p element, to 1em, so that it has the height of one line of text.


text:
Q: Expect exception when using JUnit Theory In JUnit 4 you can declare expected exception using @Test(expected = SomeException.class) annotation. However, when testing is done using Theories, @Theory annotation does not have expected property.
What is the best way to declare expected exception when testing Theories?

A: I prefer using ExpectedException rule:
import org.junit.rules.ExpectedException;

<...>

@Rule
public ExpectedException thrown = ExpectedException.none();

@Theory
public void throwExceptionIfArgumentIsIllegal(Type type) throws Exception {
    assumeThat(type, equalTo(ILLEGAL));
    thrown.expect(IllegalArgumentException.class);
    //perform actions
}

A: Also you can use a normal assert.  You can use it on older versions of JUnit (before 4.9).
@Test
public void exceptionShouldIncludeAClearMessage() throws InvalidYearException {
    try {
        taxCalculator.calculateIncomeTax(50000, 2100);
        fail("calculateIncomeTax() should have thrown an exception.");
    } catch (InvalidYearException expected) {
        assertEquals(expected.getMessage(),
                     "No tax calculations available yet for the year 2100");
    }
}


text:
Q: validating and looping javascript I need to validate the user output for three different prompts and thought this would work but it is not.
The first prompt need to validate any of the 8 states and territories of Australia.
The second prompt needs to validate that the user has entered a whole number.
The third prompt needs to validate that the user has entered a negative or positive number that can be whole or has decimals.
Then the whole thing needs to loop over again so the three prompts can be asked again. So it can build a table.
        function ask() {
          var stInput = '';
          var populationInput = '';
          var changeInput = '';

          var entering = confirm('Confirm to add state or territory');
          if (!entering) {
            return;
            } else {
              while (true) {
                stInput = prompt('Enter state or territory');
                    function validateUserChoice(stInput) {
                if (stInput !== "Queensland" && stInput !== "New South Wales" && stInput !== "Victoria" && stInput !== "Tasmania" && stInput !== "Northern Territory" && stInput !== "Western Australia" && stInput !== "South Australia" && stInput !== "Australian Capital Territory") {

                   } else {
                    return false;
                   }
               }
                populationInput = prompt('Enter population for ' + stInput + '');

                while(!isValid(populationInput)) {
                alert('Your input was invalid');
                populationInput = parseInt(prompt('Enter population for ' + stInput + ''));
                }
                changeInput = prompt('Enter growth rate for ' + populationInput + '');

                while(!isValid(changeInput)) {
                alert('Your input was invalid');
                changeInput = parseFloat(prompt('Enter growth rate for ' + populationInput + ''));
                }
                    break;
                }
                 alert("invalid state or territory");
                }

A: I cannot speak to your larger problem, but I will tell you, any time I use a while loop, I always program in a fail safe.  I usually call them a safetyValve.  It keeps the system from being caught in an infinite loop and crashing.  It looks a little like:
var myCondition = true;
var safetyValve = 0;
var safetyMax = 10000;
while (myCondition && safetyValve < safetyMax) {
  ...
  safetyValve++;
}


text:
Q: SolrJ: Disable Autocommit We have an instance of Solr, where we've found that turning on autoCommit in the solrconfig.xml actually may serve our needs well.    However there are some instances and some batch operations where we want to temporarily disable autocommit.  I have not been able to find anything, but I'm wondering if anyone knew if via SolrJ you could disable autocommit for a certain process, and then re-enable it?

A: You can't disable and enable autocommit as it's configured in solrconfig.xml. However, you can leave it disabled in solrconfig.xml and use commitWithin for those add commands that need autocommit.

A: answering because this is the first result for "solr disable autocommit".
This is now possible with the new config API that allows to override some properties set in solrconfig.xml without reloading the core.
Solrj does not implement that new API yet.
You should not disable autocommits, see this article.
If you want to do a bulk indexing of many documents at once, set updateHandler.autoCommit.openSearcher=false and disable autoSoftCommits:
/**
 * Disables the autoSoftCommit feature.
 * Use {@link #reEnableAutoCommit()} to reenable.
 * @throws IOException network error.
 * @throws SolrServerException solr error.
 */
public void disableAutoSoftCommit() throws SolrServerException, IOException
{
   // Solrj does not support the config API yet.
   String command = "{\"set-property\": {" +
         "\"updateHandler.autoSoftCommit.maxDocs\": -1," +
         "\"updateHandler.autoSoftCommit.maxTime\": -1" +
   "}}";

   GenericSolrRequest rq = new GenericSolrRequest(SolrRequest.METHOD.POST, "/config", null);
   ContentStream content = new ContentStreamBase.StringStream(command);
   rq.setContentStreams(Collections.singleton(content));
   rq.process(solrClient);
}

/**
 * Undo {@link #disableAutoSoftCommit()}.
 * @throws IOException network error.
 * @throws SolrServerException solr error.
 */
public void reenableAutoSoftCommit() throws SolrServerException, IOException
{
   // Solrj does not support the config API yet.
   String command = "{\"unset-property\": [" +
         "\"updateHandler.autoSoftCommit.maxDocs\"," +
         "\"updateHandler.autoSoftCommit.maxTime\"" +
   "]}";

   GenericSolrRequest rq = new GenericSolrRequest(SolrRequest.METHOD.POST, "/config", null);
   ContentStream content = new ContentStreamBase.StringStream(command);
   rq.setContentStreams(Collections.singleton(content));
   rq.process(solrClient);
}

You can see the overriden properties at http://localhost:8983/solr/<core>/config/overlay


text:
Q: $A,B$ are two real positive matrices then $\det (A+B) > \max(\det A , \det B)$ Let $A,B$ two square-real-positive matrices. Prove that $\det (A+B) > \max(\det A , \det B)$
So I found this solution:
https://math.stackexchange.com/a/41478/160028
Basically, if $A=I_n$ and $B$ is diagonal then the proof is immediate.
Now, I know that if $M$ is positive-symmetric then:

*

*$M$ is conjugate to $I_n$.

*$M$ is conjugate to $\text{Diag}(c_1,\ldots,c_n)$ where $c_i > 0$.

but as far as I understand it doesn't have to be the same $P$. Anyhow, how do I utilize it in order to prove the inequality?
Thanks.

A: We can show that a satisfactory $P$ exists as follows:
First, suppose we only have $P^TAP = I$. Then apply the spectral theorem to find an orthogonal $U$ such that $U^T(P^TBP)U = D$ is diagonal.  We then have
$$
(PU)^T(A + B)(PU) = \\
U^T(P^TAP)U + U^T(P^TBP)U = \\
U^T(I)U + D =\\
I + D
$$
So, the new matrix $PU$ does the job.


text:
Q: Is it safe to pass validation result directly to new object I have set up the following Request class to validate my input:
.
.
.
class SupplierStoreRequest extends FormRequest
{
    .
    .
    .
    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'address' => 'required|string|max:255',
        ];
    }

}

And I have the following method in my controller:
public function store(SupplierStoreRequest $request)
{
    $validated = $request->validated();
    $supplier = new Supplier($validated);
    $supplier->save();
    return redirect()->route('Admin::supplier.index');
}

Which works exactly as expected. My question is:
Is there a risk of SQL or JavaScript injection, or any other security risks in this code or does the FormRequest class take care of that?

A: TL;DR Prepared statements through Eloquent and escaping with htmlspecialchars through blade variables is how you prevent SQL injections and JavaScript injections. Validation is just for checking if the user input is in the expected format (which can even be JavasScript or SQL on purpose).
If you use Eloquent (without raw) you use prepared statements, which help prevent SQL injections. Validation is not a part of this process and only is in place to check the validity of the input, not for attacks per se.

Laravel's database query builder provides a convenient, fluent
  interface to creating and running database queries. It can be used to
  perform most database operations in your application and works on all
  supported database systems.
The Laravel query builder uses PDO parameter binding to protect your
  application against SQL injection attacks. There is no need to clean
  strings being passed as bindings.

As for JavaScript injection, the same thing applies when using {{ $var }} statements in Blade files. You should not rely on validation for preventing attacks solely. It's really, really, really hard to prevent all forms of attack by validation.

Blade {{ }} statements are automatically sent through PHP's
  htmlspecialchars function to prevent XSS attacks.

https://laravel.com/docs/5.8/blade#displaying-data


text:
Q: how to decide the forecasting method from the ME, MAD, MSE, SDE? how to decide the forecasting method from the ME, MAD, MSE, SDE?
for example, there is 4 methods that will be decide.
but, the value won't be always greater or smaller among the error of each other.
so, how can I decide the method of that forecast methods?

A: This is better suited to stats.stackoverflow.com.
Don't use ME (mean error) as it doesn't measure accuracy, only bias.
Use MAD (mean absolute deviation) if you want forecasts that are the medians of the future distributions conditional on past observations.
Use MSE (mean squared error) if you want forecasts that are the means of the future distributions conditional on past observations.
SDE (standard deviation of errors) is just the square root of the MSE.


text:
Q: Excel VBA: How to append records from one worksheet to the last row of another worksheet I have code and it somewhat works. It does copy a worksheet from a workbook in a array of workbooks and then pastes the data to a master Workbook/Worksheet correctly. When it copies and pastes the another sheet to that master workbook/worksheet, it does find the last row and pastes that correctly. However, when it goes to the next workbook and sheet in the array, it copies the sheet okay, but does not paste it starting at the last empty row. Yes, I know this is simple, but not getting there.
If IsArray(FileArray) Then
   For i = LBound(FileArray) To UBound(FileArray)
      Set myBook = Workbooks.Open(FileArray(i))
      Sheets("Sheet1").Select
      Rows("1:4").Select
      Selection.Delete Shift:=xlUp
      For Each mySheet In myBook.Worksheets
        mySheet.Range("A1").CurrentRegion.Copy
        Basebook.Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1,
        0).PasteSpecial Paste:=xlPasteValues
      Next mySheet
      myBook.Close
   Next i


text:
Q: Nestjs Subscriber +TypeOrm Injection through yml files How can we inject connection dependencies of the subscriber with yml files .
my files are :
ormconfig.yml
default:
    type: 'postgres'
    host: 'localhost'
    port: 5432
    username: 'postgres'
    password: 'root'
    database: 'hiring_db'
    entities: ["dist/**/*.entity{.ts,.js}"]
    synchronize: true
    logging: ["query","error"]
    logger: "file"
    extra: { timezone: "+5:30" }
    migrations: ["src/migrations/*.ts"]
    cli:   {
        migrationDir: 'src/migrations'
    }
    subscribers: ["src/**/*.subscriber{.ts,.js}"]

JobPostingModule.ts
import { Module } from '@nestjs/common';
import { JobPostingController } from './job-posting.controller';
import { JobPostingService } from './job-posting.service';
import { AuthModule } from '../auth/auth.module';
import { RecruitmentService } from '../recruitment/recruitment.service';

@Module({
  imports: [
    AuthModule
  ],
  controllers: [JobPostingController],
  providers: [JobPostingService, RecruitmentService]
})
export class JobPostingModule {}

JobSubscriber.ts
import { Injectable } from '@nestjs/common';
import { InjectConnection } from '@nestjs/typeorm';
import { Jobs } from 'src/entities/job-posting.entity';
import { Connection, EntitySubscriberInterface, getConnection, InsertEvent, UpdateEvent } from 'typeorm';
import { JobPostingService } from './job-posting.service';

@Injectable()
export class JobSubscriber implements EntitySubscriberInterface {

  constructor(private readonly connection: Connection) {
    connection.subscribers.push(this); // <---- THIS

}

  listenTo() {
    return Jobs;
  }

  afterInsert(event: InsertEvent<Jobs>) {
    console.log('Hi guys!');
  };

  afterUpdate(event: UpdateEvent<any>) {
    console.log('Hi guys!');
  }

}

I am getting this error Nest can't resolve dependencies of the JobSubscriber (?). Please make sure that the argument Connection at index [0] is available in the AppModule context.
Potential solutions:
- If Connection is a provider, is it part of the current AppModule?
- If Connection is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing Connection */ ]
  })

A: do not use subscribers: ["src/**/*.subscriber{.ts,.js}"]
just add connection.subscribers.push(this); logic
and use the subscriber as a module Provider.

A: You can refer to the official NestJS documentation for this problem.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot(),
  ],
})
export class AppModule {}

Once you imported the TypeOrmModule you can use Connection as a provider everywhere.


text:
Q: How to annotate Map with JPA? I have this map:
Map<Owner, Integer> ownerSharesMap = new HashMap<>();

I know how to map a HashMap with @OneToMany relation that has a primitive type as key, but I googled a lot and didn't find a way to map the above HashMap with JPA.
I see two options though:
to change my HashMap to this: (in which the uuid is the key column of Owner)
Map<UUID, Integer> ownerIdSharesMap = new HashMap<>();

or
create a class like this :
public class Share{
  int count;
  Owner owner
}

then persist this Set:
Set<Share> shares;

what do you suggest? is there a way to annotate first Map with JPA or should I use the later solutions?
Note that in my project, querying performance is the main concern but I want clean OOD too.
Thanks.

A: This is possible in JPA.
The values in your map collection is not an entity, therefore you need to map it using @ElementCollection.
Your mapping can be simple as this:
@ElementCollection
private Map<Owner, Integer> ownerSharesMap = new HashMap<Owner, Integer>();

Although, you can specify a collection table where the values will be stored. Using @CollectionTable annotation you can specify the name of the collection table as well as the join column.
@ElementCollection
@CollectionTable(name="OWNER_SHARES",
    joinColumns=@JoinColumn(name="SHARE_ID"))
private Map<Owner, Integer> ownerSharesMap = new HashMap<Owner, Integer>();

If @CollectionTable is not specified, the table name will default to the name of the referencing entity, appended with an underscore and the name of the entity attribute that contains the element collection. In our example, this will be SHARE_OWNERSHARESMAP. The join column default is similarly the name of the referencing entity, appended with an underscore and the name of the primary key column of the entity table.
You can use @Column annotation, to specify which column in the collection table where the integer values of the map collection table. If not specified, this will default to OWNERSHARESMAP.
@ElementCollection
@CollectionTable(name = "OWNER_SHARES", joinColumns = @JoinColumn(name = "SHARE_ID") )
@Column(name="SHARE_AMOUNT")
private Map<Owner, Integer> ownerSharesMap = new HashMap<Owner, Integer>();

When keying by entity, not all properties of the entity will be stored in the collection table. It is only the primary key of the entity that will be stored. For this we will have an additional column in our collection table to store the key of your map, that is a foreign key to the Owner entity's primary key. To override the name of this column, you can use @MapKeyJoinColumn.
@ElementCollection
@CollectionTable(name="OWNER_SHARES", joinColumns=@JoinColumn(name="SHARE_ID"))
@Column(name="SHARE_AMOUNT")
@MapKeyJoinColumn(name="OWNER_KEY")
private Map<Owner, Integer> ownerSharesMap = new HashMap<Owner, Integer>();

If @MapKeyJoinColumn is not specified, then the default column name of will be the name of element collection attribute, appended with the string "_KEY". So in our example, this will be OWNERSHARESMAP_KEY.
Here's a sample of how your entities will look like in code:
@Entity
@Table(name="OWNER")
public class Owner {

    @Id
    @Column(name="OWNER_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer id;
...
}

@Entity
@Table(name = "SHARE")
public class Share {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "SHARE_ID")
    private Integer id;

    @ElementCollection
    @CollectionTable(name = "OWNER_SHARES", joinColumns = @JoinColumn(name = "SHARE_ID") )
    @Column(name="SHARE_AMOUNT")
    @MapKeyJoinColumn(name = "OWNER_KEY")
    private Map<Owner, Integer> ownerSharesMap = new HashMap<Owner, Integer>();
...
}

Here's a sample code persisting the entities and their collections:
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();

    Owner owner1 = new Owner();
    Owner owner2 = new Owner();

    em.persist(owner1);
    em.persist(owner2);

    Share share = new Share();
    share.getOwnerSharesMap().put(owner1, 20);
    share.getOwnerSharesMap().put(owner2, 40);

    em.persist(share);

    em.getTransaction().commit();

Here's how Hibernate generated the schema in MySQL:
Hibernate:
    create table OWNER (
        OWNER_ID integer not null auto_increment,
        primary key (OWNER_ID)
    )
Hibernate:
    create table OWNER_SHARES (
        SHARE_ID integer not null,
        SHARE_AMOUNT integer,
        OWNER_KEY integer not null,
        primary key (SHARE_ID, OWNER_KEY)
    )
Hibernate:
    create table SHARE (
        SHARE_ID integer not null auto_increment,
        primary key (SHARE_ID)
    )
Hibernate:
    alter table OWNER_SHARES
        add constraint FK_th03t34g0d8hj7hmhppaa9juk
        foreign key (OWNER_KEY)
        references OWNER (OWNER_ID)
Hibernate:
    alter table OWNER_SHARES
        add constraint FK_smwhicxpq0ydqan5jn1p3goom
        foreign key (SHARE_ID)
        references SHARE (SHARE_ID)

Here's how data will look like in your tables:

You'll see a sample of this implementation in my GitHub repo.


text:
Q: jQuery - Removing text from a string Markup looks like this....
<img id="holder" src="http://www.domain.com/images/title.size.jpg">

My jQuery looks like this....
var image = jQuery('img#holder').attr('src');

I get returned http://www.domain.com/images/title.size.jpg but really I just want http://www.domain.com/images/title.jpg. My question is.... What is the best way to remove everything from between the periods in the just the filename (and one period) so I am left with http://www.domain.com/images/title.jpg?
Recap:
just need JS that checks to see if there's more than one period after the last slash, and if so, finds the position of the first period after the slash and the position of the last period and removes the chunk in the middle.

A: I guess size is a number, not a string. If so, use this code:
var image = jQuery('img#holder').attr('src');
image = image.replace(/\.([0-9]+\.)/, '.');

With this code www.example.com/image.640.jpg becomes www.example.com/image.jpg.
If size is has a syntax like 640x480 use this (note the 'x'):
image = image.replace(/\.([0-9x]+\.)/, '.');

A: function removebetweendots(str)
{
    var arr = str.split("/");
    var filename = arr[arr.length-1];
    var n = filename.split(".").length;
    var newfilename;
    if(n>2)
        newfilename = filename.split(".")[0] +"."+ filename.split(".")[n-1];
    else
        newfilename = filename;
    arr[arr.length-1] = newfilename;
    return arr.join("/");
}

removebetweendots("http://www.domain.com/images/title.size.jpg");
// returns .. "http://www.domain.com/images/title.jpg"

removebetweendots("http://www.domain.com/images/title.size.moredata.jpg");
// returns .. "http://www.domain.com/images/title.jpg"

A: The answer is to use a regular, expression.
var getSize = new RegExp({},"");

{} needs to be whatever you want to match. I don't know if it is going to be .size. everytime or a number.

A: url = jQuery('img#holder').attr('src'); //the image url
url_parts = url.split('/'); //parts of url broken by '/'
extensions = url_parts.pop().split('.'); //extensions in url (last elements in url_parts broken by '.')

if(extensions.length > 2) //if more than two extensions
   url = url_parts.join('/')+'/'+extensions[0]+'.'+extensions.pop() //replace url by joined non extension parts of orignal url, /, first and last extension

alert("My filtered url: "+url)

Working http://jsfiddle.net/5jLbs/


text:
Q: Expansion around a singular point of a multivalued meromorphic function (due to Riemann/Cauchy) In Riemann's publication about Abelian functions
'Theorie der Abelschen Functionen' (Here the original paper in german)
at the end of Chapter 4, part 2 is clamed that for every Riemann
surface $T$ and $ a \in T$ every
meromorphic multivalued (?) function $f: T \to \hat{\mathbb{C}}$
with $f(a)= \infty$ can be locally expanded via
$$g + A \cdot \log \ r +B r^{-1}+ C r^{-2}+ \ldots $$
where $g$ is finite & continuous in $a$ (so 'nice' enough), the values $A, B, C,\ldots$ are appropriate complex coefficients and the function $r: T \to \mathbb{C}$ is the so called
infinitely small function of first order. In modern language of complex analysis this $r$ is nothing but the local parameter in $a$, that is
locally near a point $a \in T$ the function $r$ behaves
like $z$ near $0$ on the plane $\mathbb{C}$. So for sake of simplicity say $T= \mathbb{C}$ and $f: \mathbb{C} \to \hat{\mathbb{C}}$ is multivalued with $f(0)= \infty$.
Why locally $f$ can be always writen as
$$ g(z) + A \cdot \log \ z +B z^{-1}+ C z^{-2}+ \ldots $$
with $g(z)$ finite in $0$ and continuous?
Riemann wrote that this ensues from known theorems on expansions of functions in power series due to Cauchy.
Unfortunately I nowhere in literature found a result on this kind of expansion. Does anybody know it? Especially the presence of $\log z$ confuses me. In this expansion $\log z$
is the only term which is multivalued and the existence of such expansion near $0$ suggests that every kind of multivaluedness of a function with $f(0)= \infty$ can be 'absorbed' by $\log z$, that's strange and I never saw such result in any book.
From modern complex analysis it is known that there are for meromorphic
functions three kinds of singularities: the removable one, pole of finite order and the essential singularity.
And in any modern book on complex analysis no one of these
three kinds of singularities is associated with an expansion
containing the $\log z $ term. Does anybody know the ancient result by Cauchy to which Riemann refer here and has it a modern analogue?
Here the relevant translated excerpt from Riemann's paper:


text:
Q: overflow:scroll prevents slider gif from displaying I've added a floating gif with a slide out form to capture lead information. it works great but with lower resolution screen the form gets cut off so I though of adding a scroll bar. But when I add a scroll bar to the form the gif does not become visible.
Css being used
/*slide-out-div */
 .slide-out-div {overflow:scroll;padding: 20px;background: #ccc; border:1px solid black;width:250px;}

Html form
<div class="slide-out-div">

web site: www.dealerclick.com

A: The problem here, as I'm sure you know, is that you have the "handle" absolute positioned negatively to the right of the form container. So when you set overflow to auto (or scroll) as I assume you were, it will hide the handle.
This is not an error, it's the way css is supposed to work. Although there are a couple ways you can solve this, I think the best way is to add overflow: auto to .slide-out-div form so that only the form has the scroll bars (when you do this, you will see that your set width was too narrow as well).
Setting overflow to auto is the way to go here because setting overflow to scroll forces the scrollbars even when they are not necessary, which is not good ux practice.
This is all good and well, but the other problem here is that when you set overflow: auto and the page is not tall enough, since the div has a fixed position, it still won't work the way you want. So really the best way to take care of this issue is to use a little JS to detect window height, like this:
var window_height = window.innerHeight;
if (window_height < 668) {
   $('.slide-out-div form').css('overflow', 'scroll');
}

What this does is check if the window height is too small to display the full height of the form plus it's offset from the top (which on your page is 668px), and if so, adds the scroll bars. If not, no scroll bars and no problems.


text:
Q: How to set a variable containing a range-definition for selecting table columns in Matlab I want to set a range dynamically.  Say:
fromcol = 2;
tocol = 5; % or: = end;
nans = isnan(mytable{:,fromcol:tocol};

I want to dynamically construct a variating range to be used in the next line of code.  Can I set a single variable to hold the  "range" definition  (i.e. 2:5) and then use it?
For example:
myrange = { 2:5 };  % this does NOT work...
nansok = isnan(mytable{:,2:5};
nansfail = isnan(mytable{:,myrange}); % err: table variable subscripts must be etc. etc.

Is there a way to do it with one variable holding the "range definition"?

A: Don't use the braces, simply
myrange = 2:5;

This creates a vector [2 3 4 5] which can be used for indexing. See this MathWorks article on indexing for more information.

If you want to group the indices, you can use parentheses
% Exactly the same as `myrange = 2:5;` but allows for matrix ops like (2:5).' or (1:4) + 1
myrange = (2:5);

To concatenate vectors you can use square brackets, so...
% This is valid but not necessary
myrange = [2:5]; % >> [2 3 4 5]
% If you want to add non-continuous values, you could concatenate using
myrange = [2:4, 5]; % >> [2 3 4 5]

If your variable names are anything to go by, then you are indexing a table variable. If so, you can also index using a cell array of column names. i.e.
a = 1; b = 2; c = 3;
mytable = table(a, b, c);

myrange = {'b', 'c'};
mytable(:, myrange); % >> columns b and c containing 2 and 3


text:
Q: How to disable "print margin" in Geany Is there a way to disable the "print margin" in Geany? I don't know if it is called print margin in general, but at least in ace it is called like that.
Here's a screenshot:
Also I really don't know how it should be useful. To me it's just distracting.
I'm running it on Win 7 btw.

A: Is there a way to disable the "print margin" in Geany?
The "print margin" you refer to is called a "Long Line Marker".
To turn off the Long Line Marker:

*

*Go to "Preferences" > "Editor" > "Display" tab.

*Remove the check mark from Long line marker "Enabled".

*Click "OK".

What is the Long Line Marker?

The long line marker helps to indicate overly-long lines, or as a hint to the user for when to break the line.

*

*Line
      Show a thin vertical line in the editor window at the given column position.

*Background
      Change the background color of characters after the given column position to the color set below. (This is recommended over the
  Line setting if you use proportional fonts).

*Disabled
      Don't mark long lines at all.

*Long line marker
  Set this value to a value greater than zero to specify the column where it should appear.

*Long line marker color
  Set the color of the long line marker.

Source Long line marker

Further reading

*

*Geany User Manual


text:
Q: Mocking different log levels on Azure Function context with jest in javascript I have been playing around with testing my Azure Functions, but I am unable to mock the context log function.
For example I have the following Azure Function:
module.exports = async function (context, req) {
  if (req.query.isGood) {
    context.log("Goooood!!!")
    context.res = {
      body: {
        message: "This is good!"
      }
    };
  } else {
    context.log.error("Not gooood!!!")
    context.res = {
      status: 404,
      body: {
        message: "This is not good!"
      }
    };
  }
}

So I want to check the amount of times a certain log occured, for example 'log.error' occured once and 'log' occured twice, but I am unable to mock this.
I tried a couple of combinations like:
log: {
      "": jest.fn(),
      "error": jest.fn()
}

At this point I'm clueless on how to mock these functions, and am wondering if it is even possible? And how do you create these kind of functions?

A: In order to do this you need to create a closure function that is immediately invoked. Inside that function, create your default and then add to it the additional methods. In Typescript, you need to cast jest.fn() to the any type to get around type checking.
log: (function() {
    let main = <any>jest.fn((message) => message) ;

    let info = jest.fn((message) => message);
    main.info = info;

    return main;
})()

Once you are back in your test, this should then behave as expected:
test ('log test', () => {
    context.log("foo");
    context.log.info("bar");

    expect(context.log.mock.calls[0][0]).toEqual("foo");
    expect(context.log.info.mock.calls[0][0]).toEqual("bar");
});


text:
Q: How to share file for anyone Google Drive API using PHP I have been trying over and over, but could not reach any result.
the code is generating permission id and I don't know what that means.
Please do help if anyone succeeded in this before, I just want to share file publicly using the google drive api v2.0
$fileId = '18mWN0UWX_z-4A1gag85ou0Im-wvKfMZU-tibdVd8nxY';
$userPermission = new Google_Service_Drive_Permission(array(
    'type' => 'anyone',
    'role' => 'reader',
    'emailAddress' => 'user@example.com'
  ));

  $request = $service->permissions->create(
    $fileId, $userPermission, array('fields' => 'id'));
  $batch->add($request, 'user');
  $domainPermission = new Google_Service_Drive_Permission(array(
    'type' => 'domain',
    'role' => 'reader',
    'domain' => 'example.com'
  ));

  $request = $service->permissions->create(
    $fileId, $domainPermission, array('fields' => 'id'));
  $batch->add($request, 'domain');
  $results = $batch->execute();

  foreach ($results as $result) {
    if ($result instanceof Google_Service_Exception) {
      // Handle error
      printf($result);
    } else {
      printf("Permission ID: %s\n", $result->id);
    }
  }
} finally {
  $service->getClient()->setUseBatch(false);
}

A: Here is my code snippet which was 2 years old.
$uplodedOriginalFile = new Google_Service_Drive_DriveFile();
$originallinkdata = file_get_contents($downloadlink['originallink']);
$uploadedfile = $service->files->insert($uplodedOriginalFile, array(
              'data' => $originallinkdata,
              'uploadType' => 'multipart',
            ));

$newPermission = new Google_Service_Drive_Permission();
//$newPermission->setValue($value);
$newPermission->setType('anyone');
$newPermission->setRole('reader');
try
{
    $service->permissions->insert($uploadedfile['id'], $newPermission);
}
catch (Exception $e)
{
    print "An error occurred: " . $e->getMessage();
}

$publicOriginallink = "https://googledrive.com/host/".$uploadedfile['id'];

So you just need the inserted file Id and keep the permssion for anyone as  reader and append the inserted file Id after "https://googledrive.com/host/ [newly inserted file id which is returned by google drive sdk]"

A: code snippet worked
$fileid =$createdFile['id'];
//--insert permission to file in public
$newPermission = new Google_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
try
{$service->permissions->insert($fileid, $newPermission);}
catch (Exception $e){print "An error occurred: " . $e->getMessage();}
$publicOriginallink = "https://googledrive.com/host/".$fileid;

I just made few changes with Jai's code (Google_Permission) to match with my Google APIs Client Library version.


text:
Q: How to get the time elapsed from a json date? I am using jquery ajax($.ajax) method to get a json object from c# webmethod.This json object contains a datetime value, which looks something like this '/Date(1329324492302)/' and I tried to parse it using the following js
new Date(parseInt(json.d.Date.replace("/Date(", "").replace(")/",""), 10))

and the resulting date looks something like this
Date {Wed Feb 15 2012 16:48:12 GMT+0000 (GMT Standard Time)}
I want to find the time elapsed from this datetime to current time in javascript but I am not sure how to do it,as the parsed date looks like a string instead of a date.
Could someone please help.
Thanks

A: You could do:
//timestamp from json
var startTime = parseInt(json.d.Date.replace("/Date(", "").replace(")/",""), 10))
//current timestamp
var endTime = new Date().getTime();
//difference in milliseconds
var diff = endTime - startTime;

A: var json = {d:{Date:"/Date(1329324492302)/"}};

var date1 = new Date(parseInt(json.d.Date.replace("/Date(", "").replace(")/",""), 10));
var date2 = new Date();

var diff = (date2-date1);  //

var hours = Math.floor( diff / 3600000);
var minutes = Math.floor( (diff % 3600000) / 60000);
var seconds = Math.floor( ((diff % 3600000) % 60000) / 1000);

console.log(" elapsed " + hours + ":" + minutes + ":" + seconds );


text:
Q: XSLT1.0 Import java code as utils from web (github for example) Im wondering is it possible to include my java code from web into my xslt1.0 file.
Why I want to import java class from web? Because I dont have access to include util locally.
For Example (date is only example here, i wanna put some other code):
This one below works well.
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:date="xalan://java.util.Date"
  extension-element-prefixes="date">

  <xsl:template match="/" >
    <xsl:value-of select="date:new()"/>
  </xsl:template>
</xsl:stylesheet>

I want to achieve something like this below:
Import this java class below from github
import java.util.Date;

public class DateUtil {
    public static Date getDate(long time) {
    return new Date(time);
    }
}

into XSLT Stylesheet util
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:java="http://xml.apache.org/xslt/java">

    <xsl:template match="/" >
        <xsl:value-of select="java:DateUtil.getDate(1288652928119)"/>
    </xsl:template>
</xsl:stylesheet>


text:
Q: Error: file_get_contents() using from google maps to codeigniter Hi i have this google maps that when a user inputs his address will get the lattitude and longitude in the registration page. After when i input the address then click register i want that, the json in the google maps will get the lattitude and longitude then save to my database. Im using file_get_contents to get the maps for google i encountered some error saying Message: file_get_contents() [function.file-get-contents]: send of 68 bytes failed with errno=10053 An established connection was aborted by the software in your host machine.
Heres my code below
 $address = urlencode($this->input->post('address'));
          $request = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . $address . "&sensor=false");
          $json = json_decode($request, true);

          echo $json; exit;

why is that it will says Message: file_get_contents() [function.file-get-contents]: send of 68 bytes failed with errno=10053 An established connection was aborted by the software in your host machine.? How will i able to solve this? can someone help me figured this out?Any help is muchly appreciated.


text:
Q: Calculate the gradient for an histogram in c++ I calculated the histogram(a simple 1d array) for an 3D grayscale Image.
Now I would like to calculate the gradient for the this histogram at each point. So this would actually mean I have to calculate the gradient for a 1D function at certain points. However I do not have a function. So how can I calculate it with concrete x and y values?
For the sake of simplicity could you probably explain this to me on an example histogram - for example with the following values (x is the intensity, and y the frequency of this intensity):
x1 = 1; y1 = 3
x2 = 2; y2 = 6
x3 = 3; y3 = 8
x4 = 4; y4 = 5
x5 = 5; y5 = 9
x6 = 6; y6 = 12
x7 = 7; y7 = 5
x8 = 8; y8 = 3
x9 = 9; y9 = 5
x10 = 10; y10 = 2
I know that this is also a math problem, but since I need to solve it in c++ I though you could help me here.
Thank you for your advice
Marc

A: I think you can calculate your gradient using the same approach used in image border detection (which is a gradient calculus). If your histogram is in a vector you can calculate an approximation of the gradient as*:
for each point in the histogram compute
     gradient[x] = (hist[x+1] - hist[x])

This is a very simple way to do it, but I'm not sure if is the most accurate.

*

*approximation because you are working with discrete data instead of continuous

Edited:
Other operators will may emphasize small differences (small gradients will became more emphasized). Roberts algorithm derives from the derivative calculus:
lim delta -> 0 = f(x + delta) - f(x) / delta

delta tends infinitely to 0 (in order to avoid 0 division) but is never zero. As in computer's memory this is impossible, the smallest we can get of delta is 1 (because 1 is the smallest distance from to points in an image (or histogram)).
Substituting
lim delta -> 0 to lim delta -> 1

we get
f(x + 1) - f(x) / 1 = f(x + 1) - f(x) => vet[x+1] - vet[x]

A: *

*Take some squared paper and draw on it your histogram.  Draw also vertical and horizontal axes through the 0,0 point of your histogram.

*Take a straight edge and, at each point you are interested in, rotate the straight edge until it accords with your idea of what the gradient at that point is.  It is most important that you do this, your definition of gradient is the one you want.

*Once the straight edge is at the angle you desire draw a line at that angle.

*Drop perpendiculars from any 2 points on the line you just drew.  It will be easier to take the following step if the horizontal distance between the 2 points you choose is about 25% or more of the width of your histogram.  From the same 2 points draw horizontal lines to intersect the vertical axis of your histogram.

*Your lines now define an x-distance and a y-distance, ie the length of the horizontal/ vertical (respectively) axes marked out by their intersections with the perpendiculars/horizontal lines.  The gradient you want is the y-distance divided by the x-distance.
Now, to translate this into code is very straightforward, apart from step 2.  You have to define what the criteria are for determining what the gradient at any point on the histogram is.  Simple choices include:
a) at each point, set down your straight edge to pass through the point and the next one to its right;
b) at each point, set down your straight edge to pass through the point and the next one to its left;
c) at each point, set down your straight edge to pass through the point to the left and the point to the right.
You may want to investigate more complex choices such as fitting a curve (such as a quadratic or higher-order polynomial) through a number of points on your histogram and using the derivative of that to represent the gradient.
Until you understand the question on paper avoid coding in C++ or anything else.  Once you do understand it, coding should be trivial.

A: Two generally approaches here:

*

*a discrete approximation to the derivative

*take the real derivative of a fitted function

In the first case try:
g = (y_(i+1) - y_(i-1))/2*dx

at all the points except the ends, or one of
g_left-end  = (y_(i+1) - y_i)/dx
g_right-end = (y_i - y_(i-1))/dx

where dx is the spacing between x points. (Unlike the equally correct definition Andres suggested, this one is symmetric. Whether it matters or not depends on you use case.)
In the second case, fit a spline to your data[*], and ask the spline library the derivative at the point you want.
[*] Use a library! Do not implement this yourself unless this is a learning project. I'd use ROOT because I already have it on my machine, but it is a pretty heavy package just to get a spline...

Finally, if you data is noisy, you ma want to smooth it before doing slope detection. That was you avoid chasing the noise, and only look at large scale slopes.


text:
Q: Set source image of image control I programming for Windows Phone 8.1. I use this way to create image and set source of image:
Dim AgreeBitmapImage As BitmapImage = New BitmapImage()
AgreeBitmapImage.setsource(New Uri("Assets/Image/Agree.png", UriKind.Relative))
//Above line gives an error
imgAccept = New Image
imgAccept.Height = 40
imgAccept.Width = 40
imgAccept.Source = AgreeBitmapImage

When I start the emulator, it doesn't work. Why? (Say error)

A: In Windows Phone 8.1, the resources like png should be get using ms-appx:
AgreeBitmapImage.UriSource =
    New Uri("ms-appx:///Assets/Image/Agree.png", UriKind.Absolute)


text:
Q: can't get jQuery's ajaxComplete working I can't get jQuery's ajaxComplete to work.  I'm thinking it's because the ajax call is being initialised by Prototype?  But how can I check when any ajax call This is basically the code I have:
jQuery(document).ready(function() {

    function popupInit() {
        jQuery('.popup-window').click(function() {
            // rest of code here
        });
    }
    popupInit();
    jQuery(document).ajaxComplete(function(){
        console.log( "Triggered ajaxComplete handler." );
        popupInit();
    });
});

I checked in the Chrome sources panel and after an XHR response has finished my function is not called an neither is the console.log.
I'm not initiating the ajax call it's coming from a extension for our Magento website:
    new Ajax.Request(url, {
        method: 'post',
        onSuccess: function(transport)    {
        if(transport.status == 200)    {

            var data = transport.responseText.evalJSON();

            // Update shipment methods
            if(shipment_methods_found)  {
                shipment_methods.update(data.shipping_method);
            }

            if(update_payments){
                payment_methods.replace(data.payment_method);
            }

            totals.update(data.summary);

        }
    },
    onComplete: function(transport){
        if(transport.status == 200)    {
            if(shipment_methods_found)  {
                $$('dl.shipment-methods input').invoke('observe', 'click', get_separate_save_methods_function(set_methods_url, update_payments));
                $$('dl.shipment-methods input').invoke('observe', 'click', function() {
                    $$('div.onestepcheckout-shipment-method-error').each(function(item) {
                        new Effect.Fade(item);
                    });
                });
            }

            if(update_payments){
                $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', get_separate_save_methods_function(set_methods_url));

                $$('div.payment-methods input[name="payment\[method\]"]').invoke('observe', 'click', function() {
                    $$('div.onestepcheckout-payment-method-error').each(function(item) {
                        new Effect.Fade(item);
                    });
                });

                if($RF(form, 'payment[method]') != null)    {
                    try    {
                        var payment_method = $RF(form, 'payment[method]');
                        $('container_payment_method_' + payment_method).show();
                        $('payment_form_' + payment_method).show();
                    } catch(err)    {

                    }
                }
            }
        }
    },
    parameters: parameters
    });

*

*Is jQuery's ajax complete not working as the ajax request is being
initialised by prototype?

*How can I check with JavaScript when any
ajax response is complete?