text:
Q: What module can strip debugs in webpack solutions? I am running a reactjs app with gulp/webpack and tried this:
https://github.com/yahoo/strip-loader.
However it does not work( throws errors in my reactjs code). How to get it working or what is another solution?
EDIT
I added this to the loaders section of the webpack.config:
new webpack.optimize.UglifyJsPlugin({
    drop_debug: true
})

I have installed the plugin with npm but it does not filter the debugger statements from my reactjs code?

A: You can use UglifyJsPlugin() and pass the drop_debugger: true property.
To utilize this property you need to pass it to the compress property inside of the options argument.
new webpack.optimize.UglifyJsPlugin(
  compressor: {
    drop_debugger: true
  }
);

This is an UglifyJS specific property and webpack can pass those directly through compress. Ironically looking at the source of the plugin it can also take the property compressor as an alt property.

A: you can use strip-loader plugin in webpack.
var WebpackStripLoader = require('strip-loader');
WebpackStripLoader.loader('console.log', 'console.error', 'debugger')


text:
Q: "Cannot convert object to a function" with mutate I get the following error
Error in mutate_impl(.data, dots) :
  Cannot convert object to a function: [type=NULL; target=CLOSXP, SPECIALSXP, or BUILTINSXP].

When running this code on an clean session
library(dplyr)
dplyr::mutate(data.frame(aa = c(1,2,3,4)),bb = aa/2)

This is the session info
R version 3.4.4 (2018-03-15)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.5 LTS

Matrix products: default
BLAS: /usr/lib/libblas/libblas.so.3.6.0
LAPACK: /usr/lib/lapack/liblapack.so.3.6.0

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8
 [6] LC_MESSAGES=en_US.UTF-8    LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] bindrcpp_0.2.2 dplyr_0.7.4

loaded via a namespace (and not attached):
 [1] compiler_3.4.4   magrittr_1.5     assertthat_0.2.0 R6_2.3.0         tools_3.4.4      pillar_1.2.1     glue_1.2.0       rstudioapi_0.7
 [9] tibble_1.4.2     yaml_2.1.18      crayon_1.3.4     Rcpp_1.0.1       pkgconfig_2.0.1  rlang_0.4.0      bindr_0.1.1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Нереальная ошибка при компиляции android приложения При компиляции в ANdroid Studio выдает следующую ошибку: Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2

Что же это такое?


text:
Q: Pandas dataframe having an additional "layer" Suppose you have the following dataframe:
import pandas as pd
import numpy as np

df = pd.DataFrame(np.nan,columns=['A','B','C'],index=[0,1,2])

Suppose I want an additional "layer" on top of this pandas dataframe, such that column A, row 0 would have its value, column B, row 0 would have a different value, column C row 0 would have something, column A row 1 and so on. So like a dataframe on top of this existing one.
Is it possible to add other layers? How does one access these layers? Is this efficient, i.e. should I just use a separate data frame all together? And one would save these multiple layers as a csv, by accessing the individual layers?, or is there a function that would break them down into different worksheets in the same workbook?

A: pandas.DataFrame cannot have 3 dimensions:

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.

However, there is a way to fake 3-dimensions with MultiIndex / Advanced Indexing:

Hierarchical indexing (MultiIndex)
Hierarchical / Multi-level indexing is very exciting as it opens the door to some quite sophisticated data
  analysis and manipulation, especially for working with higher
  dimensional data. In essence, it enables you to store and manipulate
  data with an arbitrary number of dimensions in lower dimensional data
  structures like Series (1d) and DataFrame (2d).

If you really need that extra dimension go with pandas.Panel:

Panel is a somewhat less-used, but still important container for 3-dimensional data.

but don't miss this important disclaimer from the docs:

Note: Unfortunately Panel, being less commonly used than Series and
  DataFrame, has been slightly neglected feature-wise. A number of
  methods and options available in DataFrame are not available in Panel.

There is also pandas.Panel4D (experimental) in the unlikely chance that you need it.


text:
Q: Around fixed point of renormalization group In the general formulation of renormalization group in "statistical mechanics" by P.K.Pathria, each point in parameter space is represented by a vector $\vec{K}$ and the transformed vector would be given by
$$\vec{K}'=R(\vec{K})$$
If we look at what happens when it gets very close to the fixed point $\vec{K}^*$, then we would have
$$\vec{K}'=\vec{K}^*+\vec{k}'=R(\vec{K}^*+\vec{k})+\mathcal{O}(k_i^2) $$
where both $\vec{k}'$ and $\vec{k}$ will be very small.
Now the problem is that in this book, the author directly puts
$$R(\vec{K}^*+\vec{k})=R(\vec{K}^*)+R(\vec{k})=\vec{K}^*+R(\vec{k})$$
and then conclude that the two deviations are related by
$$\vec{k}'=R(\vec{k})$$
The step $R(\vec{K}^*+\vec{k})=R(\vec{K}^*)+R(\vec{k})$ looks obviously problematic to me, or did I miss anything?

A: It turns out to be a mistake in this version of the book (2nd edition), I checked the latest version (3rd edition) and it has been corrected there. Naturally, the corrected one would be
$$R(\vec{K}^*+\vec{k})=R(\vec{K}^*)+R'(\vec{K}^*)\vec{k}+...$$
which after linearization simply becomes $\vec{K}^*+R'(\vec{K}^*)\vec{k}$, and then we have a linearized relation between $\vec{k}'$ and $\vec{k}$, which is
$$\vec{k}'=R'(\vec{K}^*)\vec{k}$$

A: You missed the fact that this operator $R$ is a linear operator, at least for sufficiently small $\vec{k}$. This is a linearization of the renormalization group transformation around the fixed point $\vec{K}^*$. Let $T$ be a renormalization group transformation. If you expand around the fixed point $\vec{K}^*$ you get:
$$
T(\vec{K}^*+\vec{k})=T(\vec{K}^*)+[T^{(1)}(\vec{K}^*)]\vec{k}+\mathcal{O}(k_i^2)
$$
Where $[T^{(1)}(\vec{K}^*)]$ is a linear operator acting on $\vec{k}$. Actually, making $R=T$ until first order in $k$ give us:
$$
R(\vec{K}^*+\vec{k})=T(\vec{K}^*)+[T^{(1)}(\vec{K}^*)]\vec{k}
$$
and
$$
R(\vec{K}^*+\vec{0})=T(\vec{K}^*)=\vec{K}^*
$$
$$
[T^{(1)}(\vec{K}^*)]\vec{k}=R(\vec{K}^*+\vec{k})-\vec{K}^*=(\vec{K}^*+\vec{k}')-\vec{K}^*=\vec{k}'
$$
Then $R$ is an affine transformation and $R(\vec{K}^*+...)-\vec{K}^*$ is a linear transformation. So, what the author realy mean is:
$$
\vec{k}'=R(\vec{K}^*+\vec{k})-\vec{K}^*=[T^{(1)}(\vec{K}^*)]\vec{k}
$$


text:
Q: How to handle nulls in IEqualityComparer? The following method is from XUnit Assert class:
public static void Equal<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer);

And I am using it as:
IEnumerable<Decimal?> x = getXValues();
IEnumerable<Decimal?> y = getYValues();

Assert.Equal(x, y, new DecimalToleranceEqualityComparer(0.01m));

I am using an IEqualityComparer because is fine to consider 2.526 equal to 2.524.
I get an error because DecimalToleranceEqualityComparer is only for Decimal ...
x and y might have null values. DecimalToleranceEqualityComparer is:
  public class DecimalToleranceEqualityComparer : IEqualityComparer<Decimal> {

    private readonly Decimal _tolerance;

    public DecimalToleranceEqualityComparer(Decimal tolerance) {

      _tolerance = tolerance;

    }

    public Boolean Equals(Decimal x, Decimal y) {

      return Math.Abs(x - y) <= _tolerance;

    }

    public Int32 GetHashCode(Decimal obj) {

      return obj.GetHashCode();

    }

  }

I suppose if 2 values are nulls they should be consider equal ...
How to change the IEqualityComparer so that it handles nulls?

A: This code works for me. The real trick is in the imlementation of the Equals method. Also keep in mind the null check in the GetHashCode.
static void Main(string[] args)
{
    IEnumerable<Decimal?> x = new List<Decimal?> { 1.51m, 3, null };
    IEnumerable<Decimal?> y = new List<Decimal?> { 1.6m, 3, null };

    Assert.Equal(x, y, new DecimalToleranceEqualityComparer(0.1m));
}

public class DecimalToleranceEqualityComparer : IEqualityComparer<Decimal?>
{
    private readonly Decimal _tolerance;

    public DecimalToleranceEqualityComparer(Decimal tolerance)
    {

        _tolerance = tolerance;

    }

    public Boolean Equals(Decimal? x, Decimal? y)
    {
        if (!x.HasValue && !y.HasValue)
        {
            // Both null -> they are equal
            return true;
        }
        else if (!x.HasValue || !y.HasValue)
        {
            // One is null, other is not null -> not equal
            return false;
        }
        else
        {
            // both have values -> run the actual comparison
            return Math.Abs(x.Value - y.Value) <= _tolerance;
        }
    }

    public Int32 GetHashCode(Decimal? obj)
    {
        if (obj.HasValue)
        {
            return obj.GetHashCode();
        }
        else
        {
            // Here decide what you need
            return string.Empty.GetHashCode();
        }
    }
}

A: One option that comes to mind could be implementing new equality comparer for nullable decimal type IEqualityComparer<decimal?> which could use your existing DecimalToleranceEqualityComparer internally. Something like
public Boolean Equals(Decimal? x, Decimal? y) {
    return (x.HasValue && y.HasValue)?
     _decimalToleranceEqualityComparer.Equals(x.Value,y.Value)
    : x == y;
}

A: You are supplying a list of Nullable<decimal>'s and your IEqualityComparer is expecting a list of Decimal's.
With a rewrite like this you should be fine:
public class DecimalToleranceEqualityComparer : IEqualityComparer<decimal?>
{
    private readonly decimal _tolerance;

    public DecimalToleranceEqualityComparer(decimal tolerance)
    {
        _tolerance = tolerance;
    }

    public bool Equals(decimal? x, decimal? y)
    {
        if (!x.HasValue && !y.HasValue) return true;
        if (!x.HasValue || !y.HasValue) return false;

        return Math.Abs(x.Value - y.Value) <= _tolerance;
    }

    public int GetHashCode(decimal? obj)
    {
        return obj.GetHashCode();
    }
}


text:
Q: image shadow in drag and drop on grid view? I am trying to make an android application in which if you drag image in gridview the images to clone moves with the finger to other position. How could I achieve this ? . I have seen codes from here, but was unable to understand how to convert it for grid view .
found one more tutorial here But still could not figure out how to change it for grid view.....any suggestions or help...

A: Try this.
http://blahti.wordpress.com/2012/03/03/improved-drag-drop-for-gridview/


text:
Q: How to get corresponding values in two lists So I have two lists called A and C that each have the same amount of data points stored in them. I have created a new list called E that contains values in C that are greater than 400.
I need to make a plot of E vs. A
My question is how do I get the corresponding values that I gained from creating E from the list A so that I can make a plot?
Is there a way to grab the data from A that corresponds with E which might make a new list I could plot? Thanks.
The data I am using is quite a large list, but here is an example:
    xpos,ypos,measurement,error
    96.54, 92.10, 236.69, 23.67
    26.26, 17.36, 457.55, 45.76
    96.15, 52.22, 369.31, 36.93
    53.23, 56.85, 630.77, 63.08
    82.48, 97.64, 198.24, 19.82

I have removed the headers and created four lists for each data column: A for the xpos, B for the ypos, C for measurement, and D for error.
C, or measurement is the data set that I edited to be E which has values over 400. I want to get the values from A (xpos) that match up across the row from the values over 400 in C (or measurement).
I am trying to plot in iPython notebook the list I got from E vs. the corresponding values in A.

A: I would do this by ziping A and C together before calculating E:
E_pairs = [pair for pair in zip(A, C) if pair[1] > 400]

That will give you a list of tuples of A and C values where C is over 400.

A: A=[100,300,400,200,500]

B=['a','b','c','d','e']

E=[[a,b] for a,b in zip(A,B)]

my_list=filter(lambda x:x[0]>400,E)

A: If the lists are the same size you can use enumerate and make lists of each:
final_a = []
final_c = []
for ind, x in enumerate(C):
    if x > 400:
        final_c.append(x)
        final_a.append(A[ind])


text:
Q: Google Guava Predicates.or() or Predicates.and() type In Guava, there is a utilities kind of method for Predicates class called 'or' or 'and', you can either pass a iterable or two predicates.
I have a code example like below:
class AccountNamePredicate implements Predicate<Account> {}
class AccountTypePredicate implements Predicate<Account> {}
class AccountManager {
    public Predicate<Account> getPredicate() {
         return Predicates.and(new AccountNamePredicate(), new AccountTypePredicate());
    }
}

My question is for the method getPredicate in AccountManager class, how can I test the method?
If I want to assert the return type of this method, how can I write the correct code. My assert statement below doesn't pass:
assertThat(getPredicate(), is(instanceOf(Predicate.class)));

Any idea about that?

A: There is nothing to test in your scenario. If you insist on test that you're testing the guava framework (guava development team already do that well) not your application.


text:
Q: How do I get a clickable link for this?
Your download link <?php echo "http://mysite.com/superupload/upload/" . $_FILES["upload"]["name"]; ?>

Okay well that's the code that I got and yeah it displays the file url but if I go to the url it displays an image if I upload an image which is great BUT I want it to be downloadable rather than viewable. Also I could do with the echo being a clickable echo link.
Hope you understand what I mean I basically want it a clickable link to down the file.

A:
<a href="<?php echo "http://mysite.com/superupload/upload/" . $_FILES["upload"]["name"]; ?>"> Your download link

might do it...


text:
Q: Why is the imported Angular/TypeScript model not properly mapping over to my service in Angular application? I am designing a system that tracks mutual fund information entered manually by the user, and am having difficulties getting the application to properly read the properties I have created for my 'fund' model. I get the following error in the Developer Tools console:
ERROR TypeError: Cannot read properties of undefined (reading 'map')
    at funds.service.ts:18
    at map.js:7
    at OperatorSubscriber._next (OperatorSubscriber.js:9)
    at OperatorSubscriber.next (Subscriber.js:31)
    at map.js:7
    at OperatorSubscriber._next (OperatorSubscriber.js:9)
    at OperatorSubscriber.next (Subscriber.js:31)
    at filter.js:6
    at OperatorSubscriber._next (OperatorSubscriber.js:9)
    at OperatorSubscriber.next (Subscriber.js:31)

Below is the syntax for the 'Fund' service:
// funds.service.ts //

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Fund } from "./fund.model";
import { Subject } from "rxjs";
import { Router } from "@angular/router";
import { map } from "rxjs";

@Injectable({providedIn: 'root'})
export class FundsService {
  private funds: Fund[] = [];
  private fundsUpdated = new Subject<Fund[]>();

  constructor(private http: HttpClient, private router: Router) {}

  getFunds() {
    this.http.get<{ message: string, funds: any }>('http://localhost:3000/api/funds')
      .pipe(map((fundData) => {
        return fundData.funds.map(fund => {    // 'fund' to be mapped has this tip:
          return {                             // Parameter 'fund' implicitly has an 'any'
            fund_ticker: fund.fund_ticker,     // type, but a better type may be inferred from
            short_low: fund.short_low,         // usage.
            short_high: fund.short_high,
            long_low: fund.long_low,
            long_high: fund.long_high,
            id: fund._id
          };
        });
      }))
      .subscribe(transformedFunds => {
        this.funds = transformedFunds;
        this.fundsUpdated.next([...this.funds]);
      });
  }

I was under the impression that the system would be able to import the 'Fund' interface (shown below) using the 'import { Fund } from "./fund.model";' line of code. Is this not the case? Do I need to explicitly declare and define the Fund model again within the funds.service.ts file? How do I fix this issue? Below is the model interface syntax.
// fund.model.ts //

export interface Fund {
  id: string;
  fund_ticker: string;
  short_low: number;
  short_high: number;
  long_low: number;
  long_high: number;
}

Any and all help is much appreciated. Sorry if I'm not being clear enough with my question. Please let me know if I can sharpen up the phrasing or answer any questions myself to help clarify my issue.

A: Try making the type of funds an array type instead of any -
this.http.get<{ message: string, funds: Fund[] }>

Also ensure that the shape of the data being returned from the http.get matches { message: string, funds: Fund[] }. Hope this helps.


text:
Q: Java streams compare object from two streams and create new Object I have two Lists:
List<Object1> listOne = provider.getObjects().stream().collect(Collectors.toList());
List<Object2> listTwo = provider2.getObjects().stream().collect(Collectors.toList());

Now I want create List containg all possible Object1-Object2 combinations: List<ObjectCombinations> result;
class ObjectCombinations {
    Object1 object1;
    Object2 object2;

    public ObjectCombinations(Object1 object1, Object2 object2)  {
        this.object1 = object1;
        this.object2 = object2;
    }
}

How is that possible with java 8 streams?

A: You can use flatMap to get all the combinations:
List<ObjectCombinations> result =
    listOne.stream()
           .flatMap(o1 -> listTwo.stream()
                                 .map(o2 -> new ObjectCombinations(o1,o2)))
           .collect(Collectors.toList());

First you create a Stream<Object1>, then you use flatMap to combine each element of that stream with all the elements of listTwo, and create the ObjectCombinations instances, which you collect to a List.

A: You can use flatMap where you can stream over 2nd list and create ObjectCombinations and flatten the list.
List<ObjectCombinations> res =
       listOne.stream()
              .flatMap(a -> listTwo.stream().map(b -> new ObjectCombinations(a,b)))
              .collect(Collectors.toList());


text:
Q: Explorer Android Device MFC using VS2010 - WinXP, Win7 and Win8
My application lists the content of folders with drive letters ("c:\") withour problems. But if failed with the folders that you get when you plug your android phone (or similar device) into a windows PC.
I use the standard CFileFind with FindFile and FindNextFile but no file are retrieved. I add the path directly as it appears in Windows Explorer .. For example, for my Samsung device, it is: \\GT-S7562\Card\DCIM\Camera
Any clues how to do this ?
Thanks for your help
Thierry


text:
Q: Xubuntu. Wireless network disappears! After installing Security Onion with Xubuntu(12.4.3-20130904.iso) on my machine my wireless network disappears completely. It's not visible in Network Settings with the icon in the bar also gone!? Any help is appreciated. Thanks, D.

A: You can start the icon in the bar manually in a terminal by:
nm-applet

Security Onion is a separate distro based on xubuntu, so i think they use their own tools to manage the wireless interface. Here are a few things you can try:
Check if your wireless interface is recognized as a wireless interface by:
iwconfig

it should output something like this:
lo        no wireless extensions.

wlan0     IEEE 802.11bgn  ESSID:off/any
          Mode:Managed  Access Point: Not-Associated   Tx-Power=14 dBm
          Retry  long limit:7   RTS thr:off   Fragment thr:off
          Encryption key:off
          Power Management:off

eth0      no wireless extensions.

Check if your wireless interface is soft or hard blocked:
rfkill list wlan

Possible output:
0: sony-wifi: Wireless LAN
        Soft blocked: yes
        Hard blocked: no
3: phy0: Wireless LAN
        Soft blocked: yes
        Hard blocked: yes

Hard blocked means it is blocked by a hardware switch on your device.
Soft Blocked means an application (like Network Manager) is blocking it, as in my case.
Unblock blocked wireless device:
rfkill unblock wlan

It's obvious you can't unblock a hardware switch, besides with magic =)
Check if your wireless interface is managed by Network Manager:
nm-tool

In case of yes output looks like this:
- Device: wlan0 ---------------------------------------------------------------
  Type:              802.11 WiFi
  Driver:            iwlwifi
  State:             disconnected
  Default:           no
  HW Address:        8C:A9:82:52:CA:2A

  Capabilities:

  Wireless Properties
    WEP Encryption:  yes
    WPA Encryption:  yes
    WPA2 Encryption: yes

If no, you see State: unavailable:
- Device: wlan0 ---------------------------------------------------------------
  Type:              802.11 WiFi
  Driver:            iwlwifi
  State:             unavailable
  Default:           no
  HW Address:        8C:A9:82:52:CA:2A

  Capabilities:

  Wireless Properties
    WEP Encryption:  yes
    WPA Encryption:  yes
    WPA2 Encryption: yes

Check if your wireless interfaces is not in the /etc/network/interfaces file:
Network Manager is not managing an interface that is listed in this file.
Check if your wireless interface in not down:
To up the interface invoke in terminal (assumed that wlan0 is your wireless interface):
ifconfig wlan0 up

If something give errors please add them to your question.


text:
Q: How can i run nginx and node.js on one server? What kind of setup can i use to host both wordpress/php and node.js on the same server? I have a VPS from Digitalocean, an Ubuntu 12.04 server.
I have read that some use: Apache -> Nginx -> Varnish, but then again i read some places that if you have Nginx you don't need Varnish.
The solution i have now is Varnish on port 80 with 2 backends, one for Apache and one for Node.js.
Will this work for with nginx instead of Apache behind Varnish?

A: Yes, your existing setup (Varnish front-end, with Apache & Node.js backends) will work the same if you switch Apache for Nginx (i.e. Varnish doesn't particularly care about the backends - Nginx and Apache will be treated the same).
Node.js is typically run with Nginx because it is much more efficient to serve static assets directly via Nginx than through Node.js. For a simple setup you can eliminate Varnish entirely - Node.js will run on port 80 and will proxy select requests to a Node.js upstream server:
upstream nodejs  {
      server 127.0.0.1:3000;
      server 127.0.0.1:3000;
}

server {
        listen 80 default_server;
        server_name  www.example.com;
        error_log /var/log/nginx/www.example.com/error.log;
        access_log /var/log/nginx/www.example.com/access.log;
        root   /var/www/www.example.com/public;

        location / {
             try_files $uri @nodejs;
        }

        location @nodejs {
             proxy_pass  http://nodejs;
             proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
             proxy_redirect off;
             proxy_buffering off;
             proxy_set_header        Host            $host;
             proxy_set_header        X-Real-IP       $remote_addr;
             proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        }
}

One of the (previous) reasons for using Varnish in front of this setup was because Nginx did not natively support proxying HTTP 1.1 connections (which was needed for the Upgrade header used with Websockets) - this is no longer an issue, and current versions of Nginx are able to proxy websocket connections as well. That aside, if you are actually using Varnish to cache files that is a compelling reason to keep it as the front end server (although, it is worth noting that the only real gain occurs if you are using Varnish to serve cached copies of dynamically generated pages). For instance, if you have Nginx listening on port 81, and Node.js on port 3000, you might have the following in your Varnish VCL (which will serve paths from example.com/nodejs using Node.js and everything else with Nginx):
backend default {
  .host = "127.0.0.1";
  .port = "81";
}

backend nodejs{
  .host = "127.0.0.1";
  .port = "3000";
}

...

sub vcl_recv {
    set req.grace = 120s;
    ...
    if (req.http.Host ~ "^(www\.)?example.com") {
        if (req.url ~ "^/nodejs/") {
            set req.backend = nodejs;
        }
    }

    return (lookup);
}


text:
Q: I have to explain this function in C I have to indicate what the function does
 void f(char *s, const char *t) {while(*s++ = *t++) ;}

I don't understand how the condition in while is evaluated. The condition should return 1 or 0 (False or True) but in this case the content of the (*t) is assigned to (*s). How is that possible?
Can anyone help me please? Thanks =D

A: This function iterate on two pointers (sand t) and copy the value of *t into *s while the value is evaluated to true.
It's probably used to copy strings because strings in C are terminated by \0 (which is evaluated to false).
It's equivalent to do this:
while(*t)
{
    *s = *t;
    s++;
    t++;
}
*s = *t;

Or, like mcleod_ideafix has suggested, to do this:
do
{
    *s = *t;
    s++;
    t++;
}
while (*(t - 1));

A: The assignment operator returns the assigned value. So, at the first character equal to zero the function will return (after copying it). This function could be good for example to copy a null terminated string.
In C, any value that is not zero is considered "true".

A: while(*s++ = *t++) ;

This while will copy *t to *s till *t becomes 0. Value of assignment operator is used to check condition, when it reaches to NULL (0) loop ends.

A: In C, an assignment is also an expression (this is different in many other languages but allows for natural chaining of assignments). The value of the expression is the value of the left side after the assignment. That value (here: the character at s before it is incremented) is not zero until the end of the string is reached (and the zero byte there has been copied), terminating the loop.

A: The way of working can be found in the precedence of operators.
The *operator has the highest priority, when it references to the specific character of the pointer.
After the assignment will come the ++operator which is placed after the variable (right handled) and increases the booth pointers to point to the next characters in the string.
The result of the evaluation which was be stored in the character pointed of s will be in the same time the result of the while condition. The while ends when a '\0' value was be assigned.


text:
Q: Compact Framework 3.5 image Gradient not smooth Why doesn't compact framework 3.5 render Images with gradient right on windows mobile?

A: If your image contained originally 32 bits or 24 bits of color and your device LCD only supports 16 bits (which is usually the case) then you will see some degradation on the image quality while displaying it.


text:
Q: AWS CDK - Logical ID keeps changing for HttpsRedirect (aws-route53-patterns) I'm running into an issue where I have a stack that uses HttpsRedirect from aws-route53-patterns.
It's part of my Codepipeline and every time I release a change (even without changing any code) the logical ID is recreated, and different (which I didn't think was supposed to happen).
All my other stacks behave normally, but it seems that the HttpsRedirect construct gets a new Logical ID each time and then fails because the Route53 records it tries to create a resource that already exist.
Here's my stack:
export class CdnStack extends cdk.Stack {

  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const domainName = ssm.StringParameter.valueForStringParameter(
      this,
      `/env/domainName`,
      1
    );

    const hostedZoneId = ssm.StringParameter.valueForStringParameter(
      this,
      `/env/hostedZoneId`,
      1
    );
    const wwwDomainName = `www.${domainName}`;

    const redirect = new HttpsRedirect(this, "HttpsRedirectToWww", {
      recordNames: [domainName],
      targetDomain: wwwDomainName,
      zone: route53.HostedZone.fromHostedZoneAttributes(this, "HostedZone", {
        hostedZoneId,
        zoneName: domainName,
      }),
    });

  }
}

Here is the code in context in case it helps.
Any help is appreciated!
I've tried to update the logical ID manually but couldn't figure out the interface for the HttpsRedirect construct.

A: Looks like it's creating a hash for each domain and because I use tokens, it's changing every update/deploy. Since I use the valueForStringParameter, it has a different token each time, which is hashed into a new value too.
Here's the source code from the package that was causing the issue:
domainNames.forEach((domainName) => {
      const hash = md5hash(domainName).slice(0, 6);
      const aliasProps = {
        recordName: domainName,
        zone: props.zone,
        target: RecordTarget.fromAlias(new CloudFrontTarget(redirectDist)),
      };
      new ARecord(this, `RedirectAliasRecord${hash}`, aliasProps);
      new AaaaRecord(this, `RedirectAliasRecordSix${hash}`, aliasProps);
    });

And here is a link to the package in cdk in case it changes.
So my fix was to manually create the pattern locally, which looks like this in case anyone needs it:
export class CdnStack extends cdk.Stack {

  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const domainName = ssm.StringParameter.valueForStringParameter(
      this,
      `/env/domainName`,
      1
    );

    const hostedZoneId = ssm.StringParameter.valueForStringParameter(
      this,
      `/env/hostedZoneId`,
      1
    );

    const wwwDomainName = `www.${domainName}`;

    const zone = route53.HostedZone.fromHostedZoneAttributes(this, "MyZone", {
      hostedZoneId,
      zoneName: domainName,
    });

    const certificate = new acm.DnsValidatedCertificate(this, "Certificate", {
      domainName,
      subjectAlternativeNames: [`*.${domainName}`],
      hostedZone: zone,
      region: "us-east-1",
    });

    const redirectBucket = new s3.Bucket(this, "RedirectBucket", {
      websiteRedirect: {
        hostName: wwwDomainName,
        protocol: s3.RedirectProtocol.HTTPS,
      },
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
    });

    const redirectDist = new cloudfront.CloudFrontWebDistribution(
      this,
      "RedirectDistribution",
      {
        defaultRootObject: "",
        originConfigs: [
          {
            behaviors: [{ isDefaultBehavior: true }],
            customOriginSource: {
              domainName: redirectBucket.bucketWebsiteDomainName,
              originProtocolPolicy: cloudfront.OriginProtocolPolicy.HTTP_ONLY,
            },
          },
        ],
        viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(
          certificate,
          {
            aliases: [domainName],
          }
        ),
        comment: `Redirect to ${wwwDomainName} from ${domainName}`,
        priceClass: cloudfront.PriceClass.PRICE_CLASS_ALL,
        viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
      }
    );

    const redirectRecordProps = {
      zone,
      recordName: domainName,
      target: route53.RecordTarget.fromAlias(
        new targets.CloudFrontTarget(redirectDist)
      ),
    };

    new route53.ARecord(this, "ARedirectAliasRecord", redirectRecordProps);
    new route53.AaaaRecord(
      this,
      "AaaaRedirectAliasRecord",
      redirectRecordProps
    );
  }

Hopefully it helps someone else that gets stuck following a similar pattern.


text:
Q: problems validating user sign in from a .dat file I figured out how to write user info from a registration page to a .dat file but I am stuck at trying to validate a user on the sign in page by cross checking with the .dat if their information matches.
My sign in page code consists of this:
<?php

include "functions.inc";

// Useful variables
$datafile = "users.dat";

if (array_key_exists('submit', $_POST))
            // Function to check the password length

            {
            $the_user = $_POST['newuser'];

        // Load the file of users and store it in $users
        $users = arrayfile_to_array($datafile);

            $users = arrayfile_to_array($datafile);
            // Validate user name and password
            }
           else
            {
                $users = arrayfile_to_array($datafile);

                    // Validate the email address
    if (!user_unique($users, $the_user['newuser']))
        echo "User already exists!";

            }

            if (array_key_exists('submit', $_POST))
// Function to check the password length
            {
            header('Location: 04invoice.php');
            }
   else
   if (array_key_exists('register', $_POST))
   {
        header('Location: 03registration.php');
   }

?>
<!DOCTYPE html>

        Welcome to the Pay'N'Go Kiosk

        <form action= "<?php $_SERVER["PHP_SELF"] ?>" method="POST">

Username:

<input style="background-color: yellow; color:black" type='text' name='username'
                              value='<?php if(isset($_POST['newuser[username]']))
        echo $_POST['newuser[username]'] ?>'>

            Password:

<input style="background-color:magenta" type='password' name='newuser[password]'>

            <input type='submit' name='submit' value='Sign In'>

            Not a user? Sign up today!

            register here!
        </form>

I am trying to use arrayfile_to_array to bring up the file with all the arrays but I am lost as to how to use it.  Any tips would greatly be appreciated.
 // Open the file

    // If the file doesn't exist, create it.
    if (!file_exists($datafile))
    {
        $users = array();
        array_to_arrayfile($users, $datafile);
    }
    else
    {
        $users = arrayfile_to_array($datafile);
    }
}


text:
Q: Sinatra steam helper doesn't work require 'sinatra/base'

class Counter < Sinatra::Base
    set :server, 'thin' # 'webrick' doesn't work either
    get '/' do
        haml :index
    end

    get '/stream' do |out|
        out << 'first sentence'
            sleep 0.5
            out << 'second sentence'
            sleep 0.5

    end
    run!
end

I follow the guide in the README file, which suggests Thin server works. But it gives me a empty page whereas webrick serve the page with the two sentences altogether without the stream  effect.
Could someone let me know where I did wrong?

A: Excerpt from Sinatra:  The blog
get '/stream' do
  stream do |out|
    out << "It's gonna be legen -\n"
    sleep 0.5
    out << " (wait for it) \n"
    sleep 1
    out << "- dary!\n"
  end
end

notice line: 2 stream do |out|


text:
Q: Conditional Order by multiple columns Mysql I have a table consisting of authors, few authors have both Bio and Image, few have only image, few have only bio, and few have neither..
bio and image are stored in different columns,
I want to sort my query result (order by ) in such a way that authors that have both bio and image should come first, those which have images only should come secondary, those having bio should come in third order, and those with neither should come last.
How to write such a query..

A: You can use CASE in order by so the authors with both bio and image will be listed first the authors with image then authors with only having bio and then the rest ones
select *
from table
order by case when bio is not null and image is not null then 3
when image is not null then 2
when bio is not null then 1
else 0 end desc

A: I tried using CASE but it didn't work as per my liking, got a simpler solution to work.
Select * from mytable order by Condition1 Desc, condition2 desc, condition3 desc

A: For multiple conditional ORDER BY statements:
ORDER BY CASE category WHEN 0 THEN concat(cName,', ',bName) END DESC,
         CASE category WHEN 1 THEN concat(aName,', ',bName,', ',cName) END DESC,
         CASE category WHEN 2 THEN concat(bName,', ',aName,', ',cName) END DESC


text:
Q: ordernar lista por tamanho de palavras usando bubblesort Estou tentando usar o bubble sort para arrumar uma lista de string em ordem decrescente, mas só estou conseguindo fazer pra arrumar por ordem alfabética. Alguém saberia me dizer o que estou fazendo de errado?
arq_palavras = open('exer_1.txt', 'r')

linhas = arq_palavras.read().lower()
lista_linhas = linhas.split()
print(lista_linhas)

for i in range(len(lista_linhas)-1):
        for j in range(len(lista_linhas) -1 -i):
            if lista_linhas[j] > lista_linhas[j + 1]:
                aux = lista_linhas[j]
                lista_linhas[j] = lista_linhas[j + 1]
                lista_linhas[j + 1] = aux

print(lista_linhas)
arq_palavras.close()

o arquivo no caso tem as seguintes string:
Top Coder comp Wedn at midnight
one three five
I love cpp C
sj sa df r e w f d s v c x z sd fd a

e o output desejado seria esse, com todas as letras minusculas, e caso as strings tenham a mesma quantidade de letras, colocar então em ordem alfabética:
midnight coder comp wedn top at
three five one
love cpp c i
df fd sa sd sj a c d e f r s v w x z

A: Uma possível solução para o seu problema.
arq_palavras = open('exer_1.txt', 'r')

linhas = arq_palavras.read().lower().split('\n')

for i in range(len(linhas)):
  linha = linhas[i].split()
  for j in range(len(linha) - 1):
    for k in range(len(linha) - 1 - j):
      if len(linha[k]) < len(linha[k + 1]):
        aux = linha[k]
        linha[k] = linha[k + 1]
        linha[k + 1] = aux
      elif (len(linha[k]) == len(linha[k + 1])) and (linha[k] > linha[k + 1]):
        aux = linha[k]
        linha[k] = linha[k + 1]
        linha[k + 1] = aux
  linhas[i] = " ".join(linha)

print(linhas)
arq_palavras.close()


text:
Q: Control de FormGroup dentro de otra plantilla en Angular Tengo un modal en Angular 9, que muestra un formulario reactivo:

El formulario tiene varios campos, pero muestro en el que tengo duda ya que está un poco extenso.
<ng-template #createEvent>

    <form *ngIf="!buttonAdd" [formGroup]="createEventForm" (ngSubmit)="createEventForm.valid && onCreateEventIn()" novalidate="">

            <button type="button" class="inputs" placement="top" autoClose="outside" [ngbPopover]="popContent"  popoverTitle="Select a Map">
              {{ 'Select Map' | translate }}
            </button>

            <input class="btnAdd float-right" name="btnAdd" type="submit" value="{{'Create' | translate}}" [disabled]="!createEventForm.valid">

    </form>

</ng-template>

Cuando hago click en el botón "Select Map" se abre un PopOver que dentro debe contener unos radio button con imágenes, y el valor del radio button que se elija debe ser parte del form, pero no sé cómo decirle que ese valor será parte de él.
Este es el código de la plantilla del popOver:
 <ng-template #popContent>
  <mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group">
    <mat-radio-button class="example-radio-button" [value]="1">

    </mat-radio-button>
    <mat-radio-button class="example-radio-button" [value]="2">

    </mat-radio-button>
    <mat-radio-button class="example-radio-button" [value]="3">

    </mat-radio-button>
  </mat-radio-group>
</ng-template>

Y bueno, este sería el código typescript del formulario:

@ViewChild('createEvent') createEventTemplate: TemplateRef<any>;

  createValidatorsEventForm() {
    this.createEventForm = this.formBuilder.group({
      serie: ['', Validators.required],
      title: ['', Validators.required],
      eventDate: ['', Validators.required],
      startTime: ['', Validators.required],
      image: ['', Validators.required],
      imageSlider: ['', Validators.required],
      customerId: this.customerId,
      user: this.tokenStorage.getUser().username,
      map: ['']
    });
  }

Espero me puedan ayudar, gracias.

A: Al no tener un código de ejemplo presupongo que todo está dentro del mismo componente.
La manera más sencilla de lograr lo que pides es agregando el evento (change) a los mat-radio-button

<mat-radio-button class="example-radio-button" [value]="3"
(change)="setearValor(3)"
>

    </mat-radio-button>

Y en tu componente solo agregarias lo siguiente:
setearValor(valor){

  this.createEventForm.get("elCampoDelFormuario).setValue(valor)
}

El codigo esta echo sobre la marcha y puede contener errores ...editando...


text:
Q: Copy active cell row and insert copied row directly underneath I am trying to copy the active cell row and want to insert the copied row directly beneath that row. Like so:
Row 1   < User clicks relevant cell to trigger macro (Active Row)
Row 2   < Copied Cell gets inserted directly beneath Active Row

I want this to happen even if there is a row already below my Active Row i.e. this, when user clicks to copy Active Row:
Row 1 < Active Row
Row 2 < Other Content

Would turn into this:
Row 1 < Active Row
Row 2   < Copied Cell gets inserted directly beneath Active Row
Row 3 < Other Content

Here is my code which I have tried to put together with no luck:
'Add Tender Type Row
Dim NextRow As Range
Set NextRow = Range("B" & Sheets("Home").ActiveCell.Rows.Count + 1)
If Not Intersect(Target, Range("AF" & ActiveCell.Row)) Is Nothing And Range("AF" & ActiveCell.Row).Value = "+" Then
Sheet1.Range("B" & ActiveCell.Row & ":AF" & ActiveCell.Row).Copy
Sheet1.Activate
NextRow.PasteSpecial Paste:=1, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End If

Please can someone show me the correct way to do this?

A: You definition of NextRow was wrong, you used Sheets("Home").ActiveCell.Rows.Count + 1 instead of ActiveCell.Row + 1
Give this a try :
Sub Mark_Harris()

Dim Ws As Worksheet, _
    NextRow As Range

If Target.Cells.Count > 1 Then Exit Sub
Set Ws = ActiveWorkbook.Sheets("Home")

With Ws
    If Not Intersect(Target, .Range("AF" & ActiveCell.Row)) Is Nothing And .Range("AF" & ActiveCell.Row).Value = "+" Then
        .Rows(ActiveCell.Row + 1).Insert Shift:=xlDown
        Set NextRow = .Range("B" & ActiveCell.Row + 1)
        .Range("B" & ActiveCell.Row & ":AF" & ActiveCell.Row).Copy
        NextRow.PasteSpecial Paste:=1, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    End If
End With
Application.CutCopyMode = False

End Sub


text:
Q: Getting error " No provider for AlertIconAndTypesService!" I am using clarity module with my angular 4 code.
When using their alert box example, I am getting the above error
Example Code

                <clr-icon class="alert-icon" shape="info-circle"></clr-icon>

            ...

                Acknowledge
                Reset to green

    <button type="button" class="close" aria-label="Close">
        <clr-icon aria-hidden="true" shape="close"></clr-icon>
    </button>

Error stack details

ERROR Error: Uncaught (in promise): Error: No provider for
  AlertIconAndTypesService! Error: No provider for
  AlertIconAndTypesService!
      at injectionError (core.es5.js:1169)
      at noProviderError (core.es5.js:1207)
      at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.throwOrNull
  (core.es5.js:2649)
      at ReflectiveInjector.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.getByKeyDefault
  (core.es5.js:2688)
      at ReflectiveInjector.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.getByKey
  (core.es5.js:2620)
      at ReflectiveInjector.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.get
  (core.es5.js:2489)
      at resolveNgModuleDep (core.es5.js:9475)
      at NgModuleRef_.webpackJsonp.../../../core/@angular/core.es5.js.NgModuleRef_.get
  (core.es5.js:10557)
      at resolveDep (core.es5.js:11060)
      at createClass (core.es5.js:10913)
      at injectionError (core.es5.js:1169)
      at noProviderError (core.es5.js:1207)
      at ReflectiveInjector_.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.throwOrNull
  (core.es5.js:2649)
      at ReflectiveInjector.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.getByKeyDefault
  (core.es5.js:2688)
      at ReflectiveInjector.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.getByKey
  (core.es5.js:2620)
      at ReflectiveInjector.webpackJsonp.../../../core/@angular/core.es5.js.ReflectiveInjector_.get
  (core.es5.js:2489)
      at resolveNgModuleDep (core.es5.js:9475)
      at NgModuleRef_.webpackJsonp.../../../core/@angular/core.es5.js.NgModuleRef_.get
  (core.es5.js:10557)
      at resolveDep (core.es5.js:11060)
      at createClass (core.es5.js:10913)
      at resolvePromise (polyfills.bundle.js:3328)
      at resolvePromise (polyfills.bundle.js:3299)
      at polyfills.bundle.js:3376
      at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask
  (polyfills.bundle.js:2969)
      at Object.onInvokeTask (core.es5.js:3881)
      at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask
  (polyfills.bundle.js:2968)
      at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (polyfills.bundle.js:2736)
      at drainMicroTaskQueue (polyfills.bundle.js:3140)
      at

A: The issue is actually described in the big red box under the "Code & Examples" header in the alerts documentation on the Clarity website.
So you need to do one of two things:
1: Turn your alert into a clr-alert component.
<clr-alert>

            <clr-icon class="alert-icon" shape="info-circle"></clr-icon>

        ...

            Acknowledge
            Reset to green

</clr-alert>

2: Use the .static classname to have the AlertComponent ignore your straight HTML alert.

                <clr-icon class="alert-icon" shape="info-circle"></clr-icon>

            ...

                Acknowledge
                Reset to green

    <button type="button" class="close" aria-label="Close">
        <clr-icon aria-hidden="true" shape="close"></clr-icon>
    </button>

A: As the error suggests, import the AlertIconAndTypesService service in your module
So in your app.module.ts file
import { AlertIconAndTypesService } from "clarity-angular/emphasis/alert/providers/icon-and-types-service";

....
@NgModule({
...
providers:['AlertIconAndTypesService']
...
})

A: Make sure you have added AlertIconAndTypesService under provides inside app.module.ts
import { AlertIconAndTypesService } from 'clarity-angular/emphasis/alert/providers/icon-and-types-service';

and then,
@NgModule({
 providers: [
       AlertIconAndTypesService
    ]
})

A: Import in app.module.ts file:
import { DeviceDetectorService } from 'ngx-device-detector';
And add in providers array
providers: [
DeviceDetectorService
]


text:
Q: 'Unable to get local issuer certificate' in PHP Twitter API So I need to use the Twitter REST API in a web application I'm developing and I have written some very basic PHP code to just test whether or not I can connect to the Twitter Server. Unfortunately, whenever I try to execute the code, it crops up with an error:
Fatal error: Uncaught exception 'Exception' with message 'SSL certificate problem: unable to get local issuer certificate'
I am hosting the application currently on XAMPP 3.2.2 as a testing front so it's not officially hosted anywhere as of yet.
Here is my code with the exception of my consumer key and oauth token as they're confidential:
<?php

    require_once("TwitterAPIExchange.php");
    $url = "https://api.twitter.com/1.1/search/tweets.json";
    $twitter = new TwitterAPIExchange($settings);
    $requestMethod = "GET";
    $getField = "?q=twitter";
    $response = $twitter->setGetfield($getField)->buildOauth($url, $requestMethod)->performRequest();
    echo $response;

?>

How can I solve the SSL certificate problem? I'm not very knowledgeable about SSL and I need it to use this API in my web app.
As I've said before, I have entered my oauth and consumer details but not here as that's private information
Thanks in advance

A: You need to set up the CURL library to use a "CA certificates" file (commonly known as cacert.pem).
Basically you need to alter php.ini (example).

A: It's not recommanded, but you can alter the library and disable the CURL SSL.
On line 296, add this:
CURLOPT_SSL_VERIFYPEER => false
That should work.
enter image description here
Hope it helps.

A: XAMP has had issue with outdated root/chain certificate in curl for ages now.
If you are free to use another tool, I would suggest switching to Laragon

A: The correct answer is:
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest(true, [CURLOPT_SSL_VERIFYPEER => false]);

Reason being, they merge the 2nd parameter on performRequest with their options they pass to curl


text:
Q: Adding embedded scripting to a PHP page I have a class like this:
class Person {
    function __construct($name) {
        $this->name = $name;
    }
    function show() {
        echo $this->name;
    }
}

On my PHP page, I'd like to have a textbox that lets me either type in a custom-language script or a PHP script (without security vulnerabilities somehow) like :
PHP Example:
    $me = new Person("Alexander");
    $me->show();

And see output on the page with the result of the show() function. Obviously I don't want people writing malicious code. How is this done? I don't have any experience with this type of programming.
Examples of problem domain:
Interactive "learn php" website. User can type php in and see result without having to set up their own web server.
"Program an attack script" game. User programs their fleet AI and watches the result of the battle against the computer AI.

A: The simplest option is to run a sandboxed virtual server. You can also try the PHP sandbox, though it doesn't look to be sufficient.
Ultimately, the safest approach would be to create your own interpreters that simply don't have capabilities that would let malicious scripts perform any damaging tasks (i.e. they have no affect in the real world), which is a topic that can fill books. The interpreter translates the code into a format that can be executed by a VM, which emulates whatever system features you want to support and provides sandboxed system calls (though the latter can also be provided by interpreter libraries you create). Basing the project on a VM allows you to support multiple languages without having to create an executor for each. Microsoft's CLI and VES provide an example of this.
When it comes to books with more information, basically anything on compilers/interpreters and virtual machines is of primary relevance. For more on VMs, see also "Good literature about making a VM", "Simple Interpreted Language Design & Implementation".


text:
Q: C++ problematic function, Array to List I have this code from programing class:
void ToList(List *first, int *arr, int n) {
    List *p = first;
    for(int i=0; i<n; i++) {
       p->x = arr[i];
       if (p->next != NULL) p = p->next;
    }
}

I call it in order to transfer an Array element to a List:
int main() {

const int N = 10;
int m[N] = {5, 8, 1, 7, 2, 6, 9, 4, 0, 3};

List *first = NULL;

ToList(first, m, N);
PrintList(first);

I got a "Segmentation fault" -- the program finished with exit code 139. What is wrong and how can it be fixed?

A: It looks like you dereference a NULL pointer:
In main:
List *first = NULL;

In ToList:
List *p = first; // first = NULL
...
p->x = arr[i]

So, you need to allocate the list firstly.


text:
Q: how to check if a string is a composition of another string? I would like to know how check if a string is a composition of another in the case bellow :
isIn("xy","xyxy") -> true
isIn("xy","xyxyx") -> true
isIn("xy","xyxyy") -> false

I have done this :
isIn(X,Y) ->
case string:substr(Y,1,length(X)) == X of
    true -> true;
    false -> false
end

but I dont know how to continue checking the rest of the string .
Thank you

A: One approach is to "rotate" the substring while working through the string you're checking, comparing character by character:
is_in(_, []) -> true;
is_in([H|T1], [H|T2]) -> is_in(T1++[H], T2);
is_in(_,_) -> false.

The first clause of is_in/2 states that if we've checked the entire second argument such that it's now the empty string, then the answer is true. The second clause verifies via pattern matching that the heads of the two strings are identical, and if so, calls recursively with the head of the first string rotated to its tail and the head of the second string dropped. The final clause of is_in/2 returns false to handle the case of the heads of the strings not matching.
There are likely additional checks you need on the initial arguments, such as ensuring the length of the first string is less than or equal to that of the second string, ensuring that neither string is empty, etc.

A: There is better performant solution
is_in(S1, S2) ->
    is_in(S1, false, S1, S2).

is_in(S1, A, [H|T1], [H|T2]) ->
    is_in(S1, A, T1, T2);
is_in([_|_] = S1, _, [], S2) ->
    is_in(S1, true, S1, S2);
is_in(_, A, _, []) -> A;
is_in(_, _, _, _) -> false.


text:
Q: Can't use specific methods in Mapbox LocationEngine I was trying to set up my own navigation app, but i can't use the methods listed here: https://github.com/mapbox/mapbox-java/blob/master/mapbox/app/src/main/java/com/mapbox/services/android/testapp/nav/NavigationActivity.java
In details i'm referring at locationEngine.setInterval(0); and locationEngine.setSmallestDisplacement(3.0f); , if used Android Studio complains that they're not existing.
I've added the references to the latest mapbox-services snapshot as stated in the homepage of the github project.
What i'm missing?

A: Inside the readme, the SNAPSHOT snippet is only suggesting one dependency when Mapbox Services has 7.
repositories {
    mavenCentral()
    maven { url "http://oss.sonatype.org/content/repositories/snapshots/"}
}

dependencies {
    compile 'com.mapbox.mapboxsdk:mapbox-android-ui:2.1.0-SNAPSHOT'
}

see the documentation for more details.


text:
Q: Supervised approaches vs. topic models in sentiment analysis I am researching Sentiment Analysis over social media, particularly classifying online texts such as blog posts as positive, negative or neutral.
Most of the approaches I have found for sentiment analysis are supervised (they need labeled data to train a classifier). However, I have also found a couple of papers that do it using joint topic-sentiment models (unsupervised) like this one.
According to the results in the topic model papers, the main advantage of unsupervised approaches based on topic models is that they do no need any labeled data (apart from prior "general" sentiment information, i.e. a dictionary of positive/negative words). However, they do not reach the accuracy of a supervised approach (2% less of accuracy).
Are there any other advantages/disadvantages for using topic-sentiment models for sentiment classification instead of supervised approaches?
Thanks.

A: One disadvantage of an unsupervised method like LDA is it will generally take considerably longer to train compared to supervised methods. I'm also confused about the 2% increase you mention, based on table 2 it looks like an 8% difference between the best supervised approach they compared against and their best unsupervised model.
While I generally like the idea of "how far can you push unsupervised learning", sentiment seems like a poor fit in pracitce. I say this because sentiment analysis is one of the domains where it's easiest (cost, effort) to get labeled data due to the massive amount of reviews and review like content available on the internet. If your ultimate goal is to classify accurately, even the unsupervised paper you linked seems to suggest you will be better off spending your time scraping this data, as opposed to spending your time building dictionaries of positive negative words and incorporating priors.

A: As an additional note, by using unsupervised model, possible to have more domain specific result, especially if you are interested in a outlier domain. In that case it is not easy to find a good dataset for supervised learning thus you might need to use one of the unsupervised method. Or an semi-unsupervied method like, creating a lexicon list for your specific domain using one of the algorithm (there are some) than using that lexicon list you might classify your text with a supervised method.


text:
Q: Updating a foreign key in Entity Framework without separate id property? I have setup an entity which looks like this:
public partial class Test
{
    public Test()
    {
    }

    public int Id { get; set; }
    public virtual Test2 Test2 { get; set; }
    //and some other fields
}

test2 is another test object, with no navigation properties:
public partial class Test2
{
     public int Id {get;set;}
     public string Name {get;set;}
}

I don't have a model builder setup in the context, it just has DbSet properties for test and test2.
And I'm attempting to update a row in the database from an unattached object that I create based on user input. In this test case the Test2 property is null, and I am trying to update it to 3:
static void Main(string[] args)
{
    using(var context = new db.Model1())
    {
        var test = new db.Test();

        // we know id 1 exists for this simple test case
        test.Id = 1;

        // fake user input is 3 for test2 id
        test.Test2 = context.Test2.Where(x => x.Id == 3).FirstOrDefault();

        context.Test.Attach(test);
        context.Entry(test).State = System.Data.Entity.EntityState.Modified;
        context.SaveChanges();
    }
}

The issue is that this doesn't change the Test_Id column in the database to 3. What am I missing?
I have determined that if instead of creating the test object using new(), I query it from the context and then update, it works fine (shown below):
var test = context.Test.FirstOrDefault(x => x.Id == 2);
test.Test2 = context.Test2.FirstOrDefault(x => x.Id == 3);
context.SaveChanges();

Why does my first approach not work if I am attaching the object to the context and setting its state to modified? Can I get away with not having a separate test2_id field for the foreign key relationship, which seems redundant?


text:
Q: Select in batch mode JDBC SQL Why is there no batchSelect in JDBC?
Is there some good way to handle select for multiple keys or ids?
Creating a query matching the length of all possible keys seem silly, because the database couldn't reuse prepared statements. Using stored procedures is very database dependant.
Are their any better ways?

A: Use the IN clause. E.g.
SELECT
    id, name, value
FROM
    entity
WHERE
    id IN (1, 13, 42)

This returns the entities having an id of 1, 13 and 42 in a ResultSet with 3 rows.
Using the IN clause in a JDBC PreparedStatement is however not exactly trivial. As to how to do this, check this question: What is the best approach using JDBC for parameterizing an IN clause?


text:
Q: jquery fadein() works, but fadeout() does not This is driving me batty... this works fine:

But this does NOT work:

So, anyone know why I can fade in but not out?

A: I don't know how fadein works actually. it is supposed to be fade*I*n, same for fadeOut.


text:
Q: номер символа в ASCII у меня имеется символ, например - 'a'. нужен способ узнать его код в таблице. заранее спасибо.

A: Первое в google.com
Умение пользоваться данным поисковиком поможет Вам в дальнейшем.
char character = 'a';
int ascii = (int) character; // 97

A: Можно вот так
 char ch ='a';
 int code = (int) ch;


text:
Q: bash unable to compare multiple number conditions with bc Have tried several different syntax methods to make bash test between number ranges for floating point numbers and cannot get this to work.  Whole numbers work, so do statements without the && operator.  I must be missing something obvious.
Essentially 70 and below is "ok", between 70.1 and 79.9 is "warn", 80 and above is "critical"
Thanks in advance for any help or advice.
#! /bin/bash

number=70.1
echo $number

if (( $(echo "$number < 70" | bc -l) )); then echo "OK";fi
if (( $(echo "$number >= 70" && "$number < 80" | bc -l) )); then echo "WARN";fi
if (( $(echo "$number >= 80" | bc -l) )); then echo "CRITICAL";fi

A: echo "$number >= 70" && "$number < 80" are two commands in bash. The first is echo and the second command is "70.1 < 80" (pretty sure there is no such command on your system).
You probably wanted to write echo "$number >= 70 && $number < 80" which is just one command.
By the way: In bash you can use bc <<< ... instead of echo ... | bc.
if (( $(bc <<< "$number < 70") )); then echo "OK"; fi
if (( $(bc <<< "$number >= 70 && $number < 80") )); then echo "WARN"; fi
if (( $(bc <<< "$number >= 80") )); then echo "CRITICAL"; fi

or with restructured control flow
if (( $(bc <<< "$number < 70") )); then
  echo "OK";
elif (( $(bc <<< "$number < 80") )); then
  echo "WARN"
else
  echo "CRITICAL"
fi

A: This should be a single awk command.
awk -v n="$number" 'BEGIN {
  if      (n < 70) { print "OK"; }
  else if (n < 80) { print "WARN"; }
  else             { print "CRITICAL"; }
}'

A: Since the comparison ranges are positive integers¹, these can be compared natively by the shell if $number is first converted to an integer:
#!/usr/bin/env bash

# Defines the locale of our floating-point numbers
LC_NUMERIC=POSIX
number=70.1
echo $number

declare -i intnum

# Get decimal_point from locale (can be comma or anything locale specific)
dp="$(locale decimal_point)"

# Cut fractional part of floating-point number to a whole integer intnum
intnum="${number%$dp*}"

# Shell natively compares integer
if [ $intnum -lt 70 ]; then
  echo 'OK';
elif [ $intnum -lt 80 ]; then
  echo 'WARN'
else
  echo 'CRITICAL'
fi

*

*The integer comparison only works for positive numbers.
(-1.1 < -1 but -1 = -1)


text:
Q: how to show data in url from input text using editext i want make some process in my aplication to input some text first, after that, When user clicks the done button on the screen keyboard(using android:imeOptions="actionSearch") Isome data will show from this url :
("http://www.aaaa.com/selectAgent.htm?n="+cari_agen);

but when i make some process, there's nothing happen, my code still load all data, not specific as cari_agen, this is my source code :
public class MainActivity extends Activity {
GridView gridView;
private static final String ATASAN = "atasan";
private static final String KODE_AGEN = "kode_agen";
private static final String JENIS = "jenis";
private static final String NO_AAJI = "no_aaji";
private static final String NAMA_AGEN = "nama_agen";

List AgenList = new ArrayList();
boolean boolStatusKoneksi=true;
private ProgressDialog Dialog;
protected Context applicationContext;
EditText cari;
SearchView search;

@Override
public void onCreate(Bundle savedInstanceState){

    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainmenu);

    search=(SearchView) findViewById(R.id.searchView1);
    cari=(EditText) findViewById(R.id.search);

    cari.setOnEditorActionListener(new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
        new AgenAsyncTask().execute();
        return true;
    }
    return false;
     }
   });

}

public class AgenAsyncTask extends AsyncTask<String, String, String>
{
    String cari_agen = cari.getText().toString();
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Dialog = new ProgressDialog(MainActivity.this);
        Dialog.setMessage("Mohon Tunggu sebentar...");
        Dialog.setIndeterminate(false);
        Dialog.setCancelable(true);
        Dialog.show();
    }

    protected String doInBackground(String... args) {
    String url =("http://www.aaaa.com/selectAgent.htm?n="+cari_agen);
              try{
                  JSONParser j=new JSONParser();
                    JSONArray jsonArray = j.takeJson(url);

                  for(int i =0; i<jsonArray.length(); i++)
                  {
                  JSONObject c  = jsonArray.getJSONObject(i);
                        HashMap<String, String> map = new HashMap<String, String>();
                        if (c.has("nama_agen"))
                        Log.v(NAMA_AGEN,"Nama agen=") ;
                        map.put("nama_agen", c.get("nama_agen").toString());
                        if (c.has("atasan"))
                            map.put("atasan", c.get("atasan").toString());
                        if (c.has("jenis"))
                            map.put("jenis", c.get("jenis").toString());
                          AgenList.add(map);
                            if (c.has("no_aaji"))
                                map.put("no_aaji", c.get("no_aaji").toString());
                     }
                } catch (JSONException e) {
                    e.printStackTrace();
                    }
              return null;
                }

@Override
protected void onPostExecute(String arg)
{
Dialog.dismiss();
GridView gridview = (GridView) findViewById(R.id.gridview);
ListAdapter adapter = new SimpleAdapter(
    MainActivity.this, AgenList, R.layout.list_item,
    new String[] { NAMA_AGEN, ATASAN, JENIS,NO_AAJI }, new int [] {R.id.nama_agen, R.id.atasan, R.id.jenis,R.id.no_aaji});
gridview.setAdapter(adapter);   }

i hope somebody can help me to solve this problem, thank u


text:
Q: Trigger event (image fadein) for external div on polygon mouseover with Google Maps API V3 Been looking a while for a solution and not sure exactly how to execute this... I'm trying to have a polygon trigger an event outside of the map area.  Basically what I'm trying to figure out is how to have an image in some div fade in when the polygon is on mouseover, and fade out when at mouseout.
I tried looking at this for help but not sure exactly how to make it work that way.
http://gmaps-samples-v3.googlecode.com/svn/trunk/map_events/map_events.html

A: Without jQuery, I don't think I could have helped you. See this page:
http://jsfiddle.net/CUfZS/3/
In the javascript:
google.maps.event.addListener(polygon, 'mouseover', function(event) {
          $("#myImage").fadeIn("slow");
});

In the body:
<img id="myImage" src="https://chart.googleapis.com/chart?chst=d_bubble_icon_text_small&chld=ski|bb|Wheeee!|FFFFFF|000000" />

The image starts hidden:
 #myImage {display: none}


text:
Q: playing/pausing MP3 with JavaScript Issue I have a problem with pausing a currently playing mp3.
For an example, if I run my function like this: playSong(drake); it starts running the code out of the first part of my if statement and it's playing the MP3 out of the "drake" object and sets songValue=2
The problem is that it doesn't pause the song if I run it the second time but my console.log gets displayed in the console, so it definitely runs the second part of my if statement when I click it the second time but it doesn't pause the song for some reasons.
//object with mp3 audio
var drake = {
    value: 3,
    name: 'Energy',
    artist: 'Drake',
    audio: 'energy.mp3', //
    img: ''
};

songValue = 1;

// plays and SHOULD pause a Song
function playSong(object) {
    var Song = new Audio(object.audio);

    //plays the song
    if (songValue == 1) {

        Song.play();
        songValue = 2;

        // SHOULD pause the song when the functions is runned the second time
    } else if (songValue == 2) {
        console.log("Is it working ?"); // String to test if the "else if" gets runned
        Song.pause();
        songValue = 1;

    }
};

A: move the var Song = new Audio(object.audio) outside playSong.
You essentially make a new audio each time you call the function!
of course you would need to make changes to reference the object.audio since object is not a global.
A better way is to do like this:

//object with mp3 audio
var drake = {
  value: 3,
  name: 'Energy',
  artist: 'Drake',
  audio: 'https://www.w3schools.com/html/horse.mp3', //
  img: ''
};

songValue = 1;

// plays and SHOULD pause a Song
function playSong(object) {

  //plays the song
  if (songValue == 1) {
    var player = document.getElementById('song');
    var sourceMp3 = document.getElementById('sourceMp3');

    sourceMp3.src = object.audio;

    player.load(); //just start buffering (preload)
    player.play(); //start playing

    songValue = 2;

    // SHOULD pause the song when the functions is runned the second time
  } else if (songValue == 2) {
    console.log("Is it working ?"); // String to test if the "else if" gets runned
    var player = document.getElementById('song');

    if (!player.paused)
      player.pause();
    songValue = 1;

  }
};
<audio id="song" controls="controls">
  <source id="sourceMp3" src="" type="audio/mp3" />
  Your browser does not support the audio element.
</audio>

  <button onclick='playSong(drake)'> Play Song </button>

Referenced fiddle: http://jsfiddle.net/jm6ky/2/
Updated fiddle: http://jsfiddle.net/c6jgjewg/2/

A: You should store you Audio object in your base object like this
if (object.song == undefined){
    object.song = new Audio(object.audio);
}

And use object.song instead of the Song variable
You can user the object.song.paused(boolean) to know if the song is paused or not and launch the song again.

A: You should have 2 separate functions. One for creating the audio element, and one for playing/pausing a given audio element.
One of your problems is that every time you're calling playSong(), you're creating a whole new audio element.
Solution
var drake = {
    value: 3,
    name: 'Energy',
    artist: 'Drake',
    audio: 'energy.mp3', //
    img: ''
};

var audioElement = playSong(drake); // load song and play it

togglePlayPause(audioElement); // pause song

function playSong(object) {
    var Song = new Audio(object.audio);
    Song.play();

    return Song;
}

function togglePlayPause(audioElement) {
    if (audioElement.paused) {
        audioElement.play();
    } else {
        audioElement.pause();
    }
}

You first create the audio element and store it in a variable, using the playSong() function. Then you pass the audio element in to togglePlayPause() to toggle its playing status.
In the example, I'm playing the song and then immediately calling togglePlayPause() to pause it again.
Also, you don't need to keep the playing status in a separate variable. I've just used the .paused property on the audio element, which returns true if the player has been paused. If you really needed a separate variable, you should store it within the drake object as a new property .isPlaying.
https://jsfiddle.net/5k38da10/


text:
Q: Доступно мало оперативной памяти При запуске пк, он начал виснуть.Кое-как зашёл в «Мой компьютер» и увидел, что из 6гб оперативной памяти, доступен 1.10 гб.
Windows 7 домашняя расширенная.  64-разрядная.
Через mscofig пробовал.


text:
Q: DataTable with several type of checkbox Am using datatable with checkbox. have serveral checkbox with two type of class name.Need to check all checkbox based on class name
This is my code :-
      var exampless = $('.table1').DataTable({
        responsive: true,
        "searching": false,
        "ordering": false,
        "lengthChange": false,
         "bInfo" : false,
         className: 'select-checkbox',
     });
     $(".alluser").click(function () {
        var cols = exampless.column(0).nodes(),
        state = this.checked;

        for (var i = 0; i < cols.length; i += 1) {
        cols[i].querySelector(".User").checked = state;
        }
     });

Getting this error

TypeError: cols[i].querySelector(...) is null

A: See if this example helps:
http://live.datatables.net/legemixi/1/edit
The key part of the code to check all is this code which use DataTables API's:
$('input.checkall').on('change', function () {
  var checked = this.checked;  //get checked state of Check All or Check Page checkbox
  $('.filter-ck', table.cells().nodes()).prop('checked',this.checked);

The example also show how to check all on only the page displayed.  Also it updates the checkbox data value of 1 or 0 depending on the checkbox state.


text:
Q: setting tintColor with appearance proxy or self.view.tintColor? As per title.
What is the advantage in setting my app tint color with appearance proxy
[[UINavigationBar appearance] setTintColor:
as opposed to just with
self.view.tintColor?
Or is appearance proxy just more powerful, being able to set tabbar item appearances etc.
Lastly, does this only apply to ios7? Or is the answer to my questions universal. Thank you.

A: As apple Docs says: - Setting the tintColor property by using the appearance proxy APIs is not supported in iOS 7.
FYI
"UIAppearance protocol with iOS 5 that has greatly reduced the work required to apply a consistent style to an application. Instead of having to customise the appearance of each UIKit control directly you can customise the appearance of a whole class of UIKit controls (e.g. all the UIButtons in an application). The UIAppearance protocol works by creating an appearance proxy for the UIKit class. Modifying the appearance of the appearance proxy modifies the appearance of all subsequent instances of that class".
To customize the appearance of all instances of a class, send the relevant appearance modification messages to the appearance proxy for the class. For example, to modify the bar tint color for all UINavigationBar instances:
    [[UINavigationBar appearance] setBarTintColor:myColor];
Note for iOS7: On iOS7 the tintColor property has moved to UIView, and now has special inherited behavior described in UIView.h.
    This inherited behavior can conflict with the appearance proxy, and therefore tintColor is now disallowed with the appearance proxy.


text:
Q: Use .NET dll as COM I have a somewhat convoluted issue where I need to call a WCF web service from a SQL Server 2005 stored procedure.
While researching I discovered that the only version of .NET SQL Server 2005 will natively support it 2.0 - yet I needed to use a client to consume the web service written for .NET 4. After playing around with some workaround to try to get SQL Server to recognize a .NET 4 DLL I decided to simply create a .NET 2 CLR stored procedure and use a wrapper class written in .NET 4 exposed as COM in order to call my web service.
I found several guides dealing with how to use a .NET 4 dll with .NET 2 as a COM dll (link, link) yet am still struggling.
My "wrapper class" (.NET 4) looks like this:
namespace Wrapper
{
    [Guid("4C1D992C-4965-49B2-A694-33810A3B9775")]
    [ComVisible(true)]
    public class WrapperClass
    {
         public bool Process(Guid ID)
         {
         }
    }
}

I've added the app.manifest file as suggested by the second link above. However, when I add the generated DLL to my .NET 2 sql server project, it fails to build with the following message:
1>c:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1578,5): Warning:  MSB3274: The primary reference "Wrapper" could not be resolved because it was built against the ".NETFramework,Version=v4.0" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v2.0".

What am I doing wrong here? I tried not adding the DLL as a reference at all but then the code does not even compile.
Alternatively, is there another (easier) way I can approach this issue?
EDIT: I can't directly add a web reference either:

A: I ended up just using John Koerner's suggestion and generating a client using WSDL that didn't use System.ServiceModel. As a result I made my CLR assembly .net 2.0 and it worked fine.


text:
Q: Unexpected behavior with Struct internal values *Solved.  Thanks for the explanations guys,  I didn't fully understand the implications of using a value type in this situation.
I have a struct that I'm using from a static class.  However,  the behavior is showing unexpected behavior when I print it's internal state at runtime.  Here's my struct:
    public struct VersionedObject
    {

        public VersionedObject(object o)
        {
            m_SelectedVer = 0;
            ObjectVersions = new List<object>();
            ObjectVersions.Add(o);
        }

        private int m_SelectedVer;
        public int SelectedVersion
        {
            get
            {
                return m_SelectedVer;
            }

        }

        public List<object> ObjectVersions;//Clarifying:  This is only used to retrieve values,  nothing is .Added from outside this struct in my code.

        public void AddObject(object m)
        {
            ObjectVersions.Add(m);
            m_SelectedVer = ObjectVersions.Count - 1;
        }
    }

Test code
        VersionedObject vo = new VersionedObject(1);
        vo.AddObject(2);//This is the second call to AddObject()
        //Expected value of vo.SelectedVerion:  1
        //Actual value of vo.SelectedVersion:   1

Now,  if you test this code in isolation,  i.e., copy it into your project to give it a whirl, it will return the expected result.
The problem; What I'm observing in my production code is this debug output:
objectName, ObjectVersions.Count:2, SelectedVer:0,

Why? From my understanding, and testing, this should be completely impossible under any circumstances.
My random guess is that there is some sort of immutability going on,  that for some reason a new struct is being instanced via default constructor,  and the ObjectVersions data is being copied over, but the m_SelectedVersion is private and cannot be copied into the new struct?
Does my use of Static classes and methods to manipulate the struct have anything to do with it?
I'm so stumped I'm just inventing wild guesses at this point.

A: Struct is value type. So most likely you are creating multiple copies of your object in your actual code.
Consider simply changing struct to class as content of your struct is not really good fit for value type (as it is mutable and also contains mutable reference type).
More on "struct is value type":
First check FAQ which have many good answers already.
Value types are passed by value - so if you call function to update such object it will not update original. You can treat them similar to passing integer value to function: i.e. would you expect SomeFunction(42) to be able to change value of 42?
struct MyStruct { public int V;}
void UpdateStruct(MyStruct x)
{
  x.V = 42; // updates copy of passed in object, changes will not be visible outside.
}
....
var local = new MyStruct{V = 13}
UpdateStruct(local); // Hope to get local.V == 42
if (local.V == 13) {
  // Expected. copy inside UpdateStruct updated,
  // but this "local" is untouched.
}

A: Why is this a struct and not a class? Even better, why are you tracking the size of the backing store (List<T>) rather than letting the List<T> track that for you. Since that underlying backing store is public, it can be manipulated without your struct's knowledge. I suspect something in your production code is adding to the backing store without going through your struct.
If it were me, I'd set it up something like this, though I'd make it a class...but that's almost certainly a breaking change:
public struct VersionedObject
{

    public VersionedObject()
    {
        this.ObjectVersions = new List<object>() ;
        return ;
    }

    public VersionedObject(object o) : this()
    {
        ObjectVersions.Add(o);
        return ;
    }
    public VersionedObject( params object[] o ) : this()
    {
        ObjectVersions.AddRange( o ) ;
        return ;
    }

    public int SelectedVersion
    {
        get
        {
            int value = this.ObjectVersions.Count - 1 ;
            return value ;
        }
    }
    public List<object> ObjectVersions  ;

    public void AddObject(object m)
    {
        ObjectVersions.Add(m);
        return ;
    }

}

You'll note that this has the same semantics as your struct, but the SelectedVersion property now reflects what's actually in the backing store.


text:
Q: why html5boilerplate is stuck to V5.3.0 with old version of all Bootstrap, normalize & modernizr? I just noticed that when I download html5boilerplate V5.3.0 it comes with

*

*Bootstrap v3.3.1 (but Bootstrap v3.3.7 is available)

*normalize.css v3.0.2 (but normalize.css 7.0.0 is available)

*modernizr 2.8.3 respond 1.4.2 (but modernizr 3.5 is available)

so why html5boilerplate come with old version of Bootstrap, normalize & modernizr ?
Can I update latest version of all Bootstrap, normalize & modernizr on my own ? will that break any settings of html5boilerplate ? is it safe to update all Bootstrap, normalize & modernizr on my own ?
Again how can I update Bootstrap, normalize & modernizr into html5boilerplate ? any shortcut or something ?
or html5boilerplate is old thing now ? anything new and better then html5boilerplate came in ?
Usefull links :
1. https://html5boilerplate.com/
2. https://necolas.github.io/normalize.css/
3. http://getbootstrap.com/
4. https://modernizr.com/

A: As I shared on the Github repo, if you download the project from Github you get updated versions of almost everything (minus Modernizr which is one PR away from being updated.) Also, we're looking to release 6.0 sooner rather than later. I just need some help getting the last few issues cleared (I'm the only active developer right now and... I'm super busy with work.)


text:
Q: Python Beginner Using Variables to change Tkinter Canvas Items I am having a seemingly simple issue with getting the default value of variables to change. I am trying to make a rectangle drawn on a Tkinter Canvas to get smaller when I press a button. Any help in understanding how the variables work would be greatly appreciated. I am working in Python 3.6.
Here is a sample:
from tkinter import *
root=Tk()
bar_var=200

def test_callback():
    iteration = 100
    for iteration in range(0, iteration):
        bar_var -= 1
        bar_display.coords('bar', 0, 4, bar_var, 16)
        print("bar_var =" + str(bar_var))
bar_display = Canvas(root, height=20, width=200)
bar_display.grid(row=0, column=0)
bar_display.create_rectangle(0, 4, 200, 16, fill='blue', tag='bar')

button = Button(root, text="Resize Bar", command=test_callback)
button.grid(row=1, column=0)
root.mainloop()

I have tried to change the "bar_var" variable to an example I found:
bar_var = None
    if bar_var():
        bar_var = 200

but this seems to throw an exception None Object type is not callable. Any help and explanation would be appreciated. Thanks!

A: Your variable bar_var is not defined as a local variable within your function. Even if you put a simple command like bar_var += 2 into the function body, it will throw an error, because it doesn't know, what your variable is.
One way to overcome this problem, is to refer to the global variable, when calling the button function with, surprise, global:
def test_callback():
    global bar_var
    iteration = 20
    for iteration in range(iteration):
        bar_var -= 1
        bar_display.coords('bar', 0, 4, bar_var, 16)
        print("bar_var =" + str(bar_var))


text:
Q: Finite difference method for 3D diffusion/heat equation I'm trying to use finite differences to solve the diffusion equation in 3D. I think I'm having problems with the main loop. In particular the discrete equation is:

With Neumann boundary conditions (in just one face as an example):

Now the code:
import numpy as np
from matplotlib import pyplot, cm
from mpl_toolkits.mplot3d import Axes3D ##library for 3d projection plots
%matplotlib inline

kx = 15     #Number of points
ky = 15
kz = 15
largx = 90  #Domain length.
largy = 90
largz = 90

dt4 = 1/2 #Time delta (arbitrary for the time).
dx4 = largx/(kx-1)    #Position deltas.
dy4 = largy/(ky-1)
dz4 = largz/(kz-1)

Tin = 25    #Initial temperature
kapp = 0.23

Tamb3d = 150 #Ambient temperature

#Heat per unit of area. One for each face.
qq1=0 / (largx*largz)
qq2=0 / (largx*largz)
qq3=0 / (largz*largy)
qq4=0 / (largz*largy)
qq5=0 / (largx*largy)
qq6=1000 / (largx*largy)

x4 = np.linspace(0,largx,kx)
y4 = np.linspace(0,largy,ky)
z4 = np.linspace(0,largz,kz)

#Defining the function.
def diff3d(tt):

    w2 = np.ones((kx,ky,kz))*Tin         #Temperature array
    wn2 = np.ones((kx,ky,kz))*Tin

    for k in range(tt+2):
        wn2 = w2.copy()
        w2[1:-1,1:-1,1:-1] = (wn2[1:-1,1:-1,1:-1] +
                        kapp*dt4 / dy4**2 *
                        (wn2[1:-1, 2:,1:-1] - 2 * wn2[1:-1, 1:-1,1:-1] + wn2[1:-1, 0:-2,1:-1]) +
                        kapp*dt4 / dz4**2 *
                        (wn2[1:-1,1:-1,2:] - 2 * wn2[1:-1, 1:-1,1:-1] + wn2[1:-1, 1:-1,0:-2]) +
                        kapp*dt4 / dx4**2 *
                        (wn2[2:,1:-1,1:-1] - 2 * wn2[1:-1, 1:-1,1:-1] + wn2[0:-2, 1:-1,1:-1]))

        #Neumann boundary (dx=dy=dz for the time)
        w2[0,:,:] =   w2[0,:,:] + 2*kapp* (dt4/(dx4**2)) * (w2[1,:,:] - w2[0,:,:] - qq1 * dx4/kapp)
        w2[-1,:,:] =  w2[-1,:,:] + 2* kapp*(dt4/(dx4**2)) * (w2[-2,:,:] - w2[-1,:,:] + qq2 * dx4/kapp)
        w2[:,0,:] =   w2[:,0,:] + 2*kapp* (dt4/(dx4**2)) * (w2[:,1,:] - w2[:,0,:] - qq3 * dx4/kapp)
        w2[:,-1,:] =  w2[:,-1,:] + 2*kapp* (dt4/(dx4**2)) * (w2[:,-2,:] - w2[:,-1,:] + qq4 * dx4/kapp)
        w2[:,:,0] =   w2[:,:,0] + 2 *kapp* (dt4/(dx4**2)) * (w2[:,:,-1] - w2[:,:,0] - qq5 * dx4/kapp)
        w2[:,:,-1] =   w2[:,:,-1] + 2 *kapp* (dt4/(dx4**2)) * (w2[:,:,-2] - w2[:,:,-1] + qq6 * dx4/kapp)

    w2[1:,:-1,:-1] = np.nan    #We'll only plot the "outside" points.
    w2_uno = np.reshape(w2,-1)

    #Plotting
    fig = pyplot.figure()
    X4, Y4, Z4 = np.meshgrid(x4, y4,z4)
    ax = fig.add_subplot(111, projection='3d')
    img = ax.scatter(X4, Y4, Z4, c=w2_uno, cmap=pyplot.jet())
    fig.colorbar(img)
    pyplot.show()

For 5000 iterations (qq6 = 1000/Area) we get:

I'm only applying heat on the top surface. Somehow I end up with the bottom surface heating up.
Adding to that I'm trying to confine the region to which I apply heat (just a small part of one face). When I try that it seems like heat is only transferred in one direction, ignoring all others. Applying (qq1 = 1000/Area) for half of the front face (the other part is adiabatic, q = 0) we end up with:

This is pretty odd. I suspect I'm having some trouble in the main loop (or maybe in the boundary conditions) that I'm not finding.

A: there are something wrong with this code:
w2[:,:,0] =   w2[:,:,0] + 2 kapp (dt4/(dx4**2)) * (w2[:,:,-1] - w2[:,:,0] - qq5 * dx4/kapp)
please check it again.
and I am working on a similar project recently. Do you have a moment to share some experience with me.

A: Perhaps you may try a more test driven approach. A help is the Python slice-command. It's fast in numpy array access and it's use is less error prone in finite differencing. Give it a try:
import numpy as np

def get_slices(mx, my, mz):
    jxw, jxp, jxe = slice(0,mx-2), slice(1,mx-1), slice(2,mx)  # west,  center, east
    jys, jyp, jyn = slice(0,my-2), slice(1,my-1), slice(2,my)  # south, center, north
    jzb, jzp, jzt = slice(0,mz-2), slice(1,mz-1), slice(2,mz)  # botoom,center, top
    return jxw, jxp, jxe,   jys, jyp, jyn,    jzb, jzp, jzt

nx, ny, nz = 15, 10, 15
jxw, jxp, jxe, \
jys, jyp, jyn, \
jzb, jzpc, jzt = get_slices(nx, ny, nz)

ax, ay, az = np.arange(nx), np.arange(ny), np.arange(nz)

print('axW', ax[jxw])
print('axP', ax[jxp])
print('axE', ax[jxe])

axW [ 0  1  2  3  4  5  6  7  8  9 10 11 12]
axP [ 1  2  3  4  5  6  7  8  9 10 11 12 13]
axE [ 2  3  4  5  6  7  8  9 10 11 12 13 14]

I'm not quite shure what the graphics in your code shows us. So check it out carefully by using different initialisations for T (or w2) and with kx, ky, kz values that are not all the same. Note the indexing="ij" option in the np.meshgrid() command. The use of np.nan is somehow dangerous because it changes the variable globaly.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

def get_grid(mx, my, mz, Lx,Ly,Lz):
    ix, iy, iz = Lx*np.linspace(0,1,mx), Ly*np.linspace(0,1,my), Lz*np.linspace(0,1,mz)
    x, y, z = np.meshgrid(ix,iy,iz, indexing='ij')
    print('ix', ix), print('iy', iy), print('iz', iz)
    return x,y,z

def plot_grid(x,y,z,T):
    def plot_boundary_only(x,y,z,T):
        mx, my, mz = x.shape
        x[1:-1, 1:-1, 1:-1],y[1:-1, 1:-1, 1:-1],z[1:-1, 1:-1, 1:-1],T[1:-1, 1:-1, 1:-1] = np.nan, np.nan, np.nan, np.nan     # remove interior
        x[1:-1, 1:,0], y[1:-1, 1:,0], z[1:-1, 1:,0],  T[1:-1, 1:,0] = np.nan, np.nan, np.nan, np.nan                         # remove bottom
        x[1:-1, my-1, 1:-1], y[1:-1, my-1, 1:-1], z[1:-1, my-1, 1:-1], T[1:-1, my-1, 1:-1] = np.nan, np.nan, np.nan, np.nan  # remove north face
        x[0, 1:, :-1], y[0, 1:, :-1], z[0, 1:, :-1], T[0, 1:, :-1] = np.nan, np.nan, np.nan, np.nan                          # remove west face
        return x,y,z,T

    x,y,z,T = plot_boundary_only(x,y,z,T)
    fig = plt.figure(figsize=(15,15))
    ax = fig.add_subplot(111, projection='3d')
    img = ax.scatter(x,y,z, c=T.reshape(-1), s=150, cmap=plt.jet())
    fig.colorbar(img)

    #ax.zaxis.set_rotate_label(False) # To disable automatic label rotation
    ax.set_ylabel('Y')
    ax.set_xlabel('X', rotation=0)
    ax.set_zlabel('Z', rotation=0)
    plt.savefig("cube.png")
    plt.show()

def init_T(x,y,z):
    T = np.zeros_like(x)
    case = 'xz'
    if case == 'x': T = x
    if case == 'y': T = y
    if case == 'z': T = z
    if case == 'xz': T = x+z
    return T

nx, ny, nz = 35, 20, 30
Lx, Ly, Lz = nx-1, ny-1, nz-1
x,y,z = get_grid(nx, ny, nz, Lx,Ly,Lz)  # generate a grid with mesh size Δx = Δy = Δz = 1
T = init_T(x,y,z)
plot_grid(x,y,z,T)

This is the main program to run the the heat equation solver. Note that we can not use the grafics displaying the points at the surface to see any results! The Neumann conditions are at the bottom which we can not see, and the values at the faces are fixed value boundary conditions which do not change.
def set_GradBC(u):
    #--- Neuman BC at bottom boundary ---
    u[:, :, 0] = u[:, :, 1]
    return u

def dT(u,DU):
    DU[jxp,jyp,jzp] = (u[jxe,jyp,jzp] - 2.0*u[jxp,jyp,jzp] + u[jxw,jyp,jzp])*Dx + \
                      (u[jxp,jyn,jzp] - 2.0*u[jxp,jyp,jzp] + u[jxp,jys,jzp])*Dy + \
                      (u[jxp,jyp,jzt] - 2.0*u[jxp,jyp,jzp] + u[jxp,jyp,jzb])*Dz
    return DU

#mmmmmmmmmmmmm main mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
#---- set the parameters ------------------------
dt = 0.01                                    # time step size
nIterations = 5000                           # number of iterations
nx, ny, nz = 40,20,30                       # number of grid points
Lx, Ly, Lz = nx-1, ny-1, nz-1                 # physical grid size
Kx, Ky, Kz = 1, 1, 1                          # diffusion coeficients
dx, dy, dz = Lx/(nx-1), Ly/(ny-1), Lz/(nz-1)  # mesh size
Dx, Dy, Dz = Kx/dx**2, Ky/dy**2, Kz/dz**2     # equation coefficients

#---- initialize the field variables -----------------
x,y,z = get_grid(nx, ny, nz, Lx,Ly,Lz)       # generate the grid
T = init_T(x,y,z)                            # initialize the temperature
DT = np.zeros_like(T)                        # initialize the change of temperature
jxw, jxp, jxe, \
jys, jyp, jyn, \
jzb, jzp, jzt = get_slices(nx, ny, nz)       # slices for finite differencing

#---- run the solving algorithm ----------------------
for jter in range(nIterations):
    T = set_GradBC(T)              # set Neumann boundary condition
    T = T + dt*dT(T,DT)            # update

Here is a slice displaying the result along JY1=constant:
def plot_y_slice(JY1, x,y,z,T):
    T2 = T[:,JY1,:]
    X =  x[:,JY1,:]
    Z =  z[:,JY1,:]

    fig = plt.figure(figsize=(15,15))
    ax = fig.add_subplot(111)
    ax.set_aspect('equal')
    plt.contourf(X,Z,T2, 40,alpha=0.99)
    plt.savefig("y_slice.png")
    plt.show()

JY1 = 10
plot_y_slice(JY1, x,y,z,T)

A: There's an error in your equation for the Neumann BC, the diffusion constant  is missing. This lines
#Neumann boundary (dx=dy=dz for the time)
        w2[0,:,:] =   w2[0,:,:] + 2*kapp* (dt4/(dx4**2)) * (w2[1,:,:] - w2[0,:,:] - qq1 * dx4/kapp)
        w2[-1,:,:] =  w2[-1,:,:] + 2* kapp*(dt4/(dx4**2)) * (w2[-2,:,:] - w2[-1,:,:] + qq2 * dx4/kapp)
        w2[:,0,:] =   w2[:,0,:] + 2*kapp* (dt4/(dx4**2)) * (w2[:,1,:] - w2[:,0,:] - qq3 * dx4/kapp)
        w2[:,-1,:] =  w2[:,-1,:] + 2*kapp* (dt4/(dx4**2)) * (w2[:,-2,:] - w2[:,-1,:] + qq4 * dx4/kapp)
        w2[:,:,0] =   w2[:,:,0] + 2 *kapp* (dt4/(dx4**2)) * (w2[:,:,-1] - w2[:,:,0] - qq5 * dx4/kapp)
        w2[:,:,-1] =   w2[:,:,-1] + 2 *kapp* (dt4/(dx4**2)) * (w2[:,:,-2] - w2[:,:,-1] + qq6 * dx4/kapp)

Should be changed to
#Neumann boundary (dx=dy=dz for the time)
        w2[0,:,:] =   w2[0,:,:] + 2*kapp* (dt4/(dx4**2)) * (w2[1,:,:] - w2[0,:,:] - qq1 * dx4)
        w2[-1,:,:] =  w2[-1,:,:] + 2* kapp*(dt4/(dx4**2)) * (w2[-2,:,:] - w2[-1,:,:] + qq2 * dx4)
        w2[:,0,:] =   w2[:,0,:] + 2*kapp* (dt4/(dx4**2)) * (w2[:,1,:] - w2[:,0,:] - qq3 * dx4)
        w2[:,-1,:] =  w2[:,-1,:] + 2*kapp* (dt4/(dx4**2)) * (w2[:,-2,:] - w2[:,-1,:] + qq4 * dx4)
        w2[:,:,0] =   w2[:,:,0] + 2 *kapp* (dt4/(dx4**2)) * (w2[:,:,-1] - w2[:,:,0] - qq5 * dx4)
        w2[:,:,-1] =   w2[:,:,-1] + 2 *kapp* (dt4/(dx4**2)) * (w2[:,:,-2] - w2[:,:,-1] + qq6 * dx4)


text:
Q: Downloading zombies I got the season pass for advanced warfare and your supposed to get all the dlc's when they come out. I downloaded atlas gorge. Zombies came out a couple weeks ago. How do I download Advanced warfare zombies? Im on ps3.

A: Exo-Zombies only just came out a few days ago for Xbox platforms only, you have to wait a while (usually a month) before other platforms can purchase/download Call of Duty DLCs.

Beginning Jan. 27, those playing Call of Duty: Advanced Warfare on Xbox will be able to purchase and download the $15 Havoc DLC; a collection of post-launch content that both introduces Exo Zombies and fleshes out the game's current collection of competitive multiplayer maps. After 30 days, those playing Advanced Warfare on PlayStation 3, PS4 and/or PC will also be given a chance to buy the Havoc DLC and check out the latest iteration of Call of Duty's love-it-or-hate-it Zombies mode.

source


text:
Q: Spring Starter Project in Eclipse -- Can not use Maven: M2E Eclipse Luna 4.4.2 with Java JDK 1.7

I installed
Spring IDE plugin version 3.7.3
Pivotal Software Spring Tool Suite(STS 3.7.3)

plugins successfully, have no problem with switching to the Spring perspective and my File->new->projects has several spring related selections.
I have been building using maven with no problems.  My maven version is 3.3.3.  Checking the Help->Installation Details dialog shows eclipse m2e-workspace 0.3.1
When accessing the Eclipse Marketplace, the dialog shows Maven Integration for Eclipse(Luna and newer) 1.5 and the update button is greyed out and there is an uninstall button, so I have that installed.
When selecting Spring Starter Project, I get the creation dialog box with an error message at the top reading --

Can not import using Maven because Can not use Maven: M2E (Eclipse
  Maven Tooling) is not installed

I have also lost my maven sub-menu when I right click on pom.xml. Its no longer there.
Any ideas on a solution before I start removing things/changing things and possibly making things worse? Explanations also welcome.
Thanks

A: When installing the Spring IDE plugin into Eclipse that already has the maven plugin installed results in a serious conflict as Spring IDE also installs maven.  It may be resolvable, but I was unable to find a solution.
I did uninstall the Spring IDE, but the problem was not cleared on Eclipse restart.  I deleted the corrupted eclipse installation, while keep its workspace intact.
I finally installed STS w/eclipse and pointed it at my previous workspace.

A: I had the same issue and I have no idea of how to fix that.
To turnaround the this problem, I downloaded the Spring Tool Suite™ by the url: http://spring.io/tools/sts/all
This Suite have all the tools to build any Spring project that you'll want.
Hope this work for you.


text:
Q: Adding a URL from a field to a PDF get broken when used within an automated email Links to PDFs get broken when used within an automated email
It would seem  the spaces in the between the URL are breaking it up.
I have tried it as a string, description , URL.
I have tried adding the A href anchor to it but still to no avail.
Any way around this please?

A: I figured it out.
In a workflow I copied the field value to another field and then in the email I inserted the latter current field as a hyperlink,
Respect to M.Qassass
Thank you wjervis