text:
Q: Get phone number label using Google Contacts API and .Net I'm trying to retrieve phone numbers with respective labels from Google with the following code.
        RequestSettings settings = new RequestSettings("myapp", username, password){
                                                                                UseSSL = true,
                                                                                AutoPaging = true,
                                                                                PageSize = 5000
                                                                                };
        ContactsRequest c = new ContactsRequest(settings);
        Feed<Contact> feed = c.GetContacts();
        foreach (var entry in feed.Entries)
        {
            foreach (PhoneNumber phoneNumber in entry.Phonenumbers){
                Debug.Write(phoneNumber.Label ?? "Empty"); //Always null!
                Debug.Write(phoneNumber.Value ?? "Empty");//Have value
            }
        }

However, I had set label to the phone numbers in my Google account such as "Home", "Movile", but those values are not been returned. Am I missing something here?

A: The Contacts API uses the rel attribute for standard labels:

*

*Home: http://schemas.google.com/g/2005#home

*Work: http://schemas.google.com/g/2005#work

*Other: http://schemas.google.com/g/2005#other
Custom labels are held in the label attribute, and these two attributes are mutually exclusive as described here.


text:
Q: Xamarin ios App is behaving strange in release mode,Which works as expected in debug Mode My Xamarin ios App is behaving strange in release mode,Which is working as expected in debug Mode
I have following line in one of the button handler
partial void OnClickStartBtn (UIKit.UIButton sender)
{
    string strCurrentImage = sender.CurrentImage.AccessibilityIdentifier;
}

Its giving the proper AccessibilityIdentifier string output in Debug Mode , But in Release mode Its Null and my application is crashing,
 we should not use AccessibilityIdentifier  ? Or is there any fixes for release mode?

A: I feel like you should not use AccessibilityIdentifier for what you are trying to accomplish.
If you are trying to identify the UIButton and take a different action depending on the button, use any of the following instead:

*

*Use UIButton.Tag, an integer to identify each button.

*Use a different click method for each button.

*Use a better design pattern, such as the MVVM pattern. Your
ViewModel would know the appropriate action to take. This one is
best but probably would require you to restructure your application.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Switch is not clickable inside CollapsingToolbarLayout on android 5.+ I have a CollapsingToolbarLayout and I put  an android.widget.Switch inside. So on Android 4.3 this switch is clickable and I can do whatever I want with it, but on Android 5.+ it is not clickable. Adding clickable = "true" for both Switch and CollapsingToolbarLayout made no effect.  `
<android.support.design.widget.AppBarLayout

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:id="@+id/appBar"
    >

<android.support.design.widget.CollapsingToolbarLayout
    android:id="@+id/collapsing_toolbar"
    android:layout_width="match_parent"
    android:layout_height="352dp"
    android:fitsSystemWindows="true"
    app:contentScrim="?attr/colorPrimary"
    app:expandedTitleMarginEnd="64dp"
    app:expandedTitleMarginStart="48dp"

    app:layout_scrollFlags="scroll|exitUntilCollapsed">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:layout_scrollFlags="scroll|enterAlways"
        >
    </android.support.v7.widget.Toolbar>

    <ImageView
        app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
        android:layout_width="match_parent"
        android:id="@+id/pillImage"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        app:layout_collapseMode="parallax"
        android:maxHeight="192dp"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="15dp"
        android:paddingRight="12dp">
    <Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Отслеживать"
        android:textColor="@color/textColor"
        android:id="@+id/switchInsideCollapsingLayout"

        />
    </RelativeLayout>

</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>`

Why Switch isn't clickable on 5.+ androids and how can I make it clickable for 5.+ versions of android.
Thanks in advance.

A: Add elevation in your Image View or Switch
it Worked For me
<android.support.design.widget.AppBarLayout
    app:expanded="false"
    android:theme="@style/Theme.AppCompat.Light.DarkActionBar"
    android:layout_width="match_parent"
    android:layout_height="140dp">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapse_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">
        <LinearLayout
            android:elevation="25dp"
            android:paddingTop="15dp"
            android:paddingBottom="15dp"
            android:paddingLeft="15dp"
            android:paddingRight="15dp"
            android:gravity="center_vertical|fill_horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageView
                android:tint="#ffffff"
                android:src="@drawable/volume"
                android:layout_width="30dp"
                android:layout_height="30dp" />

            <android.support.v7.widget.AppCompatSeekBar
                android:clickable="true"
                android:progressBackgroundTint="@color/progressBackground"
                android:progressTint="@color/progress"
                android:thumbTint="@color/thump"
                android:progress="55"
                android:layout_weight="1"
                android:layout_width="0dp"
                android:layout_height="wrap_content"/>

        </LinearLayout>
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin">
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

Watch the Attachments
Screen 1
Screen 2


text:
Q: Why is assigning to an array not allowed in C? If I write:
int some_arr[4];
some_arr = {0, 1, 2, 3};

Then my compiler (in this case, GCC) will complain that I don't have an expression before {. So I need to use a compound literal, fine:
int some_arr[4];
some_arr = (int[]){0, 1, 2, 3};

And now we see that I'm not allowed to assign a value to an array.
What?
I can "circumvent" this with something like memcpy(some_arr, (int[]){0, 1, 2, 3}, sizeof(int[4])), or by assigning to each element of some_arr one-by-one (or through a loop.) I can't imagine that GCC is incapable of parsing the individual assignments from what I've wrote (a lazy compiler that doesn't care about the user could probably even do it in the pre-processor), so it seems to come down to "the standard said no." So why does the standard say this particular thing is off-limits?
I'm not looking for the language in the standard that says it's not allowed as much as I'm looking for the history lesson of how that part of the standard came to be.

A: From ISO/IEC 9899:1999 on assignment operator constrains

§6.5.16 An assignment operator shall have a modifiable lvalue as its left operand.

Then on modifiable lvalue

§6.3.2.1 A modifiable lvalue is an lvalue that does not have array type, does
  not have an incomplete type, does not have a const-qualified type, and
  if it is a structure or union, does not have any member (including,
  recursively, any member or element of all contained aggregates or
  unions) with a const-qualified type.

Why not? probably because the array name decays to pointer to first element most probably.

However, an array assignment wrapped by a struct is allowed, as such:
//gcc 5.4.0

#include  <stdio.h>

struct A
{
    int arr[3];
    int b;
};

struct A foo()
{
    struct A a = {{1, 2, 3},10};
    return a;
}

int main(void)
{
    struct A b = foo();
    for (int i=0; i<3; i++)
          printf("%d\n",b.arr[i]);
    printf("%d\n", b.b);
}

Yields
1
2
3
10

A: tl;dr:
because C decided that arrays decay to pointers, and hasn't provided a way for the programmer to avoid it.
Long answer:
When you write
int arr[4];

from that moment on, every time you use arr in a dynamic context, C considers arr to be &arr[0], namely the decay of an array to a pointer (see also here and here).
Therefore:
arr = (int[]){0, 1, 2, 3};

is considered to be
&arr[0] = (int[]){0, 1, 2, 3};

which cannot be assigned. A compiler could implement a full array copy using memcpy(), but then C would have to provide a means to tell the compiler when to decay to a pointer and when not to.
Note that a dynamic context is different from a static context. sizeof(arr) and &arr are static context processed at compile time, in which arr is treated as an array.
Likewise, the initializations
int arr[4] = {0, 1, 2, 3};

or
int arr[] = {0, 1, 2, 3};

are static context - these initializations happen when the program is loaded into memory, before it even executes.
The language in the standard is:

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ''array of type'' is converted to an expression with type ''pointer to type'' that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

When an array is inside a struct, e.g.
struct s {
    int arr[4];
};
struct s s1, s2;

Then again using s1.arr is like &s1.arr[0], and it cannot be assigned.
However, while s1 = s2 is dynamic context, is not referencing the array. The compiler knows it needs to copy the full array, because it's part of the definition of the structure, and this assignment is generated implicitly. For example, if the compiler chooses to implement struct assignment using memcpy(), the array is automatically copied.


text:
Q: inserting object that matches the property How do we insert the object 1 to each object on Object 2 below so that each object will have the value from the first object , so the property from Object which are firstMileRange , secondMileRange and thirdMileRange will be replaced with the values from the Object 1.
Any idea guys would be much appreciated. Thanks.
#Object 1 - data or object to insert
[
    {
        "firstMileRange": 1,
        "secondMileRange": 2,
        "thirdMileRange": 3
    }
]

#Object 2 - object to insert the data to
[
    {
        "id": 1521,
        "demographicType": "Demos",
        "demos": "Estimated Population",
        "streetName": null,
        "vehicleCount": null,
        "firstMile": 100000,
        "firstMileRange": null,
        "secondMile": 50000,
        "secondMileRange": null,
        "thirdMile": 50000,
        "thirdMileRange": null
    },
    {
        "id": 1522,
        "demographicType": "Demos",
        "demos": "Households",
        "streetName": null,
        "vehicleCount": null,
        "firstMile": 5999,
        "firstMileRange": null,
        "secondMile": 5999,
        "secondMileRange": null,
        "thirdMile": 5999,
        "thirdMileRange": null
    },
]

#expectedOutput
[
    {
        "id": 1521,
        "demographicType": "Demos",
        "demos": "Estimated Population",
        "streetName": null,
        "vehicleCount": null,
        "firstMile": 100000,
        "firstMileRange": 1,
        "secondMile": 50000,
        "secondMileRange": 2,
        "thirdMile": 50000,
        "thirdMileRange": 3
    },
    {
        "id": 1522,
        "demographicType": "Demos",
        "demos": "Households",
        "streetName": null,
        "vehicleCount": null,
        "firstMile": 5999,
        "firstMileRange": 1,
        "secondMile": 5999,
        "secondMileRange": 2,
        "thirdMile": 5999,
        "thirdMileRange": 3,
    },
]

A: .map() to iterate through 2nd array. On each object of 2nd array merge 1st array to object of 2nd array:
Object.assign(obj2, ...arr1)
// spread ... arr2 to expose the object inside of it.

const update = [{
  "firstMileRange": 1,
  "secondMileRange": 2,
  "thirdMileRange": 3
}];

const group = [{
    "id": 1521,
    "demographicType": "Demos",
    "demos": "Estimated Population",
    "streetName": null,
    "vehicleCount": null,
    "firstMile": 100000,
    "firstMileRange": null,
    "secondMile": 50000,
    "secondMileRange": null,
    "thirdMile": 50000,
    "thirdMileRange": null
  },
  {
    "id": 1522,
    "demographicType": "Demos",
    "demos": "Households",
    "streetName": null,
    "vehicleCount": null,
    "firstMile": 5999,
    "firstMileRange": null,
    "secondMile": 5999,
    "secondMileRange": null,
    "thirdMile": 5999,
    "thirdMileRange": null
  }
];

const updated = group.map(obj => Object.assign(obj, ...update));

console.log(updated);

A: const array1 = [{a: 1, b: 1, c: 1}, {a: 2, b: 2, c: 2}, {a: 3, b: 3, c: 3}];
const obj = { a: 999, b: 123 }

array1.forEach(o => { o.a = obj.a; o.b = obj.b; });

console.log(array1);

// expected output: Array [Object { a: 999, b: 123, c: 1 }, Object { a: 999, b: 123, c: 2 }, Object { a: 999, b: 123, c: 3 }]

A: You may loop through the array that contains the objects using the map method and merge the object with each object found on the array.

const objectsArray = [{
      id: 1521,
      demographicType: "Demos",
      demos: "Estimated Population ",
      streetName: null,
      vehicleCount: null,
      firstMile: 100000,
      firstMileRange: null,
      secondMile: 50000,
      secondMileRange: null,
      thirdMile: 50000,
      thirdMileRange: null
    },
    {
      id: 1522,
      demographicType: "Demos",
      demos: "Households",
      streetName: null,
      vehicleCount: null,
      firstMile: 5999,
      firstMileRange: null,
      secondMile: 5999,
      secondMileRange: null,
      thirdMile: 5999,
      thirdMileRange: null
    }
  ],
  theObject = {
    firstMileRange: 1,
    secondMileRange: 2,
    thirdMileRange: 3
  },
  /** merge an object into another */
  merge = (arr, obj) => arr.map(o => o = {...o, ...obj});

console.log(merge(objectsArray, theObject));

The above example works as expected but it has an issue! What if the object you want to apply to the other objects contains attributes you don't want them to be merged in the final array of objects ? The above example will merge these unwanted attribute! To solve that, we may have a map of the wanted attributes that should be extracted.

const objectsArray = [{
      id: 1521,
      demographicType: 'Demos',
      demos: 'Estimated Population',
      streetName: null,
      vehicleCount: null,
      firstMile: 100000,
      firstMileRange: null,
      secondMile: 50000,
      secondMileRange: null,
      thirdMile: 50000,
      thirdMileRange: null
    },
    {
      id: 1522,
      demographicType: 'Demos',
      demos: 'Households',
      streetName: null,
      vehicleCount: null,
      firstMile: 5999,
      firstMileRange: null,
      secondMile: 5999,
      secondMileRange: null,
      thirdMile: 5999,
      thirdMileRange: null
    }
  ],
  theObject = {
    firstMileRange: 1,
    secondMileRange: 2,
    thirdMileRange: 3,
    unwantedAttr1: 'should not',
    unwantedAttr2: 'be merged'
  },
  attributesMap = ['firstMileRange', 'secondMileRange', 'thirdMileRange'],
  /** merges an object into another, only attributes passed as the third parameter will be merged and any other attribute will be ignored  */
merge = (arr, obj, attrs) => arr.map(o => {
  attrs.forEach(a => o[a] = obj[a] || null);
  return o;
});

console.log(merge(objectsArray, theObject, attributesMap));

With that, unwantedAttr1 and unwantedAttr2 will not be merged into the objects as they dont appear in attributesMap that was passed to the merge function.


text:
Q: Mac Mini 2018 Ethernet option 1 vs. 10 GB What is advantage of 10 GB Ethernet vs. 1 GB Ethernet in the new Mac Mini?
Where is it important or helpful to have the 10 Gbps option that costs $100 extra.

A: 10 GB/s transfer speeds are faster than 1 GB/s transfer speeds.
From the Mac mini purchase page

Mac mini has some of the most versatile ports and connectivity options
  of any Mac, allowing it to serve and adapt to a wide variety of
  situations and workflows. Mac mini comes standard with
  10/100/1000BASE-T Gigabit (1Gb) Ethernet using an RJ-45 connector. For
  network connections that are up to 10 times faster, Mac mini has a
  10Gb Ethernet option. The 10Gb Ethernet option supports Nbase-T
  industry-standard 1Gb, 2.5Gb, 5Gb, and 10Gb network speeds using an
  RJ-45 connector. With 10Gb Ethernet, Mac mini will provide higher
  connectivity bandwidth for sharing files between desktops, working
  with high-performance network storage, or large-capacity data loads.

A: Your Mac Mini is flexible.
It comes preset for 1 Gbps (Gigabit per second).
That same plug (RJ-45) can be configured for speeds up to 10 Gbps.
So what does that mean ? You could transfer a 3.6 GB high definition movie from one computer to another in 3 seconds with the 10 Gbps. With 1 Gbps it will take about 10 times longer (30 seconds).
Why ?
For those occasion when your work in a place that has extremely high (10Gbps) computer to computer cable connection (the Ethernet).
However that speed is useless for Internet. At best you can get 1 Gbps Internet speed (with fiber optic providers).
Never than less your Mac Mini is a one mean machine:
Ethernet on mac mini
10/100/1000BASE-T Gigabit Ethernet (RJ-45 connector)
Configurable to 10Gb Ethernet (Nbase-T Ethernet with support for 1Gb, 2.5Gb, 5Gb, and 10Gb Ethernet using RJ-45 connector)


text:
Q: MySQL Selecting wrong column value in Group By query Here's a real noobish MySQL query problem I'm having.
I have a high score table in a game I'm writing. The high score DB records a name, level, and score achieved. There are many near duplicates in the db. For example:
Name | Level | Score | Timestamp (key)
Bob    2       41    | 1234567.890
Bob    3       15    | 1234568.890
Bob    3       20    | 1234569.890
Joe    2       40    | 1234561.890
Bob    3       21    | 1234562.890
Bob    3       21    | 1234563.890

I want to return a "highest level achieved" high score list, with an output similar to:
Name | Level | Score
Bob    3       21
Joe    2       40

The SQL Query I currently use is:
SELECT *, MAX(level) as level
FROM highscores
GROUP BY name
ORDER BY level DESC, score DESC
LIMIT 5

However this doesn't quite work. The "Score" field output always seems to be randomly pulled from the group, instead of taking the corresponding score for the highest level achieved. Eg:
Name | Level | Score
Bob    3       41
Joe    2       40

Bob never got 41 points on level 3! How can I fix this?

A: You'll need to use a subquery to pull the score out.
select distinct
    name,
    max(level) as level,
    (select max(score) from highscores h2
        where h2.name = h1.name and h2.level = h1.level) as score
from highscores h1
group by name
order by level desc, score desc

Cheers,
Eric
It irks me that I didn't take the time to explain why this is the case when I posted the answer, so here goes:
When you pull back everything (*), and then the max level, what you'll get is each record sequentially, plus a column with the max level on it.  Note that you're not grouping by score (which would have given you Bob 2 41, and Bob 3 21--two records for our friend Bob).
So, how the heck do we fix this?  You need to do a subquery to additionally filter your results, which is what that (select max(score)...) is. Now, for each row that reads Bob, you will get his max level (3), and his max score at that level (21).  But, this still gives us however many rows Bob has (e.g.-if he has 5 rows, you'll get 5 rows of Bob 3 21).  To limit this to only the top score, we need to use a DISTINCT clause in the select statement to only return unique rows.
UPDATE: Correct SQL (can't comment on le dorfier's post):
SELECT h1.Name, h1.Level, MAX(h1.Score)
    FROM highscores h1
    LEFT OUTER JOIN highscores h2 ON h1.name = h2.name AND h1.level < h2.level
    LEFT OUTER JOIN highscores h3 ON h1.name = h3.name AND h2.level = h3.level AND h1.score < h3.score
    WHERE h2.Name IS NULL AND h3.Name IS NULL
    GROUP BY h1.Name, h1.Level

A: This is efficient.
SELECT h1.Name, h1.Level, h1.Score
FROM highscores h1
LEFT JOIN highscores h2 ON h1.name = h2.name AND h1.level < h2.level
LEFT JOIN highscores h3 ON h1.name = h3.name AND h1.level = h3.level AND h1.score < h3.score
WHERE h2.id IS NULL AND h3.id IS NULL
You're looking for the level/score for which there is no higher level for that user, and no higher score that that level.

A: Interesting problem.  Here's another solution:
SELECT hs.name, hs.level, MAX(score) AS score
FROM highscores hs
INNER JOIN (
  SELECT name, MAX(level) AS level FROM highscores GROUP BY name
) hl ON hl.name = hs.name AND hl.level = hs.level
GROUP BY hs.name, hs.level;

Personally, I find this the easiest to understand, and my hunch is that it will be relatively efficient for the database to execute.
I like the above query best, but just for kicks... I find the following one amusing in a kludgey sort of way.  Assuming score can't exceed 99999...
SELECT name, level, score
FROM highscores hs
INNER JOIN (
  SELECT name, MAX(level * 100000 + score) AS hfactor
  FROM highscores GROUP BY name
) hf ON hf.hfactor = hs.level * 100000 + hs.score AND hf.name = hs.name;


text:
Q: Testing conservation laws experimentally How conservation laws are tested experimentally independently from each other? what do I mean by that question?
It seems that to test one conservation law experimentally, such as conservation of energy, we will have to assume other conservation laws are correct such as conservation of charge and conservation of momentum and angular momentum...etc.
But to really test any conservation law one has to check if one of them is valid independent from any other one. Is this possible experimentally? if not then how scientists check conservation laws?

A: Suppose I collide two billiard balls then I can measure the velocities before and after and check that momentum is conserved. I don't need to assume that energy is conserved. I just measure the velocities before and after.
Alternatively I can use the same system to check for conservation of energy, but again I don't have to assume conservation of momentum.
It would be possible for this experiment to conserve momentum but not energy. For example suppose I'm working in the centre of mass frame, so the net momentum is zero, and the two billard balls collide and stop dead. That would conserve momentum but not energy. Likewise suppose the billiard balls meet but then both move off together at a right angle. That would conserve energy but not momentum.
So it's hard to think of an experiment that doesn't simultaneously test more than one conservation law, but you don't need to assume other conservation laws hold when testing your selected conservation law.

A: Well, I think that conservation laws are NOT independent of each other anyways. For example, the conservation of energy is derived by integrating Newton's second law (rewriting $\frac{dv}{dt}$ as $\frac{dv}{dx}\frac{dx}{dt}=v\frac{dv}{dx}$), whereas conservation of momentum (and by extension, angular momentum) is derived from the same equation. So we actually have to verify both simultaneously (as if one is false, the other is also most probably false). Note that I am not saying that they are conserved in equivalent situations, I am saying that the overall conservation laws are equivalent.
Conservation of charge can be proved from conservation of energy also, if we take Coulomb's law as a fundamental. So really, the question doesn't mean much as most of these laws are theoretically interdependent, and thus there is experimentally prove them independently.
The best way to go about this, IMHO, is to use a series of experiments. Prove energy and momentum together in one experiment (or separately if you can manage it). Now, use an experiment that takes these two conservation laws into account without having to deal with other conservation laws (make the system charge neutral for example); prove another law with this experiment.
I think really an example of sich an experiment would make the question clearer.


text:
Q: Spring Boot & Spring Security not serving content from /static folder I am creating a simple web application using Spring Boot and Spring Security. I have a custom filter to check if x-auth-token is present and valid. I have the static content under /src/main/resources/static folder. But, the URL pointing to static content are also passing through the custom filter and failing the token validation. Could anybody help in figuring out the mistake with my configuration?
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private StatelessAuthenticationFilter statelessAuthenticationFilter;

    @Autowired
    private UserDetailsService userDetailsService;

    public SpringSecurityConfig() {
        super(true);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
            .anyRequest().authenticated().and()

            // Custom Token based authentication based on the header
            .addFilterBefore(statelessAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    public UserDetailsService userDetailsService() {
        return userDetailsService;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/auth");
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setEnabled(false);
        filterRegistrationBean.setFilter(statelessAuthenticationFilter);
        return filterRegistrationBean;
    }
}

Custom filter:
@Component
public class StatelessAuthenticationFilter extends GenericFilterBean {

    @Value("${security.token.secret:asdfasdfasdf}")
    private String tokenSecret;

    @Autowired
    private UserRepository userRepository;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                            throws IOException, ServletException {
        System.out.println("stateless authentication filter");
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        try {

            String token = httpRequest.getHeader(Constants.X_AUTH_TOKEN_HEADER_NAME);
            if(!StringUtils.hasText(token)) {
                throw new AuthenticationException(AirlineError.AUTHENTICATION_AUTH_TOKEN_MISSING);
            }

            JWTPayload jwtPayload = new JWTPayload();
            byte[] secret = tokenSecret.getBytes();
            DefaultJwtParser defaultJwtParser = new DefaultJwtParser();
            defaultJwtParser.setSigningKey(secret);

            Claims claims = defaultJwtParser.parseClaimsJws(token).getBody();
            jwtPayload.setEmail((String) claims.get("email"));
            jwtPayload.setExp((Long) claims.get("exp"));

            if (new DateTime(jwtPayload.getExp()).isBeforeNow()) {
                throw new AuthenticationException(AirlineError.AUTHENTICATION_AUTH_TOKEN_EXPIRED);
            }

            User user = userRepository.findOne(jwtPayload.getEmail());
            SecurityContextHolder.getContext().setAuthentication(new UserAuthentication(user.getEmail()));
            chain.doFilter(request, response);
        } catch(Exception e) {
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }

}

index.html is in /src/main/resources/static folder, but it is not being served when I open http://localhost:8080 from browser.
EDIT 1
I have created a sample project in github to replicate the issue. Hope this helps:
https://github.com/mgooty/spring-boot-security
when I hit:

*

*http://localhost:8080 or http://localhost:8080/index.html I get An
Authentication object was not found in the SecurityContext

*http://localhost:8080/static/index.html I get 404 error

A: If you want to permit all access to your static content then just configure it in your security configuration:
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
            .antMatchers("/index.html").permitAll()
            .anyRequest().authenticated().and()

            // Custom Token based authentication based on the header
            .addFilterBefore(statelessAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }

However, this won't work in your case because of errors in your custom security filters. But you can still disable all web security (disable all fiilters) for index.html file or other static resources.
Just change:
web.ignoring().antMatchers("/auth");

to:
web.ignoring().antMatchers("/auth", "/index.html");

Remember that your application maps /src/main/resources/static directory to / url (there is no /static prefix in your resource urls).


text:
Q: strange behavior of html tags inside contenteditable div In my project, I am trying to add HTML tag letter (< and >) dynamically to a contenteditable div. Whenever user is pressing alphanumeric character, I am appending an empty span element which is used for calculating the position of the caret in contenteditable div.
The problem is that when I type some words like following:
when <

and press a alphanumeric character like b (which calls a function to append a span element), The contenteditable div is showing just when instead of when <b.
When I inspected the element I found the contenteditable div has the following content:
when <b</b
                              ^  strange that span is holding '</b' instead of being empty

Here is a example JSFiddle.
I am not sure how this is happening. Please tell me what should I do to evade this issue.
PS: Here I am trying to add < and >, not HTML elements like .

A: As you said, you're trying to add a symbol which can be interpreted as HTML. You need to escape it or use a different way to express it as an ISO entity:
$('#btnContent').click(function(){
    $('#content').html("when <b" + "");
});

http://jsfiddle.net/Dekku/jXeVW/1/

A: I have visit your code and found there is a <b in JS don't know by are you using that.
Use the below code:
$('#btnContent').click(function(){
    $('#content').html("when" + "");
});

By removing the <b tag you will not get this. or You should properly close to it to make the code proper.
EDITED:
After visiting your new code I got the solution you should use the following code:
$('#btnContent').click(function(){
    $('#content').html("when <b");
    $('#content').html($('#content').html()  + "");
});

If you need the details then tell me.

A: The problem was actually that I was appending a span element to the text whenever the user types something in to the contenteditable div to grab the position of the caret. Something like this
Hello I am he|re
             ^ Caret position

Then I was adding a span element in between of that text using .html() something like this
Hello I am here

Now whenever I add any letter which represents Html like < or >, then it was merging some of the text inside the span (as I shown above in my post).
So, I solved it by removing it just after when I get the position through span element. I followed the below steps to solve this issue for each letter pressed by the user.
//Store the .text() in a variable.
//Replace Html letters inside the contenteditable div with alphabets which has same width. (for exact positioning).
//add span to the modified text through .html()
//get the offset position of the span
//Do something with that offset position
//Remove span
//Replace the .text() inside the contenteditable div with the text which was stored in a variable.

I did these many things to solve this issue because I was using .text() everywhere else in my project code. If I change it to .html() then I must have rewritten the complete code and might also can't complete the project.
Clearly, I couldn't have done the things which were mentioned in the other answered posts. I hope this will help someone.


text:
Q: how to export some specific points of a regular grid in python I have coordinate points (x and y) and want to rearange them. All points are stored in a list. List has several arrays and arrays have unique x values:
sp_arr=[np.array([[1., 8.]]), np.array([[2., 8.], [2., 9.]]), \
        np.array([[3., 8.], [3., 9.], [3., 10.]]),\
        np.array([[4., 8.], [4., 9.], [4., 10.]]),\
        np.array([[5., 9.], [5., 10.]]), np.array([[6., 9.], [6., 10.]]),\
        np.array([[7., 10.]]), np.array([[8., 10.]])]

If the length of array is less than 1, I do nothing. I uploaded a fig to visualize what I want. Figure has three rectangle and I want to rearange my points based on them. Change of length of arrays is the most important siganl for me. It changes from second to third array. So, I need to extract all the rows of shorter (second) array and 2 (length of shorter array) rows of third one. I extract first 2 rows of third array because the mean of y value in third (longer) array is higher than shorter. If it was less, I would export last 2 rows.
Rectangle 2 contains the arrays that their length is maximum.
From fourth to fifth array, length changes (rectangle 3).Again I keep all rows of shorter arrays (fifth and sixth) and 2 (length of shorter arrays) rows of longer one. Mean of y is shorter arrays is higher, so I keep last two rows of longer array. Finally, I want the following result:
surfs=[np.array([[2., 8.], [2., 9.], [3., 8.], [3., 9.]]), \ # first rectangle
       np.array([[3., 8.], [3., 9.], [3., 10.], [4., 8.], [4., 9.], [4., 10.]]),\# second rectangle
       np.array([[4., 9.], [4., 10.], [5., 9.], [5., 10.], [6., 9.], [6., 10.]]) # last rectangle]

I tried the following code but it was not successful:
surfs=[]
for i in range(len(sp_ar)-1):
    if 1 < len(sp_ar[i]):
        if sp_ar[i][-1][1] != sp_ar[i+1][-1][1] or sp_ar[i][0][1] != sp_ar[i+1][0][1]:
            if np.mean (sp_ar[i][:,1]) < np.mean (sp_ar[i+1][:,1]):
                surfs.append([sp_ar[i],sp_ar[i+1][0:len(sp_ar[i])]])
            if np.mean (sp_ar[i][:,1]) > np.mean (sp_ar[i+1][:,1]):
                surfs.append([sp_ar[i], sp_ar[i+1][-len(sp_ar[i]):]])

In advance, I do appreciate any help.


text:
Q: Automatically add PHPDoc using existing comments I want to tidy a large function include file where PHPDoc is only used partially. there are some functions without PHPDoc like
function name($var1,$var2){ // explanation what it does
  # ...
}

and some where the PHPDoc exists but is incomplete like some variables missing:
/**
  * explanation
  *
  * @param boolean $var1 foo foo foo
  *
  * @return null
  */
function name2($var1,$var2){
  # ...
}

or just
/** explanation
  */
function name3($var1,$var2){
  # ...
}

How is it possible to add all missing variable definitions and return values, using a correct "unknown" tag for the ones added?
It could analyse each function if it has a return value and it should convert the already existing comments (behind each function) and use them in PHPDoc.
I am aware that you will have to check the result manually, but it would be really helpful to generate a skeleton with the data that already exists.

A: You could do it using a combination of Reflection, token_get_all which uses Zend's lexical scanner to parse a string into PHP lanugage tokens and quite possibly regular expressions.
The problem with Reflection is that some methods, like ReflectionFunctionAbstract::getReturnType are available only on PHP 7.
In PHP 5+ you can use ReflectionFunctionAbstract::getParameters, ReflectionFunctionAbstract::getDocComment etc.
If there's no DocBlock you could get the function start and end lines with ReflectionFunctionAbstract::getStartLine and ReflectionFunctionAbstract::getEndLine, copy the source block to a string and use token_get_all to obtain an array of PHP tokens to analyze individually.
Reflection example in PHP 5.6:
<?php

/**
 * explanation
 *
 * @param boolean $var1 foo foo foo
 *
 * @return null
 */
 function test($var1, $var2) {

 }

 echo ReflectionFunction::export('test', true);

Output:
/**
 * explanation
 *
 * @param boolean $var1 foo foo foo
 *
 * @return null
 */
Function [ <user> function test ] {
  @@ index.php 10 - 12

  - Parameters [2] {
    Parameter #0 [ <required> $var1 ]
    Parameter #1 [ <required> $var2 ]
  }
}

A: I hope this can be helpful for you.
As I am using sublime text editor. I installed DocBlockr.
Here is link


text:
Q: Help with CTE Aggregating Children Recursively I'm trying to create a query to calculate the "Available to Sell" qty of all items in inventory. In this case, an item can have current available inventory, but could also be a kit, which is comprised of raw materials that can be assembled to form that finished good. So the available to sell is the current available Finished Good (FG) qty plus the minimum of the components that can be made into the FG.
Example:
Say we are selling a laptop kit that is comprised of a laptop and a carrying bag. If we have 2 kits already made, and 6 laptops and 3 carrying bags, our available to sell of these kits is 2 + 3 = 5 total. The carrying bags are the limiting factor in this case. Even though we have 6 laptops, we can only make 3 more kits because of the bags limiting us.
I've gotten this far and the calculations work from the lowest level 2 up to level 1, but level 0 is not correct. So in this case, the calculation for the laptop kit is correct (11 on hand + we can make 4 more = 15 avail to sell). But the top level Laptop & Bag Kit is not correct. The least Avail to Sell of the direct children of the top level (Laptop & Bag Kit) is 15 + 3 of that kit is on hand = 18, not 14.

I'm thinking maybe I need to add a second recursive CTE instead of the left join I have in the final select?
SQL Fiddle
CREATE TABLE Item (
  Id INT,
  ParentId INT,
  DisplaySeq INT,
  DisplayText VARCHAR(30),
  OnHandQty INT
  );

INSERT INTO Item (Id, ParentId, DisplaySeq, DisplayText, OnHandQty) VALUES
(9, NULL, 0, 'Laptop & Bag Kit', 3),
(8, 9, 5, 'Laptop Kit', 11),
(7, 8, 10, 'Laptop', 5),
(6, 8, 15, 'Power Supply', 4),
(26, 9, 20, 'Bag', 23)
;

;WITH items AS (
  SELECT
    Id
    , 0 as ParentId
    , Id as RootId
    , 0 AS Level
    , CAST(DisplaySeq AS VARCHAR(255)) AS Path
    , CAST('---' AS varchar(100)) AS LVL
    , CAST(DisplayText as VARCHAR(255)) as DisplayText
    , OnHandQty
  FROM Item
  WHERE ParentId IS NULL

  UNION ALL

  SELECT
    child.Id
    , child.ParentId
    , parent.RootId
    , Level + 1
    , CAST(parent.Path + '.' + CAST(child.DisplaySeq AS VARCHAR(255)) AS VARCHAR(255)) AS Path
    , CAST('---' + parent.LVL AS varchar(100)) AS LVL
    , CAST(parent.LVL + child.DisplayText as VARCHAR(255)) as DisplayText
    , child.OnHandQty
  FROM
    Item child
      INNER JOIN items parent
      ON parent.Id = child.ParentId
  )

SELECT
  t.Path
  , t.RootId
  , t.Id
  , t.ParentId
  , t.Level
  , t.DisplayText
  , t.OnHandQty
  , COALESCE(s.MaxCanMake, t.OnHandQty) as MaxCanMake
  , t.OnHandQty + COALESCE(s.MaxCanMake, 0) as AvailToSell
FROM
  items t
    left join (
        Select
          ParentId,
          MIN(OnHandQty) as MaxCanMake
        FROM items
        GROUP BY ParentId
      ) as s
      ON t.Id = s.ParentId

ORDER BY t.Path

A: Unroll the hierarchy into a temporary table first (note the computed column):
CREATE TABLE #Items
(
    Id integer PRIMARY KEY,
    MPath varchar(255) NOT NULL,
    DisplayText varchar(30) NOT NULL,
    OnHandQty integer NOT NULL,
    [Level] integer NOT NULL,
    ParentId integer NOT NULL,
    MaxCanMake integer NULL,
    AvailToSell AS OnHandQty + MaxCanMake
);

WITH Items AS
(
    SELECT
        I.Id,
        MPath = CONVERT(varchar(255), I.DisplaySeq),
        I.DisplayText,
        I.OnHandQty,
        0 AS [Level],
        0 AS ParentId
    FROM dbo.Item AS I
    WHERE I.ParentId IS NULL

    UNION ALL

    SELECT
        I.Id,
        CONVERT(varchar(255), Parent.MPath + '.' + CONVERT(varchar(11), I.DisplaySeq)),
        I.DisplayText,
        I.OnHandQty,
        Parent.[Level] + 1,
        I.ParentId
    FROM Items AS Parent
    JOIN dbo.Item AS I WITH (FORCESEEK)
        ON I.ParentId = Parent.Id
)
INSERT #Items
    (Id, MPath, DisplayText, OnHandQty, [Level], ParentId)
SELECT
    I.Id, I.MPath, I.DisplayText, I.OnHandQty, I.[Level], I.ParentId
FROM Items AS I
OPTION (MAXRECURSION 0);

-- Useful index
CREATE INDEX i
ON #Items (ParentId, AvailToSell);

That gives us:

╔════╦════════╦══════════════════╦═══════════╦═══════╦══════════╦════════════╦═════════════╗
║ Id ║ MPath  ║   DisplayText    ║ OnHandQty ║ Level ║ ParentId ║ MaxCanMake ║ AvailToSell ║
╠════╬════════╬══════════════════╬═══════════╬═══════╬══════════╬════════════╬═════════════╣
║  9 ║ 0      ║ Laptop & Bag Kit ║         3 ║     0 ║        0 ║ NULL       ║ NULL        ║
║ 26 ║ 0.20   ║ Bag              ║        23 ║     1 ║        9 ║ NULL       ║ NULL        ║
║  8 ║ 0.5    ║ Laptop Kit       ║        11 ║     1 ║        9 ║ NULL       ║ NULL        ║
║  7 ║ 0.5.10 ║ Laptop           ║         5 ║     2 ║        8 ║ NULL       ║ NULL        ║
║  6 ║ 0.5.15 ║ Power Supply     ║         4 ║     2 ║        8 ║ NULL       ║ NULL        ║
╚════╩════════╩══════════════════╩═══════════╩═══════╩══════════╩════════════╩═════════════╝

Now compute MaxCanMake per level, starting with the deepest:
DECLARE @Level integer =
(
    SELECT MAX(I.[Level])
    FROM #Items AS I
);

WHILE @Level >= 0
BEGIN
    UPDATE I
    SET I.MaxCanMake =
        ISNULL
        (
            (
                SELECT TOP (1)
                    I2.AvailToSell
                FROM #Items AS I2
                WHERE I2.ParentId = I.Id
                ORDER BY
                    I2.AvailToSell ASC
            ),
            0
        )
    FROM #Items AS I
    WHERE I.[Level] = @Level;

    SET @Level -= 1;
END;

The computed column in the temporary table automatically reflects the change in AvailToSell.
The final display query is then:
SELECT
    DisplayText = REPLICATE('---', I.[Level]) + I.DisplayText,
    I.OnHandQty,
    I.MaxCanMake,
    I.AvailToSell
FROM #Items AS I
ORDER BY
    I.MPath;

╔════════════════════╦═══════════╦════════════╦═════════════╗
║    DisplayText     ║ OnHandQty ║ MaxCanMake ║ AvailToSell ║
╠════════════════════╬═══════════╬════════════╬═════════════╣
║ Laptop & Bag Kit   ║         3 ║         15 ║          18 ║
║ ---Bag             ║        23 ║          0 ║          23 ║
║ ---Laptop Kit      ║        11 ║          4 ║          15 ║
║ ------Laptop       ║         5 ║          0 ║           5 ║
║ ------Power Supply ║         4 ║          0 ║           4 ║
╚════════════════════╩═══════════╩════════════╩═════════════╝

dbfiddle


text:
Q: Getting the Site URL in Next.JS I am setting up a Next.JS site and would like to retrieve the site url.  For example, if I have a local install, then the site url would be localhost:3000.  If I deploy the site, then it would be www.my-domainame.com.
I thought I could do this via the next.js useRouter hook.  But upon closer look it does not seem to return that information.  It has information about the path and query, but not about the site url.
As such, I am wondering -- how can I do this in Next.JS?
Thanks.


text:
Q: Phonegap - Android APP - how do i alter app launcher title Hopefully this should be a quick one to solve but - I'm building a HTMl5 Phonegap based App - all is going fine and it compiles and runs on the phone so far  - my issue is that the text under the launcher icon on the phone says 'test', i'd like this to say the name of my app - but cant figure out how to change it - can anyone help please!?
Cheers
Paul

A: You need to edit res/values/strings.xml and change the value of app_name to whatever you want it to show up as.


text:
Q: PWA successfully published on Google Play using TWA has an abnormal behave We published our PWA on Google Play using Trusted Web Activities. App was successfully signed and released.
In order to successfully sign and publish the app, We strictly followed the step by step official tutorial at the following address:
https://developers.google.com/web/updates/2019/02/using-twa
We used Android Studio.
The app on google play is:
https://play.google.com/store/apps/details?id=com.coelotec.meteodrome
The Android App locally installed on device, calls the following url that points to the web app (PWA):
https://app.meteodrome.it
The Web App, is a PWA developed with Angular 6.0.
Pre-rendering is not activated. Server return the classic bundle of javascripts, html and css.
However some of the users are reporting some issues, such as having two icons on their screen. One is named "MeteoDrome" and the other one "Meteo Drome" with the space.
One of the icons contains the correct logo of the app. The other one has the default android logo. Clicking on the first one, app correctly loads. Clicking the default android logo named "Meteo Drome", browser loads showing the app.
In the first case you correctly see the full screen app, in the second case you see the app wrapped in chrome. When you see chrome the address bar is visible.
Other users reports that they are not able to correctly load app. They usually see white screen instead of the right interface. Especially when the android version is old.
But for many other users app works fine and have no problems.
Many users in facts, neither see two icons on theirs screen nor loads a white screen view.
The app have got many likes and is much appreciated among the users. However it has also an unusual number of uninstalls.
Probably when the app works fine users doesn't uninstall.
We have no idea of what to do.
1) How can We understand what happen when the app is uninstalled and why is it uninstalled?
2) Besides, the users can:
 a - find two icons on the screen.
 b - find the correct icon on the screen and the android logo in the app list.
 c - find only the right icon on the screen without seeing any other icons.
Why does this happen?
3) Why sometime some users report me that they see white screen even if their android version is good to install the app? And in other cases the app works fine?
We really have no idea of what to do and we have some serious problems with the abnormal percentage of uninstall.
Please, help us.
Thanks.

A: *

*Is possible that some users may have installed the application from the Play Store and also installed using the Add to Home Screen?

*The Application available on the Play Store is being server with the default Android logo. The Image Asset Studio inside Android Studio can help with creating new one.

*Users with versions of Chrome < 72 or that have other browser as their default browsers will be shown the application in a Custom Tab as a fallback. This can be customised inside your application by implementing your own fallback method.
Finally, a good way to get started with your use case is to checkout the sample application on Github. It is designed to be an easy option to get started with TWAs, and can be used as a starting point for your own app.


text:
Q: why my Velero backup fail for minio storage with error An error occurred: gzip: invalid header? I have install the minio example from velero vmware-tanzu. The minio example setup is running and I have set the nodePort service. Then I follow the following command to install velero.
 velero install  --provider aws --plugins velero/velero-plu                    gin-for-aws:v1.0.0 --bucket velero --secret-file ./credentials-velero --use-volume-snapshots=false --backup-location-config r                    egion=minio,s3ForcePathStyle="true",s3Url=http://123.123.123.123:30804

When I check the logs for velero I see this error.
time="2023-02-05T10:45:30Z" level=error msg="fail to validate backup store" backup-storage-location=velero/default controller                    =backup-storage-location error="rpc error: code = Unknown desc = InvalidArgument: S3 API Requests must be made to API port.\n                    \tstatus code: 400, request id: , host id: " error.file="/go/src/github.com/vmware-tanzu/velero/pkg/persistence/object_store.                    go:191" error.function="github.com/vmware-tanzu/velero/pkg/persistence.(*objectBackupStore).IsValid" logSource="pkg/controlle                    r/backup_storage_location_controller.go:154"
time="2023-02-05T10:45:30Z" level=info msg="BackupStorageLocation is invalid, marking as unavailable" backup-storage-location                    =velero/default controller=backup-storage-location logSource="pkg/controller/backup_storage_location_controller.go:130"
time="2023-02-05T10:45:30Z" level=error msg="Error listing backups in backup store" backupLocation=velero/default controller=                    backup-sync error="rpc error: code = Unknown desc = InvalidArgument: S3 API Requests must be made to API port.\n\tstatus code                    : 400, request id: , host id: " error.file="/go/src/github.com/vmware-tanzu/velero-plugin-for-aws/velero-plugin-for-aws/objec                    t_store.go:308" error.function="main.(*ObjectStore).ListCommonPrefixes" logSource="pkg/controller/backup_sync_controller.go:1                    07"
time="2023-02-05T10:45:30Z" level=error msg="Current BackupStorageLocations available/unavailable/unknown: 0/0/1, BackupStora                    geLocation \"default\" is unavailable: rpc error: code = Unknown desc = InvalidArgument: S3 API Requests must be made to API                     port.\n\tstatus code: 400, request id: , host id: )" controller=backup-storage-location logSource="pkg/controller/backup_stor                    age_location_controller.go:191"

AS I can see velero didn't manage to find the backup location as I provided the correct URL.
When I run
kubectl describe deployment -n velero velero

I found this output.
Name:                   velero
Namespace:              velero
CreationTimestamp:      Sun, 05 Feb 2023 12:45:24 +0200
Labels:                 component=velero
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               deploy=velero
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:           component=velero
                    deploy=velero
  Annotations:      prometheus.io/path: /metrics
                    prometheus.io/port: 8085
                    prometheus.io/scrape: true
  Service Account:  velero
  Init Containers:
   velero-velero-plugin-for-aws:
    Image:        velero/velero-plugin-for-aws:v1.0.0
    Port:         <none>
    Host Port:    <none>
    Environment:  <none>
    Mounts:
      /target from plugins (rw)
  Containers:
   velero:
    Image:      velero/velero:v1.10.1-rc.1
    Port:       8085/TCP
    Host Port:  0/TCP
    Command:
      /velero
    Args:
      server
      --features=
      --uploader-type=restic
    Limits:
      cpu:     1
      memory:  512Mi
    Requests:
      cpu:     500m
      memory:  128Mi
    Environment:
      VELERO_SCRATCH_DIR:              /scratch
      VELERO_NAMESPACE:                 (v1:metadata.namespace)
      LD_LIBRARY_PATH:                 /plugins
      GOOGLE_APPLICATION_CREDENTIALS:  /credentials/cloud
      AWS_SHARED_CREDENTIALS_FILE:     /credentials/cloud
      AZURE_CREDENTIALS_FILE:          /credentials/cloud
      ALIBABA_CLOUD_CREDENTIALS_FILE:  /credentials/cloud
    Mounts:
      /credentials from cloud-credentials (rw)
      /plugins from plugins (rw)
      /scratch from scratch (rw)
  Volumes:
   plugins:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
   scratch:
    Type:       EmptyDir (a temporary directory that shares a pod's lifetime)
    Medium:
    SizeLimit:  <unset>
   cloud-credentials:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  cloud-credentials
    Optional:    false
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   velero-86f4984c96 (1/1 replicas created)
Events:
  Type    Reason             Age    From                   Message
  ----    ------             ----   ----                   -------
  Normal  ScalingReplicaSet  2m45s  deployment-controller  Scaled up replica set velero-86f4984c96 to 1

Here all the Variables are set correctly but the volume path is not set. I am not sure where is issue basically.
This might help that when I look for velero backup location it is not set.
master-k8s@masterk8s-virtual-machine:~/velero-v1.2.0-darwin-amd64$ velero backup-location get
NAME      PROVIDER   BUCKET/PREFIX   PHASE         LAST VALIDATED                  ACCESS MODE   DEFAULT
default   aws        velero          Unavailable   2023-02-05 12:52:30 +0200 EET   ReadWrite     true

What I have done so far
I have try different blogs and stack question to fix. The issue is not resolved.
What is the main cause?
The main cause of this issue is I am not able to understand the logs. I want to know why velero not able to find the location in my case where as in different blogs the same setup works.
What I want to do Or how can you help me?
Please help me to find the main issue. Why my backup fails with error ,
master-k8s@masterk8s-virtual-machine:~/velero-v1.2.0-darwin-amd64$ velero backup create mytest --inc                                             lude-namespaces postgres-operator
Backup request "mytest" submitted successfully.
Run `velero backup describe mytest` or `velero backup logs mytest` for more details.
master-k8s@masterk8s-virtual-machine:~/velero-v1.2.0-darwin-amd64$ velero backup get                                                             NAME     STATUS   ERRORS   WARNINGS   CREATED                         EXPIRES   STORAGE LOCATION   S                                             ELECTOR
mytest   Failed   0        0          2023-02-05 13:00:03 +0200 EET   29d       default            <                                             none>
master-k8s@masterk8s-virtual-machine:~/velero-v1.2.0-darwin-amd64$ velero backup logs mytest
An error occurred: gzip: invalid header

I will be really thanks full for your help and support in advance.


text:
Q: Do file tests use `$_` or `_` in a given…when switch? When using file test operators, the stat() results are cached in _ so if you want to perform several tests you don't need to do more system calls.
if (-f $file_) {
  say 'readable' if -r _;
  say 'writable' if -w _;
}

If I use them in a given…when, do they use _ or $_?
given ($file) {
  when (! -f) {}
  when (-r) {say 'readable';continue}
  when (-w) {say 'writable';continue}
  ....
}

I have the impression that this will use $_. Is that true? Also because given…when does not have default fall-through it is necessary to use continue in order to see other matches.
Probably this case is better resolved with ifs and uses less typing than with the given…when approach. But it is too tempting to see if you can fit given…when when refactoring your software. ;-)

A: This is what it deparsed into:
sub {
    use warnings;
    use strict 'refs';
    BEGIN {
        $^H{'feature_unicode'} = q(1);
        $^H{'feature_say'} = q(1);
        $^H{'feature_state'} = q(1);
        $^H{'feature_switch'} = q(1);
    }
    my $file = shift @_;
    given ($file) {
        when (not -f $_) {
            ();
        }
        when (-r $_) {
            say 'readable';
            continue;
        }
        when (-w $_) {
            say 'writable';
            continue;
        }
    }
}

So it doesn't show smart matching in the op codes.

A: The virtual filehandle _ is never the default argument for a file test operator (not counting the stacked file tests that all operate of the same file, since only one of them has an argument). You have to use it explicitly to tell the file test to use the values from the last file stat.
$_ is the default for most of the other file test operators, but not all of them.


text:
Q: Is there a way to not display empty TreeCells in JavaFX? My TreeView is displayed even though there are no TreeItems in it. Is there any way to not display the TreeCells before they actually have a corresponding TreeItem to display?
This is how it looks without any items:

This is how it looks when one item is added to the root:

Thanks for any suggestions :)

A: I think you can not prevent empty TreeCells being added to the TreeView, but if all you care about is appearance, you can define different style for empty cells. Empty cells have the :empty pseudo class, which you can use in your CSS:
.tree-cell:empty {
    -fx-background-color: transparent;
}


text:
Q: PHP RegEx: Remove CSS rules, except if contain specific string I'm struggling to match and keep all CSS rules containing the string 224,13,78.
Sample input:
h1 {
    color: rgb(224,13,78);
}

h1 {
    display: block; /* Delete this whole block */
}

#test-color {
    color: rgb(224,13,78);
}

.test-position {
    position: absolute; /* Delete this whole block */
}

.test-bg-color {
    background-color: rgba(224,13,78,0.5);
}

@media ( max-width: 1200px ) {
    .test-color {
        color: rgb(224,13,78);
    }

    .test-position {
        overflow: hidden; /* Delete this whole block */
    }
}

Desired output:
h1 {
    color: rgb(224,13,78);
}

#test-color {
    color: rgb(224,13,78);
}

.test-bg-color {
    background-color: rgba(224,13,78,0.5);
}

@media ( max-width: 1200px ) {
    .test-color {
        color: rgb(224,13,78);
    }
}

Is there a handy regex that solves my problem?
For reference, I found this solution, but it matches the property name, not the value:
Find: \{.*(font-size\:\s*\d+px\;).*\}?
Replace: \{ $1 \}
And also this JavaScript solution that does the same:
What is RegEx to remove css keeping font size
I accept a JavaScript solution too, but PHP is preferable.
Thank you all in advance.

A: Try the following regex:
\h*+[^\s{}][^{}]*{(?:[^{}](224,13,78)?)++[^{}]*+}(?(1)(*SKIP)(*F))\R*

See live demo here
What it does is trying to match a sequence of characters 224,13,78 in a {...} block. If it matches it holds the value in the first capturing group. Then later we say if 1st capturing group was successful in matching, then skip over whatever has been matched by:
(?(1)(*SKIP)(*F))

otherwise the whole match doesn't contain the desired characters and engine won't skip over it. We now only need to replace matched blocks with nothing:
$css = preg_replace('~\h*+[^\s{}][^{}]*{(?:[^{}](224,13,78)?)++[^{}]*+}(?(1)(*SKIP)(*F))\R*~', '', $css);


text:
Q: Uncountable dense measurable subgroups of $\mathbb{C}$ Is it possible to have an uncountable proper dense subgroup of $\mathbb{C}$ which is also Baire or Lebesgue measurable?

A: It seems the following.

Lebesgue measurable

As I already noted, the group $\mathbb Q\times\mathbb R$ is a required.

Baire

The construction of such a group $G$ requires Axiom of Choice, because $G$ is descriptively complex. I recall the following definitions. A subset $A$ of a topological space $X$ is meager in $X$, if $A$ is contained in the countable union of nowhere dense subsets of $X$. A subset $B$ of a topological space $X$ has the Baire Property in $X$ if $B$ contains a $G_\delta$-subset $C$ of $X$ such that $B\setminus C$ is meager in $X$. By [Kech, 8.22] each Borel subset of a space $X$ has the Baire Property in $X$. By [Kech 9.8], a topological group $G$ is Baire iff it is non-meager (in $G$). It is easy to check (or see Proposition 1.3 or the beginning of  section I.2 from [HC] ) that a dense subspace $Y$ of a  topological space $X$ is meager in $X$ iff $Y$ is meager in $Y$. At last, by Banach-Kuratowski-Pettis Theorem (see [Kel, p.279] or [Kech 9.9]), for any subset $B$ of a topological group the set $BB^{-1}$ is a neighborhood of the unit provided $B$ is non-meager and has the Baire Property in the group. So, such a proper dense Baire subgroup of $\mathbb C$ cannot be Borel or, even, cannot have the Baire Property in $\mathbb C$.
For an example of such a group $G$ consider the group $\mathbb C$ as a vector space over the field $\mathbb Q$ and let $G$ be any vector subspace of $\mathbb C$ of codimension $1$. Since $\mathbb C$ is a countable union of copies of $G$, the group $G$ is non-meager in $\mathbb C$. Using this fact it is easy to show that $G$ is dense in $\mathbb C$. So the group $G$ is non-meager in $G$, therefore $G$ is Baire.
References
[HC] R. C. Haworth, R. C. McCoy, Baire spaces, Warszawa, Panstwowe Wydawnictwo Naukowe, 1977.
[Kech] A. Kechris. Classical Descriptive Set Theory, – Springer, 1995.
[Kel] J. Kelley. General Topology. -- M.: Nauka, 1968 (in Russian).


text:
Q: How to run a function over certain observations? I am trying to calculate the number of seats that parties won per district in a given election based on the number of votes they received in the district.
There is a function in R that will do this for each region:
seats_ha(party, votes, seats, method="dhondt")

The first argument provides a vector of party list names, the second argument provides a vector of the vote totals that each party won in a district, seats = the number of seats in a given district and the method is the electoral formula used to translate votes into seats. What I've been able to do is to calculate this by individually subsetting the data by a single region in an electoral year. My problem is that I have ~27 regions over 3 electoral years.
So my data look like this:
year   region dist_seat  party_name party_vote reg_id cong_id
2016-2021 AMAZONAS   2          UPP     0            1       3
2016-2021 AMAZONAS   2          FP      51067        1       3
2016-2021 AMAZONAS   2          AP      11992        1       3
2016-2021   ANCASH   5          FE       4534        2       3
2016-2021   ANCASH   5          UPP     0            2       3

I would like to be able to run the function for each region in each year.

A: Consider by, the object-oriented wrapper to tapply which slices a data frame by one or more columns to run needed operations. The input parameter to by's FUN is always a subsetted data frame and output will always be a list of whatever function returns, here being the return of seat_ha.
You can even add a new column to subsetted data frame and then do.call + rbind results for a single data frame. Below tryCatch ensures new column is always populated: actual result of seats_ha and NA if it encounters an error.
BUILD LIST OF SUBSETTED DFs
df_list <- by(mydata, mydata[,c("year", "region")], FUN=function(sub) {
                 # ADD NEW COLUMN TO sub DF
                 sub$calc_seat <- tryCatch(with(sub, seats_ha(party_name, party_vote,
                                                              dist_seat, method="dhondt")),
                                           error = function(e) NA)
                 return(sub)
             })

# ROW BIND ALL DFs
final_df <- do.call(rbind, df_list)


text:
Q: Simple Javascript: Running a function over an array I am trying to create an array of vertices, and then run the 'rect' function over this array to display an arbitrary amount of rectangles. Right now, I have:
var vertices = new Array();

function setup() {
    createCanvas(600, 600);
    ...
    iter(width/2 - c/2, height/2 - c/2, c);
    var i;
    for (i = 0; i < vertices.length; i++) {
        fill(200);
        rect(vertices[i]);
    }
}

And then:
function iter(x, y, len) {
    r_1 = random(0, 1);

    if (r_1 < 0.5){
        vertices.push(x, y - len*0.5, len*0.5, len*0.5);
    }
}

I have seen lots about using map or foreach to run functions over arrays but I don't know why this doesn't work (specifically, using a for loop to run a function over an array). I am obviously very new to all this stuff! An explanation of what I seem to misunderstand would be very much appreciated.
Thanks

A: When you do
vertices.push(x,y-len*0.5,len*0.5,len*0.5)

you're calling push with four arguments, so four items get pushed to the array. Because you're calling rect with verticies[i] later, it sounds like each item of verticies should be a data container of some sort - an array or an object, otherwise the points of each vertex will be separated out over multiple indicies. For example, if you were to use an array:
function iter(x, y, len) {
  r_1 = random(0, 1);
  if (r_1 < 0.5){
    vertices.push([x, y - len*0.5, len*0.5, len*0.5]);
  }
}

And then spread each array in the vertex array into the rect argument list:
function setup() {
  createCanvas(600, 600);
  // ...
  iter(width/2 - c/2, height/2 - c/2, c);
  var i;
  for (i = 0; i < vertices.length; i++) {
    fill(200);
    rect(...vertices[i]);
  }
}

This assumes that rect is a function that accepts 4 arguments. (you could also change rect so that it accepts a single array as an argument instead, and avoid the spread syntax, if you wanted)
You also might consider using an array literal rather than new Array - calling the Array constructor is rarely a good idea:
var vertices = [];


text:
Q: SQLite table with some rows missing a column I have a table in a SQLite database that looks something like this, but with more columns and rows:
| Field1  | Field2  |
|---------|---------|
| A       | 1       |
| B       | 2       |
| C       |         |

What I need to do is run a SQL query like this:
SELECT * FROM <tablename> WHERE <conditions> ORDER BY Field2

The problem is, I'm getting the error: no such column: Field2
So now I've been asked to set all the missing values to 99. But when I run
UPDATE <tablename> SET Field2='99' WHERE Field2 IS NULL;

I get the same error. How do I fix this and update all those missing cells?
EDIT: I should also add that the missing values don't seem to be null since if I add a new column in my database GUI browser, all the cells show as [NULL], though this column doesn't.

A: This turned out to be caused by a very subtle problem in the table:
Several of the column names (the ones that were causing me problems) ended in a newline (\n). Removing the newline solved all my problems!


text:
Q: Using a Parameter in Expression Transformation I have a workflow in which I've set up an expression transformation to select $$Param for a particular field, and then within the target properties I've set a delete value. I've tried this by substituting $$Param for a hardcoded value and it works fine, however, for some reason when I put in $$Param, it doesn't actually do the delete. Is there a reason? Am I doing something wrong?
Just for clarification, the workflow executes successfully - no error is thrown but it's not doing what it's supposed to.
Thanks in advance,

A: $$Param needs to be passed thru a parameter file and you have the option to set an initial value when you declare the parameter in the mapping under Mappings > Parameter and Variables.
Have you looked at the session log to see what's the override value of $$Param is being used? If it's a SQL delete, try to turn see in the session log the query being executed in the database.


text:
Q: Why can't I install cudatookkit=10.1 using pip but can using conda? $ pip install cudatoolkit==10.1
Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement cudatoolkit==10.1 (from versions: none)
ERROR: No matching distribution found for cudatoolkit==10.1

This failed. However, the conda works:
$ conda install cudatoolkit=10.1
Collecting package metadata (current_repodata.json): done
Solving environment: done

## Package Plan ##

  environment location: /data0/congmin/miniconda

  added / updated specs:
    - cudatoolkit=10.1

The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    ca-certificates-2021.5.25  |       h06a4308_1         112 KB
    certifi-2021.5.30          |   py38h06a4308_0         138 KB
    conda-4.10.1               |   py38h06a4308_1         2.9 MB
    cudatoolkit-10.1.243       |       h6bb024c_0       347.4 MB
    openssl-1.1.1k             |       h27cfd23_0         2.5 MB
    ------------------------------------------------------------
                                           Total:       353.1 MB

I need to use pip to install, because I want to put it in requirements.txt.

A: pip relies on https://pypi.org/ as the default package repository.
Anaconda has it's own repository
cudatoolkit is not a package in pypi. So pip cannot find any such package.
It is available in the conda repository.
The reason why cudatoolkit is not available in pypi is because it's not a python packge. It is a toolkit from nvidia that needs a C compiler to exist in your system. Pip was never intended to handle such cases, whereas Anaconda is.
See this blog post from Anaconda for details:

This highlights a key difference between conda and pip. Pip installs Python packages whereas conda installs packages which may contain software written in any language.

As far as adding to requirements.txt is concerned. If you are using conda in your target system as well you could just export your conda environment to an environment.yml file and then clone the envrionment in your target machine.


text:
Q: Why do UIScreen dimensions differ on iOS device and simulator? In troubleshooting an app I'm developing, I discovered that the UIScreen.main.bounds.width differs between my iPhone 8 Plus real device vs the simulator. To narrow it down, I created a new Swift app from the iOS App template in Xcode 13.4.1 targetting iOS 15.5 and added one line of code in viewDidLoad():
print("\(UIScreen.main.bounds.width)x\(UIScreen.main.bounds.height)")

Running on the simulator I get the expected dimensions:
414.0x736.0

but on my device I get:
375.0x667.0

I can't figure out why the difference. Past answers on this topic talk about Launch Screen images and whatnot, but my understanding is that all went away with the Launch Storyboard which this default template is using.
BTW, deleting the Launch Storyboard from the project results in dimensions of 320x480 which is expected as the app drops back to "scaled mode". So I don't think that's a factor here.
Definitely an iPhone 8 plus:
Settings|General|About

A: Settings | Display & Brightness | Display Zoom was on. Turning it off fixed my issue.


text:
Q: Why the object isn't adding the other elements that also share the same first character? function groupBy(array) {

var result = {};

for (var i = 0; i < array.length; i++) {
  var firstChar = array[i][0]
  result[firstChar] = [];

  if (array[i].indexOf(firstChar) > -1) {
  result[firstChar].push(array[i])
 }
}
return result;
}

console.log(groupBy(['apple', 'cat', 'boat', 'card', 'bond']));

This is what I expected to get: { 'a': ['apple'], 'c': ['cat', 'card'], 'b': ['boat', 'bond'] }.
However, I'm only able to add one of the words to the array ({ 'a': ['apple'], 'c': ['card'], 'b': ['bond'] }). Could someone explain why my code is doing that? and also why is it skipping the first word that it encounters (i.e. "cat", "boat")? Anything would be greatly appreciated!

A: You are re-writing the array. first check if the value of result[firstChar] is undefined, if it's undefined then only initialize it with an empty array.

function groupBy(array) {
  var result = {};

  for (var i = 0; i < array.length; i++) {
    var firstChar = array[i][0];
    if (!result[firstChar]) {
      result[firstChar] = [];
    }
    if (array[i].indexOf(firstChar) > -1) {
      result[firstChar].push(array[i]);
    }
  }
  return result;
}

console.log(groupBy(['apple', 'cat', 'boat', 'card', 'bond']));


text:
Q: Running my python code in Gitbash I am a total newbie in programming so I was hoping anyone could help me. I am trying to write program in python that, given an integer n, returns me the corresponding term in the sylvester sequence. My code is the following:
    x= input("Enter the dimension: ")
    def sylvester_term(n):
    """ Returns the maximum number of we will consider in a wps of dimension n

    >>> sylvester_term(2)
    7
    >>> sylvester_term(3)
    43
    """
    if n == 0:
        return 2

    return sylvester_term(n-1)*(sylvester_term(n-1)-1)+1

Now, my questions are the following, when trying to run this in GitBash, I am asked to input the n but then the answer is not showing up, do you know what I could do to receive the answer back? I plan to continue the code a bit more, for calculating some other data I need, however, I am not sure if it is possible for me to, after coding a certain piece, to test the code and if so, how could I do it?

A: Here's an example of how I'd handle it. You can use sys.argv to get the arguments passed via the command line. The first argument is always the path to the python interpreter, so you're interested in the second argument, you can get it like so:
sys.argv[1]

Once that is done, you can simply invoke your function like so
print(sylvester_term(int(sys.argv[1]))

A: You will need to add:
print(sylvester_term((int(x)))

to the end of your program to print the answer.
You will need to cast to int because the Python Input() function stores a string in the variable. So if you input 5 it will return "5"
This does not handle exceptions, e.g if the user inputs a letter, so you should put it in a try and except statement.


text:
Q: How can I get Mathematica to recognize equality of symbolic matrix expressions? I have two matrix expressions:
X.Transpose[T].Transpose[X]

and
X.T.Transpose[X]

I want Mathematica  to recognize that these expressions are equal. Is it possible to do that?

A: We can easily verify the assumption that your matrices are equal is wrong, e.g. let's take two 2 x 2 matrices:
A = {{10, 5}, {2, 2}};
B = {{1, 0}, {1, 6}};

now we have
A.B.Transpose[A] == A.Transpose[B].Transpose[A]

False

However a simple fact in linear algebra says that the former matrix is equal to the latter one transposed.
TraditionalForm[ X.T.Transpose[X] == Transpose[X.Transpose[T].Transpose[X]] ]

Now we can exploit new tensor capabilities in Mathematica 9, first
assume that X and T are n x m matrices:
$Assumptions = (X | T) ∈  Matrices[{n, m}];

then we can use e.g. TensorReduce:
TensorReduce[ X.T.Transpose[X] == Transpose[ X.Transpose[T].Transpose[X]] ]

True

A: Clearly your expressions are the same only when the matrix T is symmetric. With this assumption, Mathematica can prove your expressions are equal using:
TensorReduce[
    X.Transpose[T].Transpose[X] == X.T.Transpose[X],
    Assumptions -> X ∈ Matrices[{n, n}] && T ∈ Matrices[{n,n}, Symmetric[{1,2}]]
]

True


text:
Q: Debian equivalent to Ubuntu server I am trying to install Debian 9.5 on my company's server. Problem ! I can't install it without the GUI (I don't need it and I don't want it to be there).
I tried all this .iso and the installation process is not giving me the choice of programs to install (as referred in this similar question )
I found a lot of blog posts talking about installing the debian from the netinstall .iso BUT this suppose that the server is already connected to internet (Not in my case)

A: Yesterday I installed Debian 9.5 without installing X (during installation) using the netinstall iso, but I'm quite sure it uses the same installer as full cds/dvds. It did the last time I tried any of those.
I think your problem might be that you're using live images. They are probably geared to install something very similar to what they present, and they all have a desktop environment in their name.
Try going to Getting Debian and follow the link to "A larger complete installation image", from there you should be able to download some cd/dvd images from which you can install without an internet connection.


text:
Q: Inconsistency of an Element's clientwidth/height after fullscreenchange I have an HTMLElement that is going through a fullscreenchange event. I've added to that event a listener which makes some calculations based the element's clientwidth/clientheight when fullscreened. The problem is that the element's clientheigh value isn't always consistent. Most of the time it has the expected value. In fact, when Devtools is closed, it always behaves correctly. But when Devtools is open (undocked in another monitor, so it doesn't affect the browser's dimensions), clientheight occasionally gets a smaller value.
I think that it happens since the browser has some extra tasks to perform when Devtools is open, and that occasionally these tasks "give enough time" for my listener to run before the element's dimensions managed to adjust to the fullscreen. That's my theory, but I'm not sure if it makes sense - after all, the fullscreenchange event is fired only after the element has finished entering fullscreen, no?
I would appreciate both an explanation as to why that happens, and the correct way to get around this. Thanks


text:
Q: Compare disparate Date formats, which are stored as Strings I have two disparate date formats presented in my application as strings. Here are the formats:

*

*07/01/2011

*2011-07-01

I'm looking for the most efficient way to assert their equality.

A: Parse both dates using SimpleDateFormat and then use the equals() method.
The formats to use will be "MM/dd/yyyy" and "yyyy-MM-dd".
Sample code:
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");

Date date1 = format1.parse(value1);
Date date2 = format2.parse(value2);

return date1.equals(date2);

A: You can use a SimpleDateFormat to make them into Dates (or Calendar objects) and compare them like that.
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");

MM is the month make sure they are capitalized.


text:
Q: HTTP messages are not loaded correctly ( Android ) I would like to load json with volley and download images using BufferedInputStream. Since these requests are made to LAN ip adresses on the non encrypted http port, I enabled android:usesCleartextTraffic="true"
I get this error from Volley:
com.android.volley.ParseError: org.json.JSONException: Unterminated object at character 20 of {"data":{"foo":"bar"

I use BufferedInputStream like this:
private boolean getFileFromUrl(String url, String path) {
    try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
         FileOutputStream fileOutputStream = new FileOutputStream(path)) {
        byte dataBuffer[] = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
            fileOutputStream.write(dataBuffer, 0, bytesRead);
        }
        fileOutputStream.close();

        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }

    return false;
}

If I provide a Content-Length parameter on the server, sometimes I get this error:
W/System.err: java.net.ProtocolException: unexpected end of stream
        at com.android.okhttp.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:398)
        at com.android.okhttp.okio.RealBufferedSource$1.read(RealBufferedSource.java:372)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:248)
W/System.err:     at java.io.BufferedInputStream.read1(BufferedInputStream.java:288)
W/System.err:     at java.io.BufferedInputStream.read(BufferedInputStream.java:347)

If I have no Content-Length parameter, some of the files are still not fully loaded. No IOException is thrown, but I get this error, if I try to read some of the images:
<Corrupt JPEG data: premature end of data segment> from output_message

These errors happen randomly. If I open these urls with my browser, it can load them perfectly. I have no idea how to debug it.
I tried my getFileFromUrl with a https url, and then everíthing worked fine. Unfortunately I am not able to use https in this project, only http.

Edit
I created an executor service with one thread and then submit the getFileFromUrl calls in Runnable instances, but I still get the errors:
Executors.newFixedThreadPool(1);

A: As it seems, that API (or OkHttp client) truncates the response body for some reason.
Either the OkHttp client has a low read-timeout (this value could be raised) or the API does not respond in time (or as whole JSON response). When it always responds properly in a web-browser, it should indeed be a(n Android) client-side issue. One way to handle this might be to catch that ProtocolException, delete the aborted download and then retry to download the file again.
But I'd assume that the Content-Length header's value might simply be wrong.
I mean, this value would be calculated correctly, when NOT setting it manually.
The client may only act abnormal upon erroneous instructions received.
Content-Length tells the client how large the receive-buffer has to be ...
and even if the response is not truncated, the client will reject the excess.
For example:
Content-Length: 20 ...is what the API apparently reports.
{"data":{"foo":"bar"

Content-Length: 22 ...is what the API should report.
{"data":{"foo":"bar"}}

A: From your code you are just opening raw http connection with OpenConnection. However, I'm not sure it's right(and simple) way to load image. You can use any other library for Image loading, which would take care about content length and headers.

*

*For ex with Glide.

    Glide.with(context)
            .asBitmap()
            .load(url)
            .into(new CustomTarget<Bitmap>() {

                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    // do whatever you want with bitmap
                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {

                }
            });

*

*To save just use your code above or.

public void write(String fileName, Bitmap bitmap) {
  try (FileOutputStream out = new FileOutputStream(filename)) {
      bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap
  instance
      // PNG is a lossless format, the compression factor (100) is ignored
  } catch (IOException e) {
      e.printStackTrace();
  }
}


text:
Q: Copy paste(clipboard) works differently in ssh and local system I am using my local system to copy some text using
ctrl + c

In ssh i use this command to paste
shift + insert

The above works fine
Now i using this command to copy from ssh
ctrl + insert

But i my local system i used this command to paste it
ctrl + v

But the above command pastes different text from which i copied from ssh
but inside the ssh
shift + insert

Pastes the exact text which i copied
How to copy a text from ssh and paste it in local system(I am using ubuntu)

A: In Ubuntu (and other distros which use X windows system) you can simply select the text with your mouse and then paste it to another window by clicking middle button (wheel) on your mouse. It is far easier than fiddling around with hotkeys on the keyboard.
Relating to your question - I am on Ubuntu 14.04 and I've just tried to replicate your issue - and I couldn't. For me it works as it should across windows and terminals with ssh's in them.


text:
Q: Soap Client with Maven I have a separate WSDL URL for each environment, like
DEV   URL-1 ,
SIT   URL-2,
PROD  URL-3
I want to create a soap client in such a way that if we are deploying the application using this soap client on DEV then soap should point URL-1, if we deploy in SIT it should point URL-2 for PROD it should point URL-3. I am using MAVEN for generating soap client.
I don't want to change soap URL in pom.xml each time when I am deploying the application in a different environment.
We are using Jenkins to build the application and deploy in different environment
Can you help me on this?

A: Depends on the maven plugin you are using to generate client files, but my advice is anyway to create different maven profiles for all your environments.
Please check the question here and the answer from Patrick.


text:
Q: VC2012 where to find _mm256_pow_pd? Using Visual Studio 2012/C++:
I need to apply gamma correction to my resampler code.  From Intels Docs I learned that there should be the intrinsic _mm256_pow_pd(), but I can't find it.
Planned use:
_mm256_storeu_pd(&destinationData[y*dst4+x], _mm256_pow_pd(akku, _mm256_broadcast_sd(&gamma)));

Any ideas where Microsoft has hidden this intrinsic?

A: Obviously I didn't google enough.  This SO answer implicitly answers my question: https://stackoverflow.com/a/31515534/2896592
Content: _mm256_pow_pd is from Intel's SVML library - it's not really an intrinsic.
Workaround: take a look at Agner Fog's vector library


text:
Q: POWER QUERY: Need to change 1st number in a string depending it's value and on (2 possible) conditions from 2 other columns Conditional change for separate column IF the 1st digit of a string contains "X###", then change to "Y###"
If DC = A and DS = 2XXX replace the 2 with a 3
If DC = B and DS = 5XXX replace the 5 with a 6

Dependant Column ("DC") / Data string ("DS") / Should transform to
           A        2888        3888
           B        3888        3888
           A        8888        8888
           B        5888        6888
           A        2888        3888
           B        2888        2888

3 conditions, 2 from another column(DC), then 1 possible replacement of the 1st digit (from DS)
I need to transform this in PowerQuery please

A: You may use this code:
let
    Source = YourTable,
    types = Table.TransformColumnTypes(Source,{"Col2", type text}),
    replace = Table.ReplaceValue(types,each Text.Start([Col2],1),
                                       each if [Col1] = "A" and Text.Start([Col2],1) = "2" then "3"
                                       else if [Col1] = "B" and Text.Start([Col2],1)="5" then "6"
                                       else Text.Start([Col2],1),Replacer.ReplaceText,{"Col2"})
in
    replace

Or:
let
Source = YourTable,
types = Table.TransformColumnTypes(Source,{"Col2", type text}),
replace = Table.ReplaceValue(types,0,each Text.ReplaceRange([Col2], 0, 1, if [Col1] = "A" and Text.Start([Col2],1) = "2" then "3"
                                                                          else if [Col1] = "B" and Text.Start([Col2],1)="5" then "6"
                                                                          else Text.Start([Col2],1)), (a,b,c)=>c,{"Col2"})
in
    replace


text:
Q: Make part of a paragraph wrap above a floated image
How do I get part of a paragraph to wrap above an image like in that sunflower picture?
If I make the image relative and use top, the image will still occupy the space and the text won't wrap above. If I keep the position static and use margin-top, then it also won't wrap.
Example here:

<!DOCTYPE html>

In this example, the image will float to the right in the paragraph, and the text in the paragraph will wrap around the image.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit.

How would I move the pineapple image down while having the first three wrapping above the pineapple image?
float: right;
position: relative;
top: 60px;

Doesn't work and
float: right;
margin-top: 60px;

doesn't work.

A: In relation to that example from W3Schools, just put your image element at the most ideal position within your paragraph tag.
See the code example below, and the results that it gets. You may have to experiment with the placement of the img tag to get the exact results that you're looking for, but it's a starting point.

img {
  float: right;
}

In this example, the image will float to the right in the paragraph, and the text in the paragraph will wrap around the image.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit.

A: If you want an effect like first image, using clip-path css property might do the trick.
You can use http://bennettfeely.com/clippy/. An online tool to handle clip-path.
Using clip-path allow you to create custom and very visual dramatic eye pleased layouts for wrapping images with paragraphs.
Jen Simmons explain it in a marvelous way in her channel.
https://www.youtube.com/watch?v=pOB75oTNhw0
All her videos are treasures.


text:
Q: SSIS Bulk insert error when using SQL authentication An SSIS bulk insert error is received when using SQL authentication, while I can insert data when I use windows authentication.

[Bulk Insert Task] Error: An error occurred with the following error message: "Cannot bulk load because the file "C:\BCP\extract_remove_ref.bcp" could not be opened. Operating system error code 3(failed to retrieve text for this error. Reason: 15105).".

A: When doing a BULK INSERT with SQL Server authentication the credentials of the account used by the SQL Server service are used as specified in the documentation.  To resolve this, grant access to the folders/files that are being used in the BULK INSERT operation to the account that the SQL Server service runs under.  This can be done through Windows by right-clicking on the folder/files and going to Properties > Security > Edit > Add and type in the account name.  If you're unable to find it, make sure the right account type is selected in the Object Types window and choose the proper location from the Locations window.  If you're having trouble finding the account, type use the Check Names option.

Update 1 - Official documentation
Referring to the following official documentation:

*

*Configure File System Permissions for Database Engine Access
To Grant File System Permission to the Per-service SID

*

*Using Windows Explorer, navigate to the file system location where the database files are stored. Right-click the file system folder, and then click Properties.

*On the Security tab, click Edit, and then Add.

*In the Select Users, Computer, Service Account, or Groups dialog box, click Locations, at the top of the location list, select your computer name, and then click OK.

*In the Enter the object names to select box, type the name of the per-service SID name listed in the Books Online topic Configure Windows Service Accounts and Permissions. (For the Database Engine per service SID name, use NT SERVICE\MSSQLSERVER for a default instance, or NT SERVICE\MSSQL$InstanceName for a named instance.)

*Click Check Names to validate the entry. (If the validation fails, it might advise you that the name was not found. When you click OK, a Multiple Names Found dialog box appears. Now select the per-service SID name, either MSSQLSERVER or NT SERVICE\MSSQL$InstanceName, and then click OK. Click OK again to return to the Permissions dialog box.)

*In the Group or user names box, select the per-service SID name, and then in the Permissions for  box, select the Allow check box for Full control.

*Click Apply, and then click OK twice to exit.

Additional Information

*

*Cannot bulk load because the file could not be opened


text:
Q: How do I open more than one Nautilus explorer when there is one already opened? Why can I not open a second or third window, and so on, to view directories and files?
If I click the Home Folder button the same Nautilus window keeps showing up.

A: This is a easy way to open new Nautilus window that I found for myself:

*

*Open terminal and type gksudo nautilus /usr/share/applications/ press Enter
type your password

*Now find files application. There are two files which one of them only open one Nautilus window and the other one open more than Nautilus window if you clicked on icons.

If you go to Properties from right-click on each icons, you see there, those are different from another one (see command section)

*

*Now copy --new-window %U and paste it at the end of command section for other files application command.
now both of command text box have nautilus --new-window %U in it.

*Choice close and also close applications and terminal window.
Now I assign a shortcut (like Super+E) to open new window every where even if you are not in backgound or another Nautilus explorer is already opened.
Type Keyboard in dash and open Shortcuts tab from opened keyboard window. Select Launchers from left pane and then select second column in front of Home Folder item, now press your favorite shortcut key (mine is Super+E). After assign close keyboard window and press shortcuted key to open more than one and every where NEW Nautilus Explorer. COOL.

A: There are multiple ways to open more Nautilus windows:

*

*Middle-click the Home Folder launcher icon

*With a Nautilus window open, go to File > New Window (or get the option in the HUD)

*With a Nautilus window open, use the Ctrl+N keyboard shortcut

*Press Super+Shift+N (if it's one of the top 1 through 9 in the launcher)

A: If you have a previously opened Nautilus window, holding Shift and clicking the launcher icon will open a new window. Works for all applications.
Open a new instance of a window: Shift + Left click on launcher icon.


text:
Q: couchbase I/O thread not getting cleaned It seems couchbase I/O threads are not cleaned on Tomcat restart . I see the following every time Tomcat restarts.
cb-io-1-7 2015-04-10 12:00:40 ERROR ResourceLeakDetector:176 - LEAK: ByteBuf.release() was not called before it's garbage-collected. Enable advanced leak reporting to find out where the leak occurred. To enable advanced leak reporting, specify the JVM option '-Dcom.couchbase.client.deps.io.netty.leakDetectionLevel=advanced' or call ResourceLeakDetector.setLevel()
cb-io-1-6 2015-04-10 16:15:25 ERROR ResourceLeakDetector:176 - LEAK: ByteBuf.release() was not called before it's garbage-collected. Enable advanced leak reporting to find out where the leak occurred. To enable advanced leak reporting, specify the JVM option '-Dcom.couchbase.client.deps.io.netty.leakDetectionLevel=advanced' or call ResourceLeakDetector.setLevel()
cb-io-1-7 2015-04-10 22:38:41 ERROR ResourceLeakDetector:176 - LEAK: ByteBuf.release() was not called before it's garbage-collected. Enable advanced leak reporting to find out where the leak occurred. To enable advanced leak reporting, specify the JVM option '-Dcom.couchbase.client.deps.io.netty.leakDetectionLevel=advanced' or call ResourceLeakDetector.setLevel()
cb-io-1-8 2015-04-11 04:24:26 ERROR ResourceLeakDetector:176 - LEAK: ByteBuf.release() was not called before it's garbage-collected. Enable advanced leak reporting to find out where the leak occurred. To enable advanced leak reporting, specify the JVM option '-Dcom.couchbase.client.deps.io.netty.leakDetectionLevel=advanced' or call ResourceLeakDetector.setLevel()
cb-io-1-3 2015-04-11 12:12:08 ERROR ResourceLeakDetector:176 - LEAK: ByteBuf.release() was not called before it's garbage-collected. Enable advanced leak reporting to find out where the leak occurred. To enable advanced leak reporting, specify the JVM option '-Dcom.couchbase.client.deps.io.netty.leakDetectionLevel=advanced' or call ResourceLeakDetector.setLevel()
cb-io-1-1 2015-04-11 14:31:22 ERROR ResourceLeakDetector:176 - LEAK: ByteBuf.release() was not called before it's garbage-collected. Enable advanced leak reporting to find out where the leak occurred. To enable advanced leak reporting, specify the JVM option '-Dcom.couchbase.client.deps.io.netty.leakDetectionLevel=advanced' or call ResourceLeakDetector.setLevel()

Using Couchbase Java SDK: 2.1.0 and Tomcat: 7.