text:
Q: Reverting a URL in Flask to the endpoint + arguments What would be the appropriate way of resolving a URL within Flask to retrieve a reference to the endpoint as well as a dictionary of all the arguments?
To provide an example, given this route, I'd like to resolve '/user/nick' to profile,{'username': 'nick'}:
@app.route('/user/<username>')
def profile(username): pass

From my research so far, all routes in Flask are stored under app.url_map. The map is an instance of werkzeug.routing.Map and it has a method match() that would in principle do what I am looking for. However, that method is internal to the class.

A: I know I am coming in late with an answer, but I ran into the same problem and found a simpler way to get it: request.view_args. For example:
In my views:
@app.route('/user/<username>')
def profile(username):
    return render_template("profile.html")

In profile.html:
    {{request.view_args}}
When visiting the url http://localhost:4999/user/sam, I get: {'username': u'sam'}.
You can also get the name of the function that got your view with request.endpoint.

A: This is what I hacked for this purpose looking at url_for() and reversing it:
from flask.globals import _app_ctx_stack, _request_ctx_stack
from werkzeug.urls import url_parse

def route_from(url, method = None):
    appctx = _app_ctx_stack.top
    reqctx = _request_ctx_stack.top
    if appctx is None:
        raise RuntimeError('Attempted to match a URL without the '
                           'application context being pushed. This has to be '
                           'executed when application context is available.')

    if reqctx is not None:
        url_adapter = reqctx.url_adapter
    else:
        url_adapter = appctx.url_adapter
        if url_adapter is None:
            raise RuntimeError('Application was not able to create a URL '
                               'adapter for request independent URL matching. '
                               'You might be able to fix this by setting '
                               'the SERVER_NAME config variable.')
    parsed_url = url_parse(url)
    if parsed_url.netloc is not "" and parsed_url.netloc != url_adapter.server_name:
        raise NotFound()
    return url_adapter.match(parsed_url.path, method)

The return value of this method is a tuple, with the first element being the endpoint name and the second a dictionary with the arguments.
I haven't tested it extensively, but it worked for me in all cases.

A: I rewrote Miguel's implementation to support subdomains:
from flask import current_app, request
from six.moves.urllib.parse import urlsplit

def endpoint_for(url, method=None, return_rule=False, follow_redirects=True):
    """
    Given an absolute URL, retrieve the matching endpoint name (or rule).
    Requires a current request context to determine runtime environment.

    :param str method: HTTP method to use (defaults to GET)
    :param bool return_rule: Return the URL rule instead of the endpoint name
    :param bool follow_redirects: Follow redirects to final endpoint
    :return: Endpoint name or URL rule, or `None` if not found
    """
    parsed_url = urlsplit(url)
    if not parsed_url.netloc:
        # We require an absolute URL
        return

    # Take the current runtime environment...
    environ = dict(request.environ)
    # ...but replace the HTTP host with the URL's host...
    environ['HTTP_HOST'] = parsed_url.netloc
    # ...and the path with the URL's path (after discounting the app path, if not hosted at root).
    environ['PATH_INFO'] = parsed_url.path[len(environ['SCRIPT_NAME']):]
    # Create a new request with this environment...
    url_request = current_app.request_class(environ)
    # ...and a URL adapter with the new request.
    url_adapter = current_app.create_url_adapter(url_request)

    # Domain or subdomain must match.
    # TODO: To support apps that host multiple domains, we need to remove this
    # check, or offer a callback hook to check the domain.
    if parsed_url.netloc != url_adapter.server_name and not (
            parsed_url.netloc.endswith('.' + url_adapter.server_name)):
        return

    try:
        endpoint_or_rule, view_args = url_adapter.match(parsed_url.path, method, return_rule=return_rule)
        return endpoint_or_rule
    except RequestRedirect as r:
        # A redirect typically implies `/folder` -> `/folder/`
        # This will not be a redirect response from a view, since the view isn't being called
        if follow_redirects:
            return endpoint_for(r.new_url, method=method, return_rule=return_rule, follow_redirects=follow_redirects)
    except HTTPException as e:
        pass
    # If we got here, no endpoint was found.


text:
Q: How can I make each scanf working without skip
I make the loop with gets and scanf. Actually I make the space for newline buffer. so I think each scanf works but when I input value to &books[ctr].cost compiler skip next 3 questions. I don't know why It work like this

books is structure variable
for (ctr = 0 ; ctr < 3 ; ctr++)
{
    printf("What is the name of the book #%d?\n", (ctr+1));
    gets(books[ctr].title);
    puts("Who is the author?  ");
    gets(books[ctr]. author);
    puts("How much did the book cost?  ");
    scanf("  $%f", &books[ctr].price);
    puts("How many pages in the book?  ");
    scanf("  %d", &books[ctr].pages);
    getchar( );
}
printf("\n\n Here is the collection of books : \n");
for (ctr = 0 ; ctr < 3 ; ctr ++)
{
    printf("#%d: %s by %s", (ctr+1), books[ctr].title, books[ctr].author);
    printf("\n It is %d pages and costs $%.2f", books[ctr].pages, books[ctr].price);
    printf("\n\n");
}

return 0;

}

A: First of all, two suggestions:

*

*Do not use gets() at all, it's dangerous and deprecated.

*Also, avoid using scanf() for direct user inputs, it's not worth it.

Use fgets() to take user input, and then convert to appropriate form using sscanf().

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sampling from a subset of a dataframe where the subset is conditional on a value from another dataframe in R I have two data frames in R. One contains a row for each individual person and the area they live in. E.g.
df1 = data.frame(Person_ID = seq(1,10,1), Area = c("A","A","A","B","B","C","D","A","D","C"))
The other data frame contains demographic information for each Area.
E.g. for gender df2 = data.frame(Area = c("A","A","B","B","C","C","D","D"), gender = c("M","F","M","F","M","F","M","F"), probability = c(0.4,0.6,0.55,0.45,0.6,0.4,0.5,0.5))
In df1 I want to create a gender column where for each row of df1 I sample a gender from the appropriate subset of df2.
For example, for row 1 of df1 I would sample a gender from df2 %>% filter(Area == "A")
The question is how do I do this for all rows without a for loop as in practice df1 could have up to 5 million rows?

A: Try using the following :
library(dplyr)
library(tidyr)

out <- df1 %>%
         nest(data = -Area) %>%
         left_join(df2, by = 'Area') %>%
         group_by(Area) %>%
         summarise(data = map(data, ~.x %>%
                                      mutate(gender = sample(gender, n(),
                                      prob = probability, replace = TRUE)))) %>%
         distinct(Area, .keep_all = TRUE) %>%
         unnest(data)

We first nest df1 and join it with df2 by Area. For each Area we sample gender value based on probability in df2 and unnest to get long dataframe.
There are not enough samples in df1 to verify the result but if we increase number of rows in df1 the proportion should be similar to probability in df2.


text:
Q: GridView. Не все вью полностью помещаются в ячейку Заполняю GridView адаптером из LinearLayout с двумя TextView и одним ImageView.
Адаптер:
class MySimpleAdapter extends SimpleAdapter {
        private Context context;
        private LayoutInflater inflater;
        private List<? extends Map<String, ?>> data;

        public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
            this.context = context;
            this.data = data;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (null == convertView) {
                convertView = inflater.inflate(R.layout.videoitem, parent, false);
            }
            ((TextView) convertView.findViewById(R.id.tvTimestamp)).setText((String)data.get(position).get("timestamp"));

            if (((String)data.get(position).get("imageurls")).equals("")) {
                Picasso
                        .get()
                        .load(R.drawable.standby)
                        .placeholder(R.drawable.standby)
                        .error(R.drawable.standby)
                        .into((ImageView) convertView.findViewById(R.id.imageView));
            }else{
                Picasso
                        .get()
                        .load((String)data.get(position).get("imageurls"))
                        .placeholder(R.drawable.standby)
                        .error(R.drawable.standby)
                        .into((ImageView) convertView.findViewById(R.id.imageView));
            }

            ((TextView) convertView.findViewById(R.id.tvCameraName)).setText((String)data.get(position).get("cameranames"));

            return convertView;
        }

    }

LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/llVideo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/colorBackgroundLight"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tvTimestamp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="14sp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true" />

    <TextView
        android:id="@+id/tvCameraName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="14sp" />
</LinearLayout>

Когда длина текста в каждой из ячеек строки примерно одинакова, то все выглядит отлично. Но если текст по длине сильно различается, то нижняя граница нижнего TextView либо не доходит до границы ячейки, либо наоборот вылезает за границу так, что не виден весь текст.
Мне кажется я уже перепробовал все возможные варианты layout_height как у TextView так и у LinearLayout, но ничего не помогло.
Есть ли решение этой проблемы?

A: Gridview не поддерживает разную высоту блоков. Вам нужно использовать recycler view и StaggeredGridLayoutManager


text:
Q: Which data type is arangodb storing auto-generated keys? can anybody tell me which data type is arangodb storing his auto-generated _key's?
Is it number or string?
If i store a "foreign key" in a document from a dataset of antoher document, is it better for querys to store it as string or number?
Greetings mok

A: The _key attribute in every collection is always supposed to be a string, and only string values will be stored in it.
So if your input data for _key is a number, it will be safest to convert it into a string first.


text:
Q: Defining derivation to simple field extension. Let $E=F[\alpha]$ be a proper extension of fields and $\alpha^{p^{n}}\in F$ for $p= \text{char}(F)$ and some integer $n > 0$. Show that there exists a $F$-derivation $\delta$ on $E$ for which $\delta(\alpha) = 1$.
Where an $F$-derivation is a linear (with respect to scalar multiplication from $F$) map $\delta:E\to E$ which obeys the product rule in $E$:
$$\delta(xy) = x\delta(y) + y \delta(x)$$.
The textbook gives a hint to define $\delta$ on the set $1,\alpha,\alpha^{2},\ldots,\alpha^{m-1}$ where $m$ is the degree of the extension. I see what to do for that, just the usual calculus derivative. This set forms a basis for $E$, so then extend by linearity to all of $E$. We then just have to check the product rule. I believe it just suffices to check that $\alpha^{k}=k\alpha^{k-1}$ for all $k$ (not just $k < m$). It seems like it should just be calculation, but I am struggling this way and I don't see where the assumption $\alpha^{p^{n}}\in F$ will be used.
This is from Martin Isaacs "Algebra: A Graduate Course".

A: I think I figured it out.
Notice that $m=p^{n}$, the extension $E$ is purely inseparable and the minimal polynomial of $\alpha$ is $x^{p^{n}}-\alpha^{p^{n}}$. Because $\delta$ is $0$ on $F$ we have
$$ \delta(\alpha^{p^{n}}) = 0 = p^{n}\alpha^{p^{n}-1} $$
as needed. For any $k$ we can write $k=qp^{n}+r$ with $0\leq r < p^{n}$ so that
$$\delta(\alpha^{k}) =\alpha^{qp^{n}}\delta(\alpha^{r}) = r\alpha^{qp^{n}+r-1} = k\alpha^{k-1} $$
because $r\cong k \mod p$


text:
Q: How to display the number of subroutines and their names in a perl script at the time of its execution? Consider the following Perl script script.pl as an example:
use strict;
use warnings;
sub f1
{statements}
sub f2
{statements}
sub f3
{statements}
f1();f2();f3();

When I execute the script, it should show the following output:
./script.pl

number of subroutines:3
  names of subroutines:f1 f2 f3

When the code is executed, how can I count the number of subroutines, get their names, and then print them during runtime?

A: You are looking for Devel::Symdump:
#!/usr/bin/env perl

use strict;
use warnings;

{
    require Devel::Symdump;
    my $sym = Devel::Symdump->new('main');
    my @subs = $sym->functions;
    printf "Number of subroutines: %d\n", scalar @subs;
    printf "Names of subroutines: %s\n", join(q{, } => map { s/^main:://; $_ } @subs);
}

sub f1 {
    # statements
}

sub f2 {
    # statements
}

sub f3 {
    # statements
}

f1();
f2();
f3();

Output:
Number of subroutines: 3
Names of subroutines: f2, f1, f3

A: Devel::Examine::Subs can do these types of things.
use strict;
use warnings;
use feature 'say';

use Devel::Examine::Subs;

my $des = Devel::Examine::Subs->new(file => $0);

my $subs = $des->objects;

say "number of subs:" . @$subs . "\n";

for my $sub (@$subs){
    say "name:  " . $sub->name;       # name of sub
    say "start: " . $sub->start;      # first line number of sub in file
    say "end: "   . $sub->end;        # last line number of sub in file
    say "lines: " . $sub->line_count; # number of lines in sub
    # $sub->code;                     # entire sub code from file
    # $sub->lines;                    # lines that match search term
    say "\n";
}

sub func1 {}
sub func2 {}
sub func3 {}

Output:
number of subs:3

name:  func3
start: 25
end: 25
lines: 1

name:  func2
start: 24
end: 24
lines: 1

name:  func1
start: 23
end: 23
lines: 1

A: I think the function you're looking for is caller:
#!/usr/bin/env perl
use strict;
use warnings;

sub test {

   my (
      $package, $filename,  $line,     $subroutine,
      $hasargs, $wantarray, $evaltext, $is_require,
      $hints,   $bitmask,   $hinthash
     )
     = caller(0);
   print "$subroutine called at $line of $filename\n";
}

test;

Note - without arguments, caller returns just package, filename and line. The number is a number of stack frames, in case you're nesting the subroutine.


text:
Q: How to trace an uninitialized signal in Chisel? We have a complex design and occasionally forget to initialize a signal.  Chisel assigns a random value.  But this makes it difficult to trace backwards from the point at which the error is detected, back to the origin.  There are warnings about uninitialized signals, but this is not helpful for the reason that there are many signals that we intentionally leave uninitialized because they don't propagate.  Only in a tiny few cases, such as for "valid" signals, does an uninitialized signal propagate and cause problems.  The ideal would be what verilog does, which is set the value to "x", which allows easily tracing it backwards.  Is there any relatively painless way of finding these cases with uninitialized signals that cause problems?

A: In Chisel 3, we are currently in the process of adding safety for unconnected signals: https://github.com/ucb-bar/chisel3/issues/413. I'm not sure what the outcome will be, but our goal is to prevent exactly the kind of issues mentioned here.


text:
Q: React-Admin - Warning: Encountered two children with the same key When I update a resource, it returns to List View and correctly updates the resource, but for a moment the List View blinks and console reports a warning:
Warning: Encountered two children with the same key, `2`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
in tbody (created by TableBody)
in TableBody (created by WithStyles(TableBody))
in WithStyles(TableBody) (created by DatagridBody)
in DatagridBody (created by shouldUpdate(DatagridBody))
in shouldUpdate(DatagridBody) (created by Datagrid)
in table (created by Table)
in Table (created by WithStyles(Table))
in WithStyles(Table) (created by Datagrid)
in Datagrid (created by WithStyles(Datagrid))
in WithStyles(Datagrid) (at UserList.js:13)
in div (created by ListView)
in div (created by Paper)
in Paper (created by WithStyles(Paper))
in WithStyles(Paper) (created by Card)
in Card (created by WithStyles(Card))
in WithStyles(Card) (created by ListView)
in div (created by ListView)
in ListView (created by ListController)
in ListController (created by TranslatedComponent(undefined))
in TranslatedComponent(undefined) (created by Connect(TranslatedComponent(undefined)))
in Connect(TranslatedComponent(undefined)) (created by List)
in List (created by WithStyles(List))
in WithStyles(List) (at UserList.js:12)
in UserList (created by WithPermissions)
in WithPermissions (created by Connect(WithPermissions))
in Connect(WithPermissions) (created by getContext(Connect(WithPermissions)))
in getContext(Connect(WithPermissions)) (created by Route)
in Route (created by Resource)
in Switch (created by Resource)
in Resource (created by Connect(Resource))
in Connect(Resource) (at App.js:26)
in Route (created by RoutesWithLayout)
in Switch (created by RoutesWithLayout)
in RoutesWithLayout (created by Route)
in div (created by Layout)
in main (created by Layout)
in div (created by Layout)
in div (created by Layout)
in Layout (created by WithStyles(Layout))
in WithStyles(Layout) (created by Connect(WithStyles(Layout)))
in Connect(WithStyles(Layout)) (created by LayoutWithTheme)
in MuiThemeProvider (created by LayoutWithTheme)
in LayoutWithTheme (created by Route)
in Route (created by CoreAdminRouter)
in Switch (created by CoreAdminRouter)
in div (created by CoreAdminRouter)
in CoreAdminRouter (created by Connect(CoreAdminRouter))
in Connect(CoreAdminRouter) (created by getContext(Connect(CoreAdminRouter)))
in getContext(Connect(CoreAdminRouter)) (created by Route)
in Route (created by CoreAdmin)
in Switch (created by CoreAdmin)
in Router (created by ConnectedRouter)
in ConnectedRouter (created by CoreAdmin)
in TranslationProvider (created by withContext(TranslationProvider))
in withContext(TranslationProvider) (created by Connect(withContext(TranslationProvider)))
in Connect(withContext(TranslationProvider)) (created by CoreAdmin)
in Provider (created by CoreAdmin)
in CoreAdmin (created by withContext(CoreAdmin))
in withContext(CoreAdmin) (at App.js:20)
in App (at index.js:6)

The update is applied, even though this warning occurs. In the console, the records before change and after change seem identical (both have required ids, the only difference is the change of course):
Logging list records before UPDATE:

This is how i return data on update in my httpClient:
Logging list records after UPDATE:

  switch (type) {
    // (...)
    case UPDATE:
      return { data: { id, ...updateDiff } };
    // e.g.: id = 2 and updateDiff = {diffProp: 'newValue'}
  }

On the other hand, when I return it without id:
  switch (type) {
    // (...)
    case UPDATE:
      return { data: updateDiff };
    // e.g.: id = 2 and updateDiff = {diffProp: 'newValue'}
  }

the warning states: Warning: Each child in an array or iterator should have a unique "key" prop., so I guess the id is required (according to the latest version of docs).
I guess in the moment of update it renders for some time both records for some reason (?). How to solve it?

A: Edit: I figured out the source my issue: basically in GET_LIST I was returning records with ids of type number. However, in GET_ONE (and not UPDATE) I was returning a record with id of type string. Pretty straightforward.
I came across the same issue as well. I was using my own data provider and I'm sure I return the right format after UPDATE, e.g. { data: { id: <int>, ... } }.
For some reason it seems react-admin takes the id I return and converts it to string. When I print the props passed down to Datagrid I see the ids array containing something like [308, '308', ...] (notice 308 id shows up twice, once as integer and then as string). Maybe there's a type coercion bug somewhere down the line, I need to investigate this. However, I managed to overcome this with a quick hack, I wrapped Datagrid like this
const MyDatagridHack = props => {
  const newIds = props.ids.filter(id => typeof(id) !== 'string');
  const newProps = Object.assign({}, props, { ids: newIds });
  return (
    <Datagrid {...newProps} rowClick="edit">
    </Datagrid>
  )
};

This will just remove the strings from ids array. Then where you list the items:
const ResourceList = props => {
  return (
    <List {...props}>
      <MyDatagridHack>
        <TextField source="id" />
        ...
      </MyDatagridHack>
    </List>
  );
};

This will remove the warnings but I'm not 100% happy with it. I need to investigate why the id is added again as string.

A: I met this warning too. Completely same case. For some reason ra tries to append updated record as new one, but the action type was exactly 'UPDATE'.
I've created the issue, but developer coudnt reproduce it.
Demo works fine too.
Issue link: https://github.com/marmelab/react-admin/issues/1880
If you can reproduce it on their codeSandBox example app, please reopen the issue.


text:
Q: Is this a good method to find hcf? #include <iostream>
using namespace std;
int main(){
     int a,b,hcf=0,i=1;
     cout<<"Enter Value  :";
     cin>>a;

     cout<<"Enter value  :";
     cin>>b;

    while(i<=a || i<=b){
         if(a%i ==0 && b%i ==0)hcf=i;
         ++i;
        }
 return 0;
    }

or Remainder Method ?

A: Are you finding the hcf at all ? It looks like that you are trying to reverse a number.

A: Unless the numbers involved are really small, Euclid's algorithm is likely to be a lot faster. This one is linear on the size of the number (with two divisions per iteration, and divisions are one of the slowest types of instruction). Euclid's is actually fairly non-trivial to analyze -- Knuth V2 has several pages on it, but the bottom line is that it's generally quite a bit faster.
If you want to use a variation on the one you're using now, I'd start with i equal to the smaller of the two inputs, and work your way down. This way, the first time you find a common factor, you have your answer so you can break out of the loop.


text:
Q: Allow users to contribute images to a post I'd like to curate, per-post, a collection of images submitted by many different users.  Meaning - when a user views a post, they'll see as part of it the images that others have contributed, and will have the opportunity to contribute their own.  What direction should I look in for implementing this?
Thank you for you help.
(I have a strong programming background, but not yet in Wordpress)

A: i have got quite a good solution for you, if i get you right:
you want to display an upload box for a visitor at your site, enabling him to save images into the wordpress library, and have them labeled as useruploads or something.
first step would be to create a form on the post template:
<form action='upload.php?pid=$post->ID' method='post' enctype='multipart/form-data'>
    <input type='file' name='myfile[]' multiple class='realfile'>

        <input class='fakefile fakefileinput'/>

    <input type='submit' value='upload'>
</form>

you can see a few tricks i implemented, the fakefile and realfile work for designing the boxes to look the same in every browser, style the fakefile, and hide the real file. you can just skip this part.
next comes the javascript to it (i suppose you already use jQuery on your site), in the document ready function:
var percent = $('.percent');

$('form').ajaxForm({
    beforeSend: function() {
        var percentVal = '0%';
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        percent.html(percentVal);
    },
    complete: function(xhr) {
        var responseJson = eval('(' + xhr.responseText + ')');
        if( responseJson.message != null )
            alert(responseJson.message);
        if ( responseJson.ids != null ) {
            alert( 'Upload successful' );
            $('.fakefileinput').val('');
            $('.realfile').val('');
            percent.html('');
        }
    }

});

this part handles the complete form - with a percent count of the upload. be sure to include the

.
the last thing to do is your uploadhandler. i have this one in the rootdirectory, called upload.php, as you can see in my form, but every folder should work, as long as you include the wp-load.php.
include_once( 'wp-load.php' ); // to have the wordpress functions available
$uploaddir = wp_upload_dir(); // get the directory to store the images

if ( isset( $_FILES['myfile']['name']['0'] ) ) { // check if there are files

    $files = $_FILES['myfile'];

    $number = count( $files['name'] );

    for ( $_i = 0; $_i < $number; $_i++ ) { // loop through the uploaded images

        if ( "image/jpeg" != $files['type'][$_i] && "image/pjpeg" != $files['type'][$_i] ) {
            // just allow jpeg, be sure to include pjpeg as the IE sends pjpeg instead of jpeg.
            $_message.= 'Picture is no Jpeg: ' . $files['type'][$_i];

        } else {

            $uploadfile = $uploaddir['path'] . '/' . $_GET['pid'] . '-' . basename($files['name'][$_i]); // name and directory of the file. for ordering purposes in the file system, i include the postid in front of the filename.
            move_uploaded_file($files['tmp_name'][$_i], $uploadfile); //move the file from the server upload directory to the wordpress upload directory
            $filename = basename($uploadfile); // get the filename

            $wp_filetype = wp_check_filetype(basename($filename), null ); //wordpress handler for filetypes, although we handle just jpeg here.

            // data of the new attachment. you can add any values here, for example an excerpt or whatever
            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
                'post_content' => '',
                'post_status' => 'inherit'
            );
            $attach_id = wp_insert_attachment( $attachment, $uploadfile ); // insert the attachment into the wordpress database - the file HAS to be in the uploaddir! the function returns the new id.
            // you must first include the image.php file
            // for the function wp_generate_attachment_metadata() to work
            require_once(ABSPATH . 'wp-admin/includes/image.php');

            $image = get_post( $attach_id ); // load the data of the new image.
            $fullsizepath = get_attached_file( $image->ID ); // get the filepath of the image in the wordpress upload directory
            $attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath ); // generate the thumbnails and the rest of the metadata
            wp_update_attachment_metadata( $attach_id, $attach_data ); // ... and update the image
            $mypost = array(
                'ID' => $image->ID,
                'post_parent' => $_GET['pid']
            );
            wp_update_post( $mypost ); // now set the post parent to the submitted post_id, so you have the connection between the uploaded files and the corresponding posts
            wp_set_object_terms( $image->ID, 'userupload', 'category' ); // if you want to, you can also assign a category 'userupload' to the uploaded images - you can distinguish between your own and the ones from the users.
            //$_message.= var_dump( $attach_data ); - debugging
            $_id[$_i]= $attach_id; // save all the new ids into an array to return, if you want to do anything special with them afterwards.

        }

    }

} else {

    $_message.= "No Images sent."; // Errorhandler

}
$return = json_encode( array(
    'ukid' => $_GET['uid'],
    'message' => $_message,
    'ids' => $_id
) );
echo( $return ); // return the json, explaining what happenend.
die();

that should be it!
i modified my code a little, and didn't test it afterwards, but it should work just fine :) be sure to include some sort of spam detection, to be sure your server can handle all the work from the image processing :)
if you got any additional questions to this method, do not hesitate to ask :)


text:
Q: What is the best way to fire crossdomain ajax calls? What is the best way to make cross domain ajax calls without writing custom proxy, tried using flXHR and it is working fine, but it fails in the browsers where we don't have flash, can  we do it using pure javascript?

A: JSONP is the best way to fire crossdomain ajax call. It doesn't support POST request though


text:
Q: After upgrading to the latest RN TypeError: undefined is not an object ( evaluating '_reactNativeCamera.RNCamera.constants.Aspect.fill') After upgrading to the latest RN TypeError: undefined is not an object ( evaluating '_reactNativeCamera.RNCamera.constants.Aspect.fill')
Can anyone have any solution for this?


text:
Q: Regex for capturing repeated groups Javascript I have some test data in the following format -
"lorem ipsum  lorem ipsum  ipsum "

Now, my goal is to identify all the image tags along with their respective source urls and css classes and store them together with the remaining text in an ordered array like -
["lorem ipsum", {imageObject1}, "lorem ipsum", {imageObject2}, "ipsum", {imageObject3}]

Now for this I tried to create a sample regex
var regex = /(.*()+?.*)+/ig

Now when I try this regex with the sample text i am getting -
regex.exec(sample_text) => [0:"lorem ipsum  lorem ipsum  ipsum "
1:"lorem ipsum  lorem ipsum  ipsum "
2:""
3:"some_url3"
4:"class='some_class3'"]

How in javascript can I transform the sample html text
into an array of tagged html objects with their attributes.

A: Do not use regular expressions to parse HTML. Use a DOMParser to parse the string and then CSS queries to get the images from the DOM, it will be much more reliable and easier to read.
var html = "lorem ipsum  lorem ipsum  ipsum "

var nodes = new DOMParser().parseFromString(html, "text/html").body.childNodes

That will get you almost what you wanted (just some empty Text nodes you can filter out).
Or do something a little bit more accurate like this in case you don't have just images and text in the HTML:
var images = new DOMParser().parseFromString(html, "text/html").querySelectorAll("img")
var array = new Map([...images].map(img => [img.previousSibling.nodeValue, img]))


text:
Q: Writing interceptors in CXF Webservices project How do I write a CXF interceptor to prevent execution of couple of Restful URL's based on some specific conditions. I know that I need to write an interceptor extending URIMappingInterceptor. The blocking has to be done based on the name of the url or function that will be called. I need to return immediately throwing an error.

A: You can extend AbstractInDatabindingInterceptor and using the message.get, get the url or uri and do validation Here is an example I used a long back.
public class RestInInterceptor extends AbstractInDatabindingInterceptor {

    private static final Logger LOG = LoggerFactory
            .getLogger(RestInInterceptor.class);

    public RestInInterceptor(String phase) {
        super(Phase.USER_STREAM);
        // TODO Auto-generated constructor stub
    }

    public RestInInterceptor() {
        super(Phase.USER_STREAM);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void handleMessage(Message message) throws Fault {

        Endpoint endpoint = message.getExchange().getEndpoint();

        String output = "";

        // for uri key is org.apache.cxf.request.uri
        String url = (String) message.get("org.apache.cxf.request.url");

        if(!"".equals(url) && url.contains("KP1Service")){
            Response response = Response.status(Response.Status.METHOD_NOT_ALLOWED).entity("").type(MediaType.TEXT_PLAIN) .build();
            message.getExchange().put(Response.class, response);
            return;
        }
    }
}


text:
Q: How to load images in angular other than default assets folder I have a  folder directory structure here:

I have provided the image path in html.
<img class="img-fluid" src="../../ecommerce/assets/images/bannerimg.png" alt=" ">

configured in angular json

But is not loaded

Its working well in default assets/images directory

A: Try your path for the src property of your image tag as: app/ecommerce/assets/images/bannerimg.png


text:
Q: Suitable processor for a Robocup Junior Soccer robot? Last year, I entered into the Robocup Junior Soccer competition using a robot built from the Lego Mindstorms NXT kit. It worked well, but we were thrashed at the international level, mainly because of the sheer speed and strength of the opposition.
This year, I'm intending to build the robot from scratch, as interfacing non-lego motors and sensors with the NXT is troublesome at best. However, I have absolutely no experience with any other microprocessor, and am wondering what to get.
The microprocessor needs I2C and PWM outputs (to drive 3-5 motors), and preferably should be cheapish, and programmable in some object-oriented programming language.
Would an arduino be suited to this purpose, or this that insuffient/overkill?

A: Consider using the Parallax Propeller and dedicated motor controllers such as the DMC-1. The Propeller has 8 32 bit cores which can run up to 8 processes simultaneously. You can program it using its native OO language SPIN, or for more performance, its own assembly language.
The DMC-1 is a low cost I2C dual motor controller which can drive loads of up to 2.6A at 15V continuously. It's very easy to control. You can find out about it here: http://web4robot.com
Even if you decide to use the Arduino, I would recommend using the DMC-1.


text:
Q: GWT GAE Upload through Blob If I'm using GWT File widget and form panel, can someone explain how to handle upload on blobstore on google application engine??

A: Take a look at gwtupload. There are examples on how to use it with GAE Blobstore.

A: Google blobstore is specifically designed to upload and serve blobs via http. Blobstore service (obtained using BlobstoreServiceFactory.getBlobstoreService()) generates http post action for you to use in the html form. By posting file to it you upload your blob to the blobstore. When you generate this action you provide a path to the handler (servlet) where you have access to uploaded blob key:
Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);
BlobKey blobKey = blobs.get("data");

Note, that "data" is the file field in your form. All you have is a key to the blob (your file). From here you take control - you can save this key for later and/or immediately serve the  blob on a page (using key):
BlobKey blobKey = new BlobKey(req.getParameter("blob-key"));
blobstoreService.serve(blobKey, res);

Of course, for details see Google documentation.
One nice feature of the blobstore that it's integrated with Google Mapper (rudimentary map-reduce) service (work in progress) which lets you process files uploaded as blobs line by line: http://ikaisays.com/2010/08/


text:
Q: Export Derby db as a sql file I have a derby db in "D:/Dev/workspaces/workspacePro/School-FinMa/school-finma". I want to export it to a this folder "E:/". So I run this:
Runtime.getRuntime().exec("java org.apache.derby.tools.dblook -d 'jdbc:derby:D:/Dev/workspaces/workspacePro/School-FinMa/school-finma' -o 'E:/myDB_DDL.sql'");

But nothing happens, it's like if this code does not exists.
I want a way to export the db to single .sql file, that contains all db generation code + data. How Can I do that from inside Java ??
The project (in eclipse) have derbytools.jar imported.

A: When you start a new sub process and it doesn't work, you should output the output and error streams. You said there is no output, but I think you didn't get the output stream of the process.
When running a Java sub process you should add the classpath as you would in the command line. In this case you should add derby.jar and derbytools.jar. For a network connection you need derbyclient.jar, too.
You are using Windows. Then don't use single quotation marks.
Here is a simple running example, which prints the output and error streams to the console. Without an error there is no output. But try it with single quotation marks you will see an error message.
In this example the Derby JARs are located at: e:\derby\lib.
public static void copyStream(InputStream in, OutputStream out) throws IOException {
  final byte[] buffer = new byte[1024];
  int bytesRead = 0;
  while((bytesRead = in.read(buffer)) != -1) {
    out.write(buffer, 0, bytesRead);
  }
}

public static void main(String[] args) throws IOException, InterruptedException {
  Process process = Runtime.getRuntime().exec(
    "java -cp e:\\derby\\lib\\derby.jar;e:\\derby\\lib\\derbyclient.jar;e:\\derby\\lib\\derbytools.jar org.apache.derby.tools.dblook -d jdbc:derby:D:/Dev/workspaces/workspacePro/School-FinMa/school-finma -o E:/myDB_DDL.sql");
  final int exitValue = process.waitFor();
  System.out.println("Exit value: " + exitValue);

  System.out.println("Outputstream: ");
  copyStream(process.getInputStream(), System.out);

  System.out.println("Errorstream: ");
  copyStream(process.getErrorStream(), System.out);
}


text:
Q: Как узнать, с какими флагами компилировалась утилита sqlite3?
Как узнать, какие
настройки времени компиляции
использовались при компиляции конкретного экземпляра
утилиты sqlite3?

A: Для этого можно использовать команду
PRAGMA compile_options:

PRAGMA compile_options;
This pragma returns the names of compile-time options used when building
SQLite, one option per row.  The "SQLITE_" prefix is omitted from the returned
option names.  […]

Пример вывода на ОС Ubuntu 20.04:
$ echo 'PRAGMA compile_options;' | sqlite3
COMPILER=gcc-9.3.0
ENABLE_COLUMN_METADATA
ENABLE_DBSTAT_VTAB
ENABLE_FTS3
ENABLE_FTS3_PARENTHESIS
ENABLE_FTS3_TOKENIZER
ENABLE_FTS4
ENABLE_FTS5
ENABLE_JSON1
ENABLE_LOAD_EXTENSION
ENABLE_PREUPDATE_HOOK
ENABLE_RTREE
ENABLE_SESSION
ENABLE_STMTVTAB
ENABLE_UNKNOWN_SQL_FUNCTION
ENABLE_UNLOCK_NOTIFY
ENABLE_UPDATE_DELETE_LIMIT
HAVE_ISNAN
LIKE_DOESNT_MATCH_BLOBS
MAX_SCHEMA_RETRY=25
MAX_VARIABLE_NUMBER=250000
OMIT_LOOKASIDE
SECURE_DELETE
SOUNDEX
THREADSAFE=1
USE_URI


text:
Q: How to Write to line by line in a single file on different methods in java I would like to write in a single file in java but in different methods. I wrote this
import java.io.*;
public class Test {
  public static File file = new File("text.log");

  public static void main (String [] args) throws IOException
  {
    FileWriter input= new FileWriter(file);
    input.write("hello");
    input.write("\n");
    input.close();
    test();
   }

  public  static void test() throws IOException
   {

    FileWriter input= new FileWriter(file);
    input.write("world");
    input.write("\n");
    input.close();
   }

}

The output is just world. It looks like calling the function test() overwrites what was previously written.

A: You need to open the FileWriter in append mode by passing true as the second argument:
public static File file = new File("text.log", true);

From the Javadoc:

public FileWriter(String fileName, boolean append)
  Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

A: When you write new FileWriter(file, true), it will append instead of overwrite.


text:
Q: Taking caches into consideration when writing unit/functional tests I am writing unit and functional tests in my Ruby on Rails application. I try to write a test anytime someone opens a defect against me. One of the defects that recently came up was directly related to either how we are updating the cache for an object or invalidating it. Is it normal to take caching into consideration when writing tests? I have not seen it done for much, but these days so much is stored in tools such as Redis or Memcached (we use Redis). I think testing for anything that gets stored/retrieved from these in-memory stores needs to also be in tests. Are there any tools or advice one could give for doing that in Rails 3?

A: Caching should be tested at the integration level, especially if you have multiple layers of caching working together, as it can be complex. You can also write lower-level unit tests to verify the conditions under which an object should be marked as stale.
For fixing defects, I would suggest first trying to writing an integration test which reproduces the bug, and then a unit test for the appropriate class.


text:
Q: Discussion about convergence of sequence If {sn} and {sn + tn} are both convergent then so is {tn}. is this statement correct by the sum of limit of sequence which says Suppose that the sequences {sn} and {tn} are convergent. Then
lim
n→∞
(sn + tn) = lim
n→∞
sn + lim
n→∞
tn.
If this a correct way to solve this problem? If this is wrong statement then what can we have as a counterexample because I wasn't able to find a counterexample  for this statement. Thanks in advance


text:
Q: Why EF Extensions not throwing an exception when there is any such entity on table to delete? I am wondering about why BulkDelete not throwing an exception if there is no such entity to delete on database? I am forced to check database if there are some matching entities and after calling BulkDelete method sending matched entities which I've got from querying database. Do EF Extensions has some options to automate it?

A: You dont have to check database. I am assuming you are using EF Extensions - BulkDelete. When you call BulkDelete, you just delete it but to make changes to the database, you have to .SaveChanges(); - This method however return the number of rows affected.
So, if the number is 0, then you know your DELETE failed. If the number is above 0, then you know the DELETE was successfull

A: The BulkDelete has been optimized for performance.
So indeed, there is no check about if the entity exists or not first, we just perform the Delete operation.
Something you could do on your side to make it easier is using the BulkRead method before using the BulkDelete.
var customers = context.Customers.BulkRead(deserializedCustomers);

Docs: https://entityframework-extensions.net/bulk-read
By using this method, you will be able to easily compare with your current list to get the list of customer doesn't exist in the database for example.
You could also get the RowAffecteds and compare it with your list count: https://entityframework-extensions.net/rows-affected

A:
I am wondering about why BulkDelete not throwing an exception if there is no such entity to delete on database?

Because there is nothing wrong with having a filter that ends up yielding 0 results. That is not inherently an erroneous state.
Sure, for a specific use case you may have been expecting to find at least something, but a generalized library cannot account for your specific expectation in your specific use case. There are plenty of cases where ending up not deleting something is not a problematic scenario, e.g. a daily cleanup job that removes old entries if there are any. If there are no old entries, that's not a reason to throw an exception. It just means that nothing needed to be deleted.
This is no different from why a foreach doesn't throw an exception when you pass it an empty collection. The foreach is still doing its job, i.e. performing the work for each item in the collection. There are 0 items, and therefore it performs the work 0 times.


text:
Q: jQuery: set opacity of entire element except on child? I don't know if that is even possible…
I have a div#branding inside of my header. The header has multiple other elements inside.
I want all children of my header to have a opacity of 0.3 but NOT the #branding div.
How can I achieve that?
I tried with the following piece, but that doesn't work.
$('header div:not(#branding)').css('opacity', '0.3');
Thank you for your help.

A: Try this:
$('div#header').children().css('opacity', '0.3');

It selects all children of div#header and applies the opacity to them only. ( http://api.jquery.com/children/ )
Demo: http://jsfiddle.net/MNUsL/1/

A: it should, try:
$('header div').not('#branding').css('opacity', '0.3');

edit
As for inheriting opacity - children cannot be less opaque than parent, but could be more
http://jsfiddle.net/Jacek_FH/MNUsL/12/

A: It is not possible at all. You will have to have the opacity for each child element which you want. Try this
$('headerSelector').children(":not(#branding)").css('opacity', '0.3');

A: whenever i have this issue I just do it as simple as possible for me, maybe not the most elegant solution but i just create a wrapper div i.e:

...

Then it's just a question of positioning the branding on top with the css "position:relative" and "z-index" properties. It will no longer be a child of the header but it is inside the wrapper so if you want to listen to specific events it's still possible.
I hope this helps.


text:
Q: How to upload a file in mongodb ( no gridfs want with BSON ) I am trying to store file,images and documents in mongodb but it takes only null, i am able to store the file in a folder but not able to do the same with mongo.
The .ejs file is as below:

Upload a file

            <form ng-submit="uploadFile()" class="form">
                <input type="text" placeholder="title" ng-model="titleText" class="form-control" required>

<file-field ng-model="uploadThis" class="btn" ng-class="{'btn-success':uploadThis}" preview="uploadPreview" name="up" accept="image/png,image/jpg,image/jpeg">Select file</file-field>

                <input type="submit">
            </form>

corresponding js file is as::
sample.controller('PatientEmrController',['$scope','$http',function($scope,$http){

    $scope.uploadFile=function(){

        if(!$scope.uploadThis){
            alert('Please select a file to upload.')
            return;
        }

        var fd = new FormData();

        //you can also send other fields
        //this will be available as req.body.title
        //NOTE: files must be added AFTER other form data
        fd.append('title', $scope.titleText);

        //nacho relates to what we called the file
        //in the api on sails
        fd.append('nacho', $scope.uploadThis);
        $http.post('/api/burrito', fd, {
            //transformRequest: angular.identity,
            //headers: {'Content-Type': undefined}
            up:$scope.uploadThis,
            title: $scope.titleText,
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(data){
            console.log('upload data',data);
            if(data.result){

                alert('file uploaded. See .tmp/uploads folder.');
            }

        })
        .error(function(err){
            alert('there was an error uploading the file.');
            console.log(err);
        });
    }

}]);

controller file in api is as follows::
 module.exports = {

torta:function(req,res){

    console.log('form body',req.body);

    req.file('nacho').upload(function(err,files){

            Filecontroller2.create({
                up: req.param('up'),
              title: req.param('title')
           })

            .exec(function createCB(err, created){
                     if (err)
                      {
                       return res.negotiate(err);
                      }
                       else
                      {
                        return res.ok();
                      }
              });

        if(err) return res.send(400,{result:false,error:err});

        if(!files) return res.send(400,{result:false,error:'Unable to upload file'});

        console.log('file data',err,files);

        console.log('uploaded file path',files[0].fd)

        res.send({result:true,files:files});

    });
 }  };

model in api is::
module.exports = {

  schema: true,
  attributes: {

     up: {
    type: 'jpg',
     columnName: 'up'
    },

    title: {
      type: 'string',
     // required: true
     columnName: 'title'
    }

  }
};

This is my sails controller code with gridfs coding, please take a look.
uploadAvatar: function (req, res) {

  console.log('form body',req.body);
  var patientID=req.session.me;

  req.file('avatar').upload(function(err,files){
    // don't allow the total upload size to exceed ~10MB
    //maxBytes: 10000000

    adapter: require('skipper-gridfs'),
    //uri: 'mongodb://[username:password@]host1[:port1][/[database[.bucket]]'
     uri:'mongodb://kal:kal@localhost:27017/medoolDB.bucket',
    },function whenDone(err, uploadedFiles) {
    if (err) {
      return res.negotiate(err);
      return res.ok();
    }

    // If no files were uploaded, respond with an error.
    if (uploadedFiles.length === 0){
      return res.badRequest('No file was uploaded');
    }

    filecontroller2.findOne({patientID:patientID}, function foundFilecontroller(err, fcontroller) {
    console.log(req.method);
      if (err) return next(err);
      if (!fcontroller){

             filecontroller2.create({
                 up:req.param('up'),
      })

             .exec(function createCB(err, created){
                       if (err)
                          {
                           return res.negotiate(err);
                          }
                           else
                          {
                               return res.ok();
                          }
                  });
            }

            else
            {

    // Save the "fd" and the url where the avatar for a user can be accessed
    filecontroller2.update({ patientID:patientID}, {

      // Generate a unique URL where the avatar can be downloaded.
      avatarUrl: require('util').format('%s/user/avatar/%s', sails.getBaseUrl(), req.session.me),

      // Grab the first file and use it's `fd` (file descriptor)
      avatarFd: uploadedFiles[0].fd
    })
    .exec(function (err){
      if (err) return res.negotiate(err);
      return res.ok();
    });

    if(err) return res.send(400,{result:false,error:err});
    if(!files) return res.send(400,{result:false,error:'Unable to upload file'});
     console.log('file data',err,files);
     console.log('uploaded file path',files[0].fd)

            //send response

            //result:true -- file upload successful
            //files:files -- send uploaded file data to the front end
            res.send({result:true,files:files});

}

}

}

A: if you would like to store files into a mongoDB take a look into GridFS

GridFS is a specification for storing and retrieving files that exceed
  the BSON-document size limit of 16 MB.
Instead of storing a file in a single document, GridFS divides the
  file into parts, or chunks 1, and stores each chunk as a separate
  document. By default, GridFS uses a chunk size of 255 kB; that is,
  GridFS divides a file into chunks of 255 kB with the exception of the
  last chunk. The last chunk is only as large as necessary. Similarly,
  files that are no larger than the chunk size only have a final chunk,
  using only as much space as needed plus some additional metadata.
GridFS uses two collections to store files. One collection stores the
  file chunks, and the other stores file metadata. The section GridFS
  Collections describes each collection in detail.
When you query GridFS for a file, the driver will reassemble the
  chunks as needed. You can perform range queries on files stored
  through GridFS. You can also access information from arbitrary
  sections of files, such as to "skip" to the middle of a video or audio
  file.
GridFS is useful not only for storing files that exceed 16 MB but also
  for storing any files for which you want access without having to load
  the entire file into memory


text:
Q: Error 'Uncaught SyntaxError: Unexpected token < in underscore.js' Here's my code,
HTML:

SCRIPT:
testView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },

    render: function(){
        var ops = [
            {dealGrade: '50%', devices: 123, accountValue: '20%', company_name: 'Kyocera', rep_name: 'James Kogg', rep_designation: 'Sales Rep', proposalCount: 2},
            {dealGrade: '75%', devices: 215, accountValue: '41%', company_name: 'Flipkart', rep_name: 'Christina Kogg', rep_designation: 'MD', proposalCount: 0}
        ]

        var template = _.template($("#test_temp").html(), ops);

        this.$el.append(template);
    }
});

var test_view = new testView({ el: $("#viewport .container") });

I get this error message:

Uncaught SyntaxError: Unexpected token < in underscore.js

What am I doing wrong?

A: You're not closing the <% around the _.each or opening the template tag for the _.each's  closing });:

Underscore's template engine is pretty simple minded, it just does a bit of simple text wrangling to turn your template inside-out into JavaScript code.
Also, the template function wants its data as key/value pairs (i.e. a JavaScript object) so you'll need to give your ops a name:
var template = _.template($("#test_temp").html(), { ops: ops });

A: I got a similar error

Uncaught SyntaxError: Unexpected token var
      at new Function ()
      at Function._.template

that's because in my template I wrote a js statement inside <%= instead of <%
so make sure the syntax of your template is correct


text:
Q: Jade/pug setting MIME type of javascript file to text/html Hey I've been trying to use jade/pug to have my node.js backend render my pages in the front end. I need to include some javascript to make some functionality work but I can't seem to get it to load correctly. I get this error:
"The script from "http://localhost:3000/public/javascript/newCust.js" was loaded even though its MIME type ("text/html") is not a valid JavaScript MIME type.
new Loading failed for the  with source "http://localhost:3000/public/javascript/newCust.js"."
I have tried setting the content type to javascript and tried moving the directories around to help solve the issue.
script(type='text/javascript' src='public/javascript/newCust.js')

A: I see you had put your static javascript files in the correct place, i.e in a folder named public.
But, in order to serve all static files : html, css and javascript files, you need to add a built-in middleware function, namely express.static(), in your entry point which is usually app.js or index.js file, like so :
app.use(express.static('public'));
// you can also use the absolute path, using npm package named path like below :
// app.use(express.static(path.join(__dirname, 'public')));

The express.static() function will combine your static javascript file with that public folder. Therefore, in your pug file, you should write as follow :
script(type='text/javascript' src='./javascript/newCust.js')

not
script(type='text/javascript' src='./public/javascript/newCust.js')

You don't even need to add the MIME type in that script tag, because by default, the script tag will have the correct MIME type of :
type='text/javascript'

Try with and without adding that MIME type, both should work.
For more detail about using express.static() function, you can read in Express built-in middleware function : express.static()


text:
Q: Datediff not working on Excel I am trying to write a DAX query and it is always returning me an error.
What I want to calculate hours different 2 columns -
So I have --

*

*StartTime 2015-03-02 09:00

*EndTime 2015-03-02 18:00

So I want to calculate the hours different between two ---
 DATEDIFF([StartTime]; [EndTime];HOUR)

but this query is not working !
Do anyone knows where I am making the mistake !

A: This function works only if you use Excel 2016 or Power Bi. if you want to have the same result on Excel 2013/2010 you can use this workaround:
=([end date]-[Start date])*24`


text:
Q: Dynatree checkboxes are not checked anymore I am finding that the Dynatree checkboxes are images and not real checkboxes.  However, I am assuming that the checkbox state when captured properly will be rendered through Javascript properly, and the correct image (partial checked, unchecked or completely checked) will show up.
I am using Dynatree and the correct JSON with all attributes being captured properly. During the time of testing, everything seems to be working fine as expected with correct nodes showing the proper checkbox state.
However, I came back after the weekend and I tried to access the site utilizing the Dynatree;  and the checkboxes have disappeared completely.
"select": true,
"hideCheckbox": false,
"unselectable": false,

Anyone using Dynatree with checkboxes facing the same problem and how they resolved the issue.
Please help. Thank you,

A: It's not the images...You can refer to the following link I am sure it will help and solve your issue :)
http://wwwendt.de/tech/dynatree/doc/samples.html


text:
Q: Add a column to a gridview associated with an SQL data source [C#/ASP/Webform] I have a gridview in my asp page which data comes from an SQL datasource (a stored procedure), I'm trying to find a way to add a column which is not in the datasource to the gridview: I would like to wether add an asp tag wich represents the column, make it invisible by default then programmatically make it visible or to directly create a new column in the code:
<vol:VlGridView ID="gv" DelayLoadPanelId="up" OnRowCommand="gv_RowCommand" OnRowDataBound="gv_RowDataBound" EnableViewState="true"  runat="server" AutoGenerateColumns="False" AllowSorting="true" AllowPaging="true" OnNew="gv_New" AbcTargetButtonId="btnSearch" AbcTargetFieldId="tbSearch" DataSourceID="sds" OnSorting="gv_Sorting" >
    <columns>
          <asp:boundfield datafield="CustomerID" headertext="Customer ID"/>
    </columns>
</vol:VlGridView>

However I get the following error:
System.Web.HttpException: can't find the field 'CustomerID' in the selected datasource

A: The easiest way is to add a dummy column to the SQL query when using boundfield or autogenerated colums.
SELECT ColumnA, ColumnB, ColumnC, NULL AS CustomerID FROM table

In this case CustomerID is NULL, but you can specify other data types as well.
123 AS CustomerID
'stringValue' AS CustomerID

If you do not want/can't change the query, you can add a TemplateField
<Columns>
    <asp:TemplateField HeaderText="Customer ID">
        <ItemTemplate>
            //stuff goes here
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

A: fetch data from database and store in datatable

//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("your_procedure");

dt.Columns.Add("CustomerID",  typeof(System.Int32));

foreach(DataRow row in dt.Rows)

{

  // code to assign values to newly created column CustomerID

     row["CustomerID"] = 0; //assign value according to your requirement
}

//then bind datatable to gridview
gv.Datasource=dt;
gv.DataBind();


text:
Q: How to get access to a specific header column in Vuetify data-table How can I get access to a specific header column in Vuetify data-table to customize it? Let's say I would like to hide it by using a css class-name.
In Vuetify docs suggested to use header.<name> to get acess to. But I don't have a clear understanding how to this due to the lack of an example.

A: As mentioned in official docs :

You can use the dynamic slots header.<name> to customize only certain columns. <name> is the name of the value property in the corresponding header item sent to headers.

You could do :
<template>
  <v-data-table
    :headers="headers"
    :items="desserts"
    class="elevation-1"
  >
    <template v-slot:header.name="{ header }">
      {{ header.text.toUpperCase() }}
    </template>
  </v-data-table>
</template>

<script>
  export default {
    data: () => ({
      headers: [
        {
          text: 'Dessert (100g serving)',
          align: 'start',
          value: 'name',
        },
        { text: 'Calories', value: 'calories' },
        { text: 'Fat (g)', value: 'fat' },
        { text: 'Carbs (g)', value: 'carbs' },
        { text: 'Protein (g)', value: 'protein' },
        { text: 'Iron (%)', value: 'iron' },
      ],
      desserts: [
        ...
      ],
    }),
  }
</script>

For example <template v-slot:header.<name>="{ header }"> gives you an access to the correspondant item in headers config { text: 'Calories', value: 'calories' }, where you could use the text and the value in order to customize them like :
<template v-slot:header.name="{ header }">
      <i>{{ header.text.toUpperCase() }}</i>
    </template

If you want to customize rows check this answer


text:
Q: Accuracy Equals 0 CNN Python Keras I'm working on a binary classification problem. I was getting 69% accuracy at first, but kept running out of memory so I shrunk certain parameters, now it's coming up 0. Any idea whats going on?

model = Sequential()
from keras.layers import Dropout
model.add(Conv2D(96, kernel_size=11, padding="same", input_shape=(300, 300, 1), activation = 'relu'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))

model.add(Conv2D(128, kernel_size=3, padding="same", activation = 'relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))

model.add(Conv2D(128, kernel_size=3, padding="same", activation = 'relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))

from keras.layers.core import Activation

model.add(Flatten())
# model.add(Dense(units=1000, activation='relu'  ))
model.add(Dense(units= 300, activation='relu'))
model.add(Dropout(0.2))

model.add(Dense(1))
model.add(Activation("softmax"))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

from keras.preprocessing.image import ImageDataGenerator

datagen = ImageDataGenerator(
    featurewise_center=True,
    rotation_range=90,
    fill_mode='nearest',
    validation_split = 0.2
    )

datagen.fit(train)

train_generator = datagen.flow(train, train_labels, batch_size=8)

# # fits the model on batches with real-time data augmentation:
history = model.fit_generator(generator=train_generator,
                    use_multiprocessing=True,
                    steps_per_epoch = len(train_generator) / 8,
                    epochs = 5,
                    workers=20)

A: Softmax should only be used if you have a multiclass classification problem. You have a single output from your Dense layer, so you should use sigmoid.


text:
Q: When is tabular data not tabular data? Okay, so we all know we're not supposed to use tables for formatting; we're supposed to used divs and CSS; tables are for tabular data.  But what is tabular data?
I run a forum for people who make model terrain.
The home page has a header, footer, menu on the left, and a space for content.  These are all defined by divs and CSS... as they should be.  :-)
However the content for the home page is a list of forums i.e. titles, number of topics, date of last post.  Tabular data methinks?
Click on a forum and you get a page whose content is a list of topics i.e. topic titles, number of posts, date of last post.  More tabular data?
Click on a topic and we have a page whose content is effectively split into two columns; the first contains the poster name, avatar, posters rank, etc,  The second column contains the post itself.  There are also "rows" that contain buttons to quote a post, report a post as abusive, etc.
I'm guessing that, at a first glance, most people would define the first two as tabular data.  The third... hmm... I think opinions might be divided?
My forum software is a hugely modified form of phpBB.  So modified in fact that the code is barely recognisable as phpBB.  I mention it because it, and as far as I'm aware, phpBB, and pretty much every other piece of bulletin board software I've seen, uses tables for this stuff.  So the fact that my site uses tables for all three of the page types I've described is inherited from the original phpBB code as opposed to being a decision I've made.
I also observe that most e-commerce software (including mine, that I use on other sites) uses table to "format" list of products on catalogue pages.  I like to keep an eye on what the "big boys" are doing with things like this and have observed that Amazon appear to be using divs for their product lists while eBay 'still' uses tables.
I've had a good look around the web for information on what's regarded as best practice and while there's a consensus that tables should only be used for tabular data and not for formatting, I am yet to see a definition of "what is tabular data" and specifically: at what point tabular data becomes content that should be formatted with divs.
On a similar note: there also seems to be a consensus that input forms such as login screens should be formatted with CSS (although it's a damned site easier to do it with a table).  It seems odd to me that a form with two titles (for username and password) and a couple of entry fields is NOT tabular data.  Yet if we were to design a screen to retrieve and display that information... well then it would be tabular data would it not?  And if not, then what the heck IS tabular data?  ;-)
Despite the last couple of sentences, this is a serious question and I'd like to know where other programmers draw the line with regard to what is, and what is not, tabular data.

A: This information should be useful to you: W3C definition of tabular data.
How you use tables is ultimately up to you. However, if you wish to be compliant with w3c standards, tables should assist users in understanding the data.
Think in terms of accessibility: if a person using a screen reader encountered your table, would the table help them understand the data or confuse them further?
A table with no summary attribute or no th or thead/tfoot elements can confuse a user.
A table containing any kind of script can confuse a user.
td elements with content that needs to be visually formatted to be understood can confuse a user.
If you are unsure of whether a set of data is tabular data, it is probably not tabular data. There are other ways to format content that are more accessible and more compliant with standards.


text:
Q: How to get better return of investment I have a mobile game, in which i have user engagement of 10 minutes and user retention day 1 of 27%, I'm doing app promotion on Google Ads, so in USA and United Kingdom my CPI in Google Ads is 0,15$, But i still have ROI = 0,4, is that not too small?
Can anyone help me on some suggestions on what makes that so small? Thanks in advance.


text:
Q: Build hybrid .Net Standard and .NetFramework solution in MSBuild Pardon the long post. I am trying to give as much info as possible.
I moved some classes from .Net Framework library into a new .Net Standard library in order to reference them from both existing .Net Framework projects and new .Net Core projects. After adding the new .net standard project to the solution that contains the other .Net Framework projects, the existing build definition (XAML) fails to build the .net standard project. It builds fine if i pass /t:restore,build as MSBuild parameters, but this breaks the build for existing .net framework projects in the solution. Visual Studio
is able to build the hybrid solution fine. I need to build it in this hybrid solution because the downstream project does the packaging and pushing to our nuget repository (OctopusDeploy).
To overcome this, I have tried to use default targets and initial targets but could not get it to go through.
See the example project below:
    <Project InitialTargets="restore" DefaultTargets="publish" Sdk="Microsoft.NET.Sdk">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <RootNamespace>MyCompany.Common</RootNamespace>
    <TargetFramework>netstandard2.0</TargetFramework>
    <AssemblyName>MyCompany.CommonStandard</AssemblyName>
  </PropertyGroup>

</Project>

With the above project file, I get this error.
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\NuGet\NuGet.targets (240): There is a circular dependency in the target dependency graph involving target "_FilterRestoreGraphProjectInputItems"

Other things I have tried:
<Project DefaultTargets="restore;build;publish"  Sdk="Microsoft.NET.Sdk">

OR
<Project DefaultTargets="restore;publish"  Sdk="Microsoft.NET.Sdk">

Error: Bunch of errors stating almost everything is undefined.  (vbc: Type 'System.String' is not defined.) Note: passing the same as msbuild targets like /t:restore,build,publish works.

<Project Targets="restore,build,publish"  Sdk="Microsoft.NET.Sdk">

OR
<Project DefaultTargets="publish"  Sdk="Microsoft.NET.Sdk">

OR
 <Project DefaultTargets="publish"  Sdk="Microsoft.NET.Sdk">
 <PropertyGroup>
  <BuildDependsOn>
   Restore;
   $(BuildDependsOn);
  </BuildDependsOn>
</PropertyGroup>

Error: \obj\project.assets.json' not found. Run a NuGet package restore to generate this file.

<Project InitialTargets="restore"  Targets="build,publish"  Sdk="Microsoft.NET.Sdk">

OR
<Project InitialTargets="restore"  Targets="publish"  Sdk="Microsoft.NET.Sdk">

Error: There is a circular dependency in the target dependency graph involving target "_FilterRestoreGraphProjectInputItems".

Thanks for reading. I would really appreciate any guidance in resolving this.

A: It turned out that my build definitions were pointing to an older version of MSBuild that did not recognize the sdk format. After changing that to MSBuild15 and using the restore,build targets, I was able to get these to work.


text:
Q: How to load specific storyboard depending on device in Objective C? This is a repost since the other one was closed.
I have trouble with auto layout, so I would just prefer to make two storyboards, iPad and iPhone. All I want is to detect the type of device it is or the size and then display their respected storyboard. I have tried just about every solution I have found on StackOverflow and I cannot get it to work.
Currently, I detect the size of the device on the AppDelegate.m under DidFinishLaunchingWithOptions then load the storyboard and set the initialViewController. When I run the iPad simulator it runs and displays correctly, and in the console it returns the correct storyboard and view controller. However, when I run the iPhone simulator it displays the iPad storyboard but in the console, it shows that it returned the iPhone storyboard and the correct initialviewcontroller.
Also, I am new to Objective-C but getting the hang of it. Thanks, hope someone can help.
Here is my App Delegate code.
#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.
    UIStoryboard *storyboard = self.window.rootViewController.storyboard;
    UIViewController *rootViewController;

    // detect screen height
    int height = [UIScreen mainScreen].fixedCoordinateSpace.bounds.size.height;
    NSLog(@"The fixed height is %i", height);

    // determine if this is an iPad
    if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {

        // it's an iPad
        if (height >= 1024) {

            storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            rootViewController = [storyboard instantiateViewControllerWithIdentifier:@"loginViewController"];

            NSLog(@"LOADING MAIN/IPAD STORYBOARD");
        }

    } else {
        // it's an iPhone
        storyboard = [UIStoryboard storyboardWithName:@"iPhone" bundle:nil];
        rootViewController = [storyboard instantiateViewControllerWithIdentifier:@"iPhoneLoginViewController"];

        NSLog(@"LOADING IPHONE STORYBOARD");
    }

    NSLog(@"Root View Controller: %@", rootViewController);
    NSLog(@"Storyboard: %@", storyboard);

    self.window.rootViewController = rootViewController;
    [self.window makeKeyAndVisible];

    return YES;
}
#pragma mark - UISceneSession lifecycle

- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}

- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

@end

Here is my Info.plist:
Info.plist Property List
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIMainStoryboardFile~ipad</key>
    <string>Main</string>
    <key>UIMainStoryboardFile~iphone</key>
    <string>iPhone</string>
    <key>UIRequiredDeviceCapabilities</key>

Below are screenshots of iPad VS iPhone Results:
iPad Simulator with its correct storyboard
iPhone Simulator showing incorrect storyboard
iPhone Storyboard

A: You don't have to detect anything. The Info.plist itself will arrange for the runtime to load a different storyboard depending on whether this is an iPad or not. There's a simple naming convention that governs this behavior: just make another key in the Info.plist ending in ~ipad.
So, if you want to have two different main storyboards, use the Info.plist naming convention: configure two "Main storyboard file base name" keys, UIMainStoryboardFile and UIMainStoryboardFile~ipad — or, with window scenes under iOS 13 and later, configure two "Application Scene Manifest" keys, UIApplicationSceneManifest and UIApplicationSceneManifest~ipad, that specify different UISceneStoryboardFile values.


text:
Q: How can one break the limit of 20 review a day?
Possible Duplicate:
Daily review limit exceeded

I just saw that the user akjoshi has reviews 21 first posts. How is that possible? I get a no-no after the 20th...
I saw it right here.

A: As far I know it is possible to increase this limit by editing a question instead of just approving/rejecting.
See also How do the review limits work?


text:
Q: joining data.frames from within two lists based on regular expression This is what my workspace looks like:
list.u = list(list.1 = replicate(n = 10,
                     expr = {data.frame(Var1 = as.factor(paste0("X", c(1:10))),
                                        Var2 = as.factor(paste0("X", c(11:20))),
                                        value=rnorm(10))},
                     simplify = F),
            list.2 = replicate(n = 10,
                      expr = {data.frame(Var1 = as.factor(paste0("X", c(1:10))),
                                         Var2 = as.factor(paste0("X", c(11:20))),
                                         value=rnorm(10))},
                      simplify = F))

list2env(list.u , .GlobalEnv )

names(list.1) <- paste0(LETTERS[1:10],"_NTI")
names(list.2) <- sample(paste0(LETTERS[1:10],"_RC")) # not the same order

###if meaningful can again be possibly converted to
###list.u <- list(list.1, list.2)

What i want to achieve is the joining of two correspondent data.frames based on the string found bevore _NTI and _RC, respectively:
library(dplyr)
df.A <- list.1$A_NTI %>% right_join(list.2$A_RC, by=c("Var1","Var2"))
df.B <- list.1$B_NTI %>% right_join(list.2$B_RC, by=c("Var1","Var2"))
df.C <- list.1$C_NTI %>% right_join(list.2$C_RC, by=c("Var1","Var2"))

and so on for every pair of matching elements of list.1 and list.2
How can i do this`?

A: You can first match the names using a simple regex, rearrange the data frames in the list, and merge one by one, i.e.
list.1 <- list.1[names(list.1)[match(sub('_.*', '', names(list.1)), sub('_.*', '', names(list.2)))]]
Map(function(i, j)merge(i, j, by = c('Var1', 'Var2'), all.y = TRUE), list.1, list.2)

which gives,

$A_NTI
   Var1 Var2      value.x    value.y
1    X1  X11  1.111072143  0.9893348
2   X10  X20  0.205016698 -1.0370611
3    X2  X12 -1.153484350 -0.1581219
4    X3  X13 -0.136188465 -0.8258913
5    X4  X14  0.845438616  1.0676754
6    X5  X15 -0.090040790 -0.6626899
7    X6  X16 -0.003032729  0.4220376
8    X7  X17  0.132374562 -0.5993826
9    X8  X18 -0.049654084  0.1161918
10   X9  X19  0.408352891 -0.4193510

$B_NTI
   Var1 Var2     value.x    value.y
1    X1  X11 -1.54096443  1.6954890
2   X10  X20  0.08418433 -1.1082467
3    X2  X12  0.77535586  0.9035127
4    X3  X13 -1.82040060  0.1870822
5    X4  X14 -1.00129026 -1.6371800
6    X5  X15  0.32455294  0.4544704
7    X6  X16  0.25704291 -0.1451332
8    X7  X17  0.61232730  2.1936744
9    X8  X18  0.43594609 -2.3836932
10   X9  X19 -0.23466536  1.3418739

$C_NTI
   Var1 Var2     value.x     value.y
1    X1  X11 -0.02400835  0.03265689
2   X10  X20 -1.78936480  1.55964999
....

...

NOTE: The merge(..., all.y = TRUE) is the base R equivalent of dplyr::right_join

A: stopifnot(length(list.1) == length(list.2))
stopifnot(length(setdiff(substr(names(list.1), 1, 1), substr(names(list.2), 1, 1))) == 0)

Looks like it'll do here to just order each list alphabetical before merging.
Map(merge, list.1[order(names(list.1))], list.2[order(names(list.2))], all.y=TRUE)


text:
Q: Error: Class 'Symfony\Component\Config\Resource\BCResourceInterfaceChecker' not found I migrated my application from symfony 2.8 to symfony 3.4.
In Web,it works perfectly. But when i launched functional tests, I had the following results:
▶ ./bin/phpunit --filter=testLanguageControllerTestIndexAction
    PHPUnit 5.7.27 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 126 ms, Memory: 14.00MB

There was 1 error:

1) Tests\TranslationBundle\Controller\LanguageControllerTest::testLanguageControllerTestIndexAction
Error: Class 'Symfony\Component\Config\Resource\BCResourceInterfaceChecker' not found

/var/www/renault-del/del/src/app/bootstrap.php.cache:3183
/var/www/renault-del/del/src/app/bootstrap.php.cache:2778
/var/www/renault-del/del/src/app/bootstrap.php.cache:2561
/var/www/renault-del/del/src/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php:174
/var/www/renault-del/del/src/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php:34
/var/www/renault-del/del/src/tests/TranslationBundle/Controller/LanguageControllerTest.php:22

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

By the way this is my composer.json :
"require": {
    "php": "^7.2",
    "course-hero/wse-php": "~2.0.5",
    "doctrine/doctrine-bundle": "^1.6",
    "doctrine/doctrine-fixtures-bundle": "^2.4",
    "doctrine/orm": "^2.5",
    "friendsofsymfony/rest-bundle" : "^2.1",
    "friendsofsymfony/user-bundle": "^2.1",
    "guzzlehttp/guzzle": "^5.3",
    "ijanki/ftp-bundle": "<1.0.3",
    "jms/serializer-bundle" : "^1.1",
    "knplabs/knp-snappy-bundle": "1.6.*",
    "natxet/cssmin": "^3.0",
    "nelmio/api-doc-bundle" : "^3.0",
    "patchwork/jsqueeze": "^2.0",
    "select2/select2": "^4.0",
    "sensio/distribution-bundle": "^5.0",
    "sensio/framework-extra-bundle": "4.0.0",
    "sonata-project/doctrine-orm-admin-bundle": "3.7.0",
    "stof/doctrine-extensions-bundle": "~1.2.0",
    "symfony/assetic-bundle": "^2.8",
    "symfony/monolog-bundle": "^2.8",
    "symfony/swiftmailer-bundle": "^2.3",
    "symfony/symfony": "3.4.*",
    "twig/twig": "^2.12",
    "friendsofsymfony/ckeditor-bundle": "^1.2",
    "white-october/pagerfanta-bundle": "^1.3",
    "liip/imagine-bundle": "^1.9",
    "friendsofsymfony/oauth-server-bundle": "^1.6",
    "psr/container": "^1.0"
},
"require-dev": {
    "friendsofphp/php-cs-fixer" : "@stable",
    "phpunit/phpunit":  "~5.1",
    "symfony/phpunit-bridge": "^5.1"
},

In addition this is the CHANGELOG from 2.8.0 to 3.0.0:
3.0.0
 * removed `ReferenceDumper` class
 * removed the `ResourceInterface::isFresh()` method
 * removed `BCResourceInterfaceChecker` class
 * removed `ResourceInterface::getResource()` method

So what can I do please ?

A: Finally I found the solution.
So, following the migration from Symfony 2.8 to symfony 3.4, you have to move the bootstrap.php.cache file from the "app" folder to the "var" folder and so, you have to modify the path of this file in the phpunit.xml configuration.
<!-- http://phpunit.de/manual/4.1/en/appendixes.configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
         backupGlobals="false"
         colors="true"
         bootstrap="var/bootstrap.php.cache"
>
    <testsuites>
        <testsuite name="Project Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>

    <php>
        <server name="KERNEL_DIR" value="app/" />
    </php>

    <filter>
        <whitelist>
            <directory>tests</directory>
        </whitelist>
    </filter>
</phpunit>


text:
Q: Show/Hide an image via button or radio button I am new to coding so I am looking for the simplest way to take and image and show or hide it based either on one button or via radio button controls. Currently the image is on as an  but i can use the any recommend method. If at all possible from a different page on my site.

A: For a button, you could use
<html>
<body>
    <script type="text/javascript">
            function addimage() {
              var img = document.createElement("img");
              img.src = "IMAGE_URL_HERE";
              img.height = IMAGE_HEIGHT;
              img.width = IMAGE_WIDTH;

              //optionally set a css class on the image
              var class_name = "foo";
              img.setAttribute("class", class_name);

              document.body.appendChild(img);
            }
     </script>
</head>
<body>
        <button onclick="addimage();">Click</button>
</body>
</html>


text:
Q: How do I only show an element if nested ng-repeat is not empty? I have a List of lists, created with a nested ng-repeat. Each outer ng-repeat contains a div with the label of its inner list (eg: "Group A"). I'm now trying to create a way to avoid showing this label if the inner list is empty due to filtering(Applied by an input searchtext)
Here is a plunker explaining my issue and my attempted solution : Plnkr
Having a 'heavy' function like isGroupEmpty seems extremely cumbersome - Is there any way to do this in a much simpler fashion? I was toying with the idea of moving the label inside the inner ng-repeat and having ng-show="$first" but it doesnt look great

A: I ended up with the following solution which worked perfectly. Plnkr
By setting a variable in the inner ng-repeat I was able to evaluate ng-show based on this variables length like so :
<input ng-model='searchText'/>
 0'>

{{el.label}}

A: I used the following:

{{menuItem.itemName}}
     0'>

{{subItem.itemName}}

A: you could leverage ng-init, that way you'll call the filter only once:

{{key}}

{{el.label}}

usually it is not a good practice to use ng-init out of no where, but I guess it solves calling the filter twice.
Another way is to use the filter through javascript - you could inject $filter and retrieve 'filter' $filter('filter') in your controller, calling it with group as its first argument, the filterFn as its second, and store its result in your scope.

A: checking if an array has a length of 0 is not an expensive operation. if you want to only show lists that have item, put a filter on the outer array that takes an array of arrays and returns only the arrays that have a length different than 0.
you can also hide the inner div if the array == false.
http://plnkr.co/edit/gist:3510140
http://plnkr.co/edit/Gr5uPnRDbRfUYq0ILhmG?p=preview

A: Your plunkr was pretty complicated and hard to weed through so I re-created what you wanted using a fiddle. The general idea behind my approach is to filter out the items from the array, not the sub array. And only do the filtered items when the text changes. So here's the markup:

        <input data-ng-model="filterText" data-ng-change="updateTypes()" />

            {{ type.name }}

                    - {{ entry.name }}

And here's the code:
angular.module('app', [])

function ParentCtrl($scope){
    $scope.filterText = "";
    $scope.types = [
        { name: "type1", entries: [{ name: "name1"}, { name: "name2"}, { name: "name3"}]},
        { name: "type2", entries: [{ name: "name1"}, { name: "name3"}, { name: "name3"}]},
        { name: "type3", entries: [{ name: "name1"}, { name: "name2"}, { name: "name5"}]},
            { name: "type4", entries: [{ name: "name4"}, { name: "name2"}, { name: "name3"}]}
    ];

    $scope.filteredTypes = [];
    $scope.updateTypes = function(){
        $scope.filteredTypes.length = 0;
        for(var x = 0; x < $scope.types.length; x++){
            if($scope.filterText === ""){
                $scope.filteredTypes.push($scope.types[x]);
            }
            else{
                var entries = [];
                for(var y = 0; y < $scope.types[x].entries.length; y++){
                    if($scope.types[x].entries[y].name.indexOf($scope.filterText) !== -1){
                       entries.push($scope.types[x].entries[y]);
                    }
                }
                if(entries.length > 0){
                    $scope.filteredTypes.push({
                        name: $scope.types[x].name,
                        entries: entries
                    });
                }
            }
        }
    }
    $scope.updateTypes();
}

Fiddle: http://jsfiddle.net/2hRws/
The reason I'm creating a new array and not using an actual filter to remove the results is that angular doesn't like creating dynamic arrays on the fly in filters. This is because it doesn't assign $$hashKey and things just don't line up correctly when dirty checking. I got the idea of how to do what you needed from this topic on the matter: https://groups.google.com/forum/#!topic/angular/IEIQok-YkpU

A: I have only slightly modified your list-widget.html, see it in action: plunkr
The idea is simple - use the same filter for ng-show:

{{ key }}

The label will be visible only if there are some unfiltered items.
In my example I'm using searchText for filter because I'm not familiar with CoffeeScript.


text:
Q: Xamarin Forms app getting stuck on SplashScreen I have a class SplashScreen where I show an image scaling and after it finishes scaling it goes to a login page. I tried this on multiple devices and only in one device it doesn't change from the SplashScreen.
I've been researching how to handle async methods and await instructions but nothing seems to work so far. Also I tried removing the ScaleTo and just show the image but it doesn't work.
This is what I have:
protected override async void OnAppearing()
{
     base.OnAppearing();
     await splashLogo.ScaleTo(1.5, 3000);
     ShowLogin();
}

A: I solved this problem by adding this class:
class MainPageViewModel : BaseViewModel
{
    private bool isLoadingData;

    public bool IsLoadingData
    {
        get => isLoadingData;
        set => SetProperty(ref isLoadingData, value);
    }

    public async Task LoadData()
    {
        IsLoadingData = true;
        await Task.Delay(2000);
        IsLoadingData = false;
    }
}

Then in my SplashScreen page:
public SplashScreen()
{
    //Everything else I need in this page
    BindingContext = new MainPageViewModel();
}

private MainPageViewModel ViewModel => BindingContext as MainPageViewModel;

protected override async void OnAppearing()
{
    base.OnAppearing();
    await ViewModel.LoadData();
    ShowLogin();
}


text:
Q: Windows Application (C#.Net)- Retain TextBox Values Here is my Scenario: (Windows Application/C#.Net)
I have a Form1 in that is doing some calculations with the option selected as Case 1 and On Button Click it Pushes all the textbox values to Form2. This is working fine.
Now if I come to Form 1 again and change the option to case 2 and calculate and press Button it erases the values that were added earlier.
I want to retain those values and add this values to another set of textboxes that are in Form2.
Code: In Form 1 After Clicking ADD button:
private void button1_Click(object sender, EventArgs e)
    {
        Form2 eigthForm = new Form2();
        if(comboBox1.Text == "Case 1")
        {
            eigthForm.text2.Text = textBox1.Text;
            eigthForm.text3.Text = textBox8.Text;
        }
        if (comboBox1.Text == "Case 2")
        {
            eigthForm.text4.Text = textBox1.Text;
            eigthForm.text5.Text = textBox8.Text;
        }

A: Here's an option
Form2 inst = null;
private void button1_Click(object sender, EventArgs e)
    {
        if(inst == null)
           inst = new Form2();

        if(comboBox1.Text == "Case 1")
        {
            inst.text2.Text = textBox1.Text;
            inst.text3.Text = textBox8.Text;
        }
        if (comboBox1.Text == "Case 2")
        {
            inst.text4.Text = textBox1.Text;
            inst.text5.Text = textBox8.Text;
        }

 inst.Show();

}

A: Ok I understand what you are asking now. You can use the Singleton pattern as one way as follows
Form1 buttons
private void button1_Click(object sender, EventArgs e)
{
    Form2.Instance.AddText1and2("Hello", "World");
}

private void button2_Click(object sender, EventArgs e)
{
    Form2.Instance.AddText3("Foo");
}

Form2 we will change to Singleton pattern
   private static volatile Form2 instance = null;
    private static object lockThis = new object();

    private Form2()
    {
        InitializeComponent();
    }

    public static Form2 Instance
    {
        get
        {
            if (instance == null)
            {
                lock(lockThis)
                {
                    if (instance == null)
                    {
                        instance = new Form2();
                    }
                }
            }
            return instance;
        }
    }

Now our methods to place text in the correct places
public void AddText1and2(string txt1, string txt2)
    {
        textBox1.Text = txt1;
        textBox2.Text = txt2;
        this.Show();
    }

    public void AddText3(string txt3)
    {
        textBox3.Text = txt3;
        this.Show();
    }

If you want to be able to close the window and reopen it saving values you need to use the form closing event
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        this.Hide();
        e.Cancel = true;
    }

You have to prevent the actual close. This will dispose the object and we don't want that.
This will keep all your settings in form 2.

if you don't want to do the above you can add a new class to your project doing something like this
class Global
{
    public static string Value1 { get; set; }
    public static string Value2 { get; set; }
}

in Form1
if(comboBox1.Text == "Case 1")
{
        Global.Value1 = textBox1.Text;
        Global.Value2 = textBox8.Text;
}

in Form2 load event
text2.Text = Global.Value1;
text3.Text = Global.Value2;

You should also revise your if logic
The combobox will never == "Case 2" if it's "Case 1" but you
Are still running the next if statement
You should use something like this
if(comboBox1.Text.Equals("Case 1"))
{
}
else if (comboBox1.Text.Equals("Case 2"))
{
}

OR
switch (comboBox1.Text)
{
    case "Case 1":
        //do stuff
    break;
    case "Case 2":
        //do stuff
    break;
}


text:
Q: How to Print Completed Web Form This is probably very simple but here goes - I need to put a form on my site for the users to fill in, however I need them to be able to print the completed form and mail it as opposed to submit it to me elctronically.
I have no problem creating the form, however the normal print command prints just the form without what the user has filled in, therefore is it possible to send the completed form to the printer?
Suggestions gratefully received!

A: I would solve this having them submit the form, and then rendering the information cleanly so that the resulting page could be printed.
If you are dead set on having them print without first submitting the form, look at this question: Printing HTML Form using window.print()


text:
Q: How accurate and reliable is loudness analysis (ebur128) in ffmpeg for PCM? I need to test a lot of files on possible audio normalization issues, files can be of various containers and audio encoding formats but mostly PCM audio. I tried Rhozet QC solution but found it unreliable, it could easily skip short loud spikes so now I'm looking at ffmpeg.
I tested it and it looks ok-ish but does anyone have any experience with such tasks? Can I trust ffmpeg with that?

A: The EBU provides a set of sample PCM audio files to audit loudness measuring equipment. Based on testing a few random files from the set, ffmpeg's EBU R128 analyzer passes. But you may want to do a thorough survey.
Result for 1kHz Sine -20 LUFS-16bit.wav
  Integrated loudness:
    I:         -20.0 LUFS
    Threshold: -30.0 LUFS

  Loudness range:
    LRA:         0.0 LU
    Threshold: -40.0 LUFS
    LRA low:   -20.0 LUFS
    LRA high:  -20.0 LUFS

Result for 1kHz Sine -26 LUFS-16bit.wav
  Integrated loudness:
    I:         -26.0 LUFS
    Threshold: -36.0 LUFS

  Loudness range:
    LRA:         0.0 LU
    Threshold: -46.0 LUFS
    LRA low:   -26.0 LUFS
    LRA high:  -26.0 LUFS


text:
Q: Why are games starting to refuse Users\Public\Games as the install target? I usually install games to C:\Users\Public\Games (Windows 7 x64) so that I don't run into permissions issues (especially while updating), but recently, I've run into a couple of installers that absolutely refuse to install there stating

Cannot install game into chosen directory.  Please choose another.

I've made a symbolic link to the Public\Games folder elsewhere and that seems to be a good workaround since the installer is quote happy to install there.
I've checked the permissions and given "Everyone" full control.
This appears to be a limit imposed by the installer itself and not the OS, anyone know WHY that has started to be the norm? Is there a better (more elegant) workaround? Is there some security issue that I've missed?

A: My guess would be due to licensing restrictions of the game -- I.e. you have got a license to use the software for one user on one machine.   Putting it into a Public and/or Shared directory would allow more than one user to run the same game, and they naively try to avoid that by looking for specific directory names.


text:
Q: Cakephp use numeric values with quote as string is not working I want generate following query.
SELECT `Scale`.`id`, `Scale`.`name`
FROM `woa`.`scales` AS `Scale`
WHERE `Scale`.`enabled` = '1'

So i wrote following lines in cackphp controller.
$this->set('scales', $this->Scale->find('list', array(
    'conditions' => array('Scale.enabled' => '1')
)));

But it generate following query with out quotation in Scale.enabled value.
SELECT `Scale`.`id`, `Scale`.`name`
FROM `woa`.`scales` AS `Scale`
WHERE `Scale`.`enabled` = 1

How can i use quotations with numeric (bt actually it is string) value?

A: CakePHP handles the quotes according to the actual column datatype. But if you really want to force quotes try this:
$this->set('scales', $this->Scale->find('list', array(
    'conditions' => array("Scale.enabled='1'")
)));


text:
Q: Fetching Request param in Python Quart I am trying to convert my flask app to Quart ASGI, facing an issue when try to fetch request param/argument.
It gives an error when normal request is used with Quart
Example:
@app.route('/')
async def hello():
    return function(request.args.get('requestID'))

Not able to fetch param argument using request.args.get('requestID') in Quart