text:
Q: Как реализовать диаграмму? Пробовал на css с помощью border, но возникли проблемы с шагом. Нужно реализовать в следующем соотношении: синий блок 27%, серый - 73%. В сети очень много js-библиотек с диаграммами, глаза разбегаются. Хотелось бы сделать как можно проще и понятней.

A: Вот, пример, стилизуйте под свои нужды:

.circle-chart__circle {
  animation: circle-chart-fill 2s reverse;
  transform: rotate(-90deg);
  transform-origin: center;
}

.circle-chart__circle--negative {
  transform: rotate(-90deg) scale(1, -1);
}

.circle-chart__info {
  animation: circle-chart-appear 2s forwards;
  opacity: 0;
  transform: translateY(0.3em);
}

@keyframes circle-chart-fill {
  to {
    stroke-dasharray: 0 100;
  }
}

@keyframes circle-chart-appear {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.grid {
  display: grid;
  grid-column-gap: 1em;
  grid-row-gap: 1em;
  grid-template-columns: repeat(1, 1fr);
}

@media (min-width: 31em) {
  .grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

    <svg class="circle-chart" viewbox="0 0 33.83098862 33.83098862" width="200" height="200" xmlns="http://www.w3.org/2000/svg">
      <circle class="circle-chart__background" stroke="#efefef" stroke-width="2" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431" />
      <circle class="circle-chart__circle" stroke="#00acc1" stroke-width="2" stroke-dasharray="30,100" stroke-linecap="round" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431" />
      <g class="circle-chart__info">
        <text class="circle-chart__percent" x="16.91549431" y="15.5" alignment-baseline="central" text-anchor="middle" font-size="8">30%</text>
        <text class="circle-chart__subline" x="16.91549431" y="20.5" alignment-baseline="central" text-anchor="middle" font-size="2">30% progress!</text>
      </g>
    </svg>


text:
Q: Python: Print all names that start and end with the same letter I have a python array of employee names as follows:
employees=["Greg McGuiness", "Lola White", "Richard Bright", "Chloe Nelson", "Bradley Long", "Chiara Samos"]

I need to print out all names in which first name or last name begin and end with the same letter, in my example it should print these names:
Greg McGuiness
Chloe Nelson
Chiara Samos

I have been playing around with the regex expressions but can't seem to get it right.

A: You can do that without regex:
for i in employees:
    for name in i.split(' '):
        if name.lower().endswith(name[0].lower()):
            print i
            break

A: Why regex? Here's a terrifying "one liner".
from itertools import izip

employees=["Greg McGuiness", "Lola White", "Richard Bright", "Chloe Nelson", "Bradley Long", "Chiara Samos"]

print([
    n for n, (f, l) in izip(employees, (e.split(' ') for e in employees))
    if f[0].lower() == f[-1].lower()
    or l[0].lower() == l[-1].lower()
])
['Greg McGuiness', 'Chloe Nelson', 'Chiara Samos']

A: You don't need regex for this
for employee in employees:
    for name in employee.split(" "):
        if name[0].lower() == name[len(name)-1].lower():
            print(employee)

A: I will give a solution with regex.
import re
employees=["Greg McGuiness", "Lola White", "Richard Bright", "Chloe Nelson", "Bradley Long", "Chiara Samos"]
print [i for i in employees if re.findall(r"\b(\w)\w*\1\b",i,re.I)]

A: For the sake of true functional one liner :)
In [5]:
filter(lambda e: any(x[0].lower() == x[-1].lower() for x in e.split()), employees)

Out[5]:
['Greg McGuiness', 'Chloe Nelson', 'Chiara Samos']

Or more readable:
filter(
  lambda e: any(x[0].lower() == x[-1].lower()
                for x in e.split()),
  employees)

Not RE though...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Argument list too long - echo in container The container is running a Ruby Application that will generate a huge string (not sure how huge) and I am storing it in a variable (index_render) and appending that into a file.
system("echo '#{index_render}' > temp/temp.html")

But I am getting Errno::E2BIG: [!] Argument list too long - echo
I am using a container alpine/bundle:2.7.2 that will run a ruby application and inside the application, ruby will call a node application. So I am installing nvm, node, etc from the alpine/bundle:2.7.2 image as init script (like provisioning script).
Is there any way to increase the size using the init script? as I don't have access to modify the Ruby application.

A: This because system() in many languages calls through actual shell, by default /bin/sh.
There might be several problems:

*

*the text in variable contains ' character many times, which breaks ' wrapping the variable into many small bits until number of arguments is exhausted

*the text expanded from variable is too big to parse for shell, that is being invoked by system(), so the shell dies with this error

*the text expanded from variable is really too big to fit into the argv kernel buffer

Why don't you fix application to write into target file directly by default, without intermediary "echo +variable + shell redirect" step?


text:
Q: How to filter records based on a criteria per group In SQL how can I express this question: For all groups, return all records in a group that match the result of a condition specific to the group.
For example:
Book: (Id, Title, AuthorName, PublishDate)

Return all records in Book table that if the books are grouped by the AuthorName, they are the fifth or later books of that specific author.
I'm using MS SQL Server 2016.

A: The solution to this is basically the same as Get top 1 row of each group, however, instead of = 1 you want >=5:
WITH CTE AS(
    SELECT {Columns}
           ROW_NUMBER() OVER (PARTITION BY Author ORDER By PublishDate) AS RN
    FROM dbo.YourTable)
SELECT {Columns
FROM CTE
WHERE RN >= 5;

A: You can also use a correlated subquery for this:
select t.*
from t
where t.publishdate >= (select t2.publishdate
                        from t t2
                        where t2.author = t.author
                        order by t2.publishdate asc
                        offset 4 fetch first 1 row only
                       );


text:
Q: Is it possible to use Newtonsoft.Json when using HttpClient.PostAsJsonAsync(something)? Let's say I want to add a typed HttpClient like this:
services.AddHttpClient<ISomeService, SomeService>(c =>
{
    c.BaseAddress = new Uri(someUrl);
});

Is it possible to force it to use Newtonsoft.Json for serialization when sending requests? Preferably in a similar fashion how it can be added for controllers:
services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });

So that when I use HttpClient instance like that: await httpClient.PostAsJsonAsync(testDto), Newtonsoft.Json serializer is used instead of the built-in one.
EDIT: Just noticed that PostAsJsonAsync(...) and GetFromJsonAsync(...) I am using are extension methods defined in System.Net.Http.Json, which basically renders this whole question invalid.

A: If you want to use Newtonsoft.Json, use the extension methods on the System.Net.Http.HttpClientExtensions class.
If you want to use the new System.Text.Json, use extension methods on the System.Net.Http.Json.HttpClientJsonExtensions class.


text:
Q: Google Cloud Video API gives error on using "input_content" argument I am trying to use Google Video API and pass a video which is on my local drive using the "input_content" argument but I get this error: InvalidArgument: 400 Either `input_uri` or `input_content` should be set.
Here is the code based on Google Documentation:
"""Detect labels given a file path."""
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.Feature.LABEL_DETECTION]

cwd = "E:/Google_Video_API/videos/video.mp4"
with io.open(cwd, "rb") as movie:
    input_content = movie.read()

operation = video_client.annotate_video(
    request={"features": features, "input_content": input_content}
)

A:  Video file need to be Base64 encoded so try this:
import base64
...
operation = video_client.annotate_video(
    request={"features": features, "input_content": base64.b64encode(input_content)}
)


text:
Q: CSS Calc() using two pixel amounts to get a percentage I want to do basic calculations in CSS to get a responsive layout.
Is it possible to get a % output from a basic equation, e.g. can I get the width in the below example to be set to 72%?
    width: calc(540px / 750px);

This would make the audit trail in my work easier to follow as a number of percentages will be odd, e.g. 13.33333333% etc.
Thanks

A: You need to pass a % unit, than the desired integer values

div{
  background:red;
  height:24px;
  width: calc(100% * (540 / 750));               /* 72% */
}


text:
Q: Minimum distance between a vector and a subspace I have a subspace S of R4 with basis (w1, w2, w3).
And i have some vector x and i'm asked to determine the vector s in subspace S that is closest to x, that is, find s that minimizes ||x-s||.
I did this question by projecting vector x onto subspace S (i did the projection of x onto w1, w2, w3)
However, when i asked professor about this question, he told that in order to find the minimum distance between a vector and subspace, we need to produce an orthogonal basis for S and only then do the projection of vector x onto orthogonal basis.
Can someone explain why do i necessarily need orthogonal basis and why can't i just project vector x onto set of vectors that are not orthogonal to each other?

A: If you have a point $x$ and a subspace $S$, then the orthogonal projection of $x$ onto $S$ is the unique $s_0\in S$ such that $(x-s_0)\perp S$, meaning that $(x-s_0)\cdot s=0$ for all $s \in S$. The closest point projection of $x$ onto $S$ is the unique $s_0 \in S$ such that $\|x-s_0\| \le \|x-s\|$ for all $s\in S$. The closest point projection and the orthogonal projections exist and are the same.
In your case, you want to find $s=\alpha_1 w_1 + \alpha_2 w_2 + \alpha_3 w_3$ such that
$$
                (x-\alpha_1 w_1 - \alpha_2 w_2-\alpha_3 w_3) \perp w_1 \\
           (x-\alpha_1 w_1 - \alpha_2 w_2-\alpha_3 w_3) \perp w_2 \\
           (x-\alpha_1 w_1 - \alpha_2 w_2-\alpha_3 w_3) \perp w_3.
$$
This gives you a 3x3 matrix problem for thecoefficients $\alpha_1,\alpha_2,\alpha_3$:
$$
         \begin{pmatrix}
                  w_1\cdot w_1 & w_2 \cdot w_1 & w_3 \cdot w_1 \\
                  w_1\cdot w_2 & w_2 \cdot w_2 & w_3 \cdot w_2 \\
                  w_1\cdot w_3 & w_2 \cdot w_3 & w_3 \cdot w_3
         \end{pmatrix}
         \begin{pmatrix}
                \alpha_1 \\
                \alpha_2 \\
                \alpha_3
         \end{pmatrix} =
         \begin{pmatrix}
               x\cdot w_1 \\
               x\cdot w_2 \\
               x\cdot w_3
         \end{pmatrix}
$$
This is an invertible 3x3 matrix if $\{w_1,w_2,w_3\}$ is a linearly independent set of vectors. The coefficient matrix is symmetric.
The alternative is to find an orthonormal basis of $S$, as your Professor mentioned.


text:
Q: Button with a image, is possible? I am develop an UWP app and I want a button with a image, but I dont know how I make this. This is possible?
I want a button that has an image, or an image where it is possible to click on it!
I have tried several ways, and I dont know! I am using XAML and C#, in Visual Studio 2015

A: you can use Source attribute to Image control. you can try some thing like this

<Button Grid.Column="0" Height="39" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Padding="0" BorderThickness="0">
        <Image Source="location/img.png" Stretch="UniformToFill"/>
  </Button>

A: Using Xaml you can find out that Button has attribute called Content which basically can store any kind of control inside.
<Button Content="<defaultly you put a string in here>"/>
But if you want to display some other type of content inside you can use something like this :
<Button >
    <Button.ContentTemplate> <!-- This will create new template for the button's content -->
        <DataTemplate>
            <Image Source=""/>
        </DataTemplate>
    </Button.ContentTemplate>
</Button>

Or alternatively :
<Button >
    <Button.Content> <!-- This will create only the content control inside of this particular button object -->
        <Image Source="" />
    </Button.Content>
</Button>

Or use method posted by @Midhun Mundayadan

A: You can use the MouseLeftButtonUp event handle of the image control to simulate button click
<Image MouseLeftButtonUp="Image_MouseLeftButtonUp" Source="img.png"/>


text:
Q: InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': HTTP Request with Intermediate Model and service I have an angular app which consists of a form which sets the fields of a model object and then the object itself is sent as JSON to my backend. However whenever I try to use the following approach with image/file upload, I get an error:
core.js:4352 ERROR Error: Uncaught (in promise): InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
Error: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
    at EmulatedEncapsulationDomRenderer2.setProperty

How can I get past this? Also, I cannot try change the approach of the Form so please try and suggest something within this approach.
html
<mat-toolbar>Avatar/Logo</mat-toolbar>
            <input type="file" id="my-input" (change)="onFileSelected($event) [(ngModel)]="temp_file">

.ts
  onFileSelected(event){
    this.temp_file = <File>event.target.files[0];
    this.detail.logo = this.temp_file;
  }

details.model.ts

export class Detail {
...
    logo: File;
...
}

A: First, you need to remove the [(ngModel)], then, append the this.temp_file the form when uploading it to the server, here is a sample code for the service.ts which does the http post:
dsds
postFile(fileToUpload: File, formData: FormData): Observable<boolean> {
    const endpoint = 'your-destination-url';
    formData.append('my-input', fileToUpload, fileToUpload.name);
    return this.httpClient
      .post(endpoint, formData, { headers: yourHeadersConfig })
      .map(() => { return true; })
      .catch((e) => this.handleError(e));
}

fileToUpload is temp_file which is sent from the component to the service.


text:
Q: Suppose f is a multiplicative function such that, for odd primes p, f(p) = 3p How would one go about this question? I am unsure of what to do.

Would you do for f(11)

*

*f(11)= f(8)+f(p), where p=1

*f(11)= 9x3(1)  = 27

A: $p=11$ is an odd prime, so $f(11) = 3\cdot 11 = 33$

A: $$f(11)=3\times 11 =33$$
$$f(64)=f(2^6)=0$$ because $6>3$.
$$f(100)=f(4\times 5^2)=f(4)\times f(5^2)=5\times 2=10$$
$$f(80)=f(2^4\times 5)=f(2^4)\times f(5)=0\times (3\times 5)=0$$


text:
Q: Deleting custom object via destructiveChanges.xml and Metadata API deploy() I've created a custom object in a developer edition org with the sole intention of deleting it via the Metadata API as per Deleting Components from an Organization.

To do this I created the following files:
package.xml
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <version>33.0</version>
</Package>

destructiveChanges.xml
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>DFB__ObjectToBeDeleted__c</members>
        <name>CustomObject</name>
    </types>
</Package>

Then zipped them both into destructiveChanges.zip.

I uploaded the resulting zip file to the Workbench Metadata Deploy page and deployed it.
The processing status came back as successful.

However, the custom object is still present and there is no indication that it has been deleted.
I've tried:

*

*both with and without the namespace prefix for the member name in the destructiveChanges.xml.

*change the package manifest version to be 32.0 to match the version that Workbench is using.

*checking Purge On Delete in the Workbench deploy options.

*both including and excluding the version element in the destructiveChanges.xml.

Why can't I delete this custom object using destructive changes?
Note that this will ultimately be part of a much larger set of deletions. I could potentially use deleteMetadata(), but I'd rather figure out what is wrong with my deploy() call.

A: It turns out the following DeployOptions setting was what I was missing:

singlePackage
boolean
  Indicates whether the specified .zip file points to a directory structure with a single package (true) or a set of packages (false).

I needed to set this to true, as I assume my flat zip file represents a single package. After doing that the Number of Components Deployed became 1 and the custom object moved into Deleted Objects (as I hadn't checked purgeOnDelete).


text:
Q: Bootstrap form labels not placed before the textbox? I'm not seeing why the following code is putting the labels to the right of the textbox instead of the to the left? Should I be using
 around the
?
Anyone know what I'm missing?

    @using (Html.BeginForm("EditClockGroup", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(false, "", new { @class = "alert alert-danger" })

        @Html.HiddenFor(model => model.GroupId, null)

            @Html.LabelFor(m => m.GroupId, new { @class = "col-md-2 control-label" })
            @Html.TextBoxFor(m => m.GroupId, new { @class = "col-md-7 form-control" })

            @Html.LabelFor(m => m.GroupName, new { @class = "col-md-2 control-label" })
            @Html.TextBoxFor(m => m.GroupName, new { @class = "col-md-7 form-control" })

                <input type="submit" value="Update" class="btn btn-primary" />

    }

A: You cannot apply col-md-7 to input tag. Instead, you need to place input inside div.

   @Html.LabelFor(m => m.GroupId, new { @class = "col-md-2 control-label" })

      @Html.TextBoxFor(m => m.GroupId, new { @class = "form-control" })


text:
Q: Webview and iframe fail to show Youtube videos in a sandboxed iframe in Chrome packaged app I am developing a Chrome packaged app (not a legacy packaged app); my app needs to contain a sandboxed iframe (to run 3rd party HTML/JS code), in which I need to use a webview or an iframe to show a Youtube video. Neither works; I cannot play any Youtube videos. (The webview works, however, when used outside the sandboxed iframe.)
Main HTML file looks like this:

The file sandbox.html is declared in manifest.json. It looks like this (I'm trying two alternative ways of playing a Youtube video):
<webview width="420" height="315" src="http://www.youtube.com/embed/XGSy3_Czz8k"></webview>

When I run this app, the webview is an empty white rectangle. The iframe, on the other hand, contains a cover image and the Youtube player controls for the video.
Firstly, why is the webview empty? The webview works in this app (plays video) as long as I use the webview outside the sandboxed iframe. When the webview is inside a sandbox, it silently refuses to load anything.
Secondly, there are errors in the console when I run this app:
 GET chrome-extension://boadgeojelhgndaghljhdicfkmllpafd/cast_sender.js net::ERR_FAILED www-embed-player.js:140
 GET chrome-extension://dliochdbjfkdbacpmhlcpmleaejidimm/cast_sender.js net::ERR_FAILED www-embed-player.js:140
 GET chrome-extension://hfaagokkkhdbgiakmmlclaapfelnkoah/cast_sender.js net::ERR_FAILED www-embed-player.js:140
 GET chrome-extension://fmfcbgogabcbclcofgocippekhfcmgfj/cast_sender.js net::ERR_FAILED www-embed-player.js:140
 GET chrome-extension://enhhojjnijigcajfphajepfemndkmdlo/cast_sender.js net::ERR_FAILED www-embed-player.js:140

These errors come when I load the iframe shown above, inside the sandboxed page. These errors are strange (why is Chrome trying to load a JS file out of some random Chrome extensions?)
When I try to start playing the video in the iframe, I get sometimes the message "An error occurred" from the Youtube player, and sometimes no message but the player goes black. In all cases, I have this error on the console:
 XMLHttpRequest cannot load https://www.youtube.com/get_video_info?html5=1&video_id=S2VXOd3uXh8&cpn=Rso…=en_US&sts=16309&lact=11140&width=300&height=300&iframe=1&c=web&cver=html5. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

My manifest.json has all necessary permissions:
 "permissions": [
 "http://www.youtube.com/*", "https://www.youtube.com/*", "webview" ],
 "sandbox": {
   "pages": [ "sandbox.html" ]
 }, ...

I tried <object data=...>, <embed src=...>, MediaElement - none of them works at all in a Chrome app.
I am at a loss and can't find any relevant information on the Web either.

*

*Why is the webview blank when it is inside a sandboxed iframe?

*Is there something I can do to make webview or iframe work inside a sandboxed iframe in a packaged Chrome app to show Youtube videos?

A: You should load the URL directly into the webview, not through an iframe.
Your main HTML should contain:
<webview  width="420" height="315" src="http://www.youtube.com/embed/XGSy3_Czz8k"></webview>

directly.
I tried loading your URL http://www.youtube.... into the browser sample app, which loads the URL inside a  and seems to work fine.
The browser sample app can be found here for reference:
webview-samples/browser

A: A workaround is to use a webview in which to play the videos using an iframe.
This creates a bunch of other problems, such as the asynchronous nature of webview, the fact that a webview will silently unload everything if it's made invisible, etc. But at least videos play.
No other combination works: I tried a webview inside a webview, or an iframe inside of an iframe, or a webview inside an iframe.
Main HTML file:
 <webview src="sandbox.html" partition="static"></webview>

Inside sandbox.html:

In manifest.json:
   ...
   "permissions": [
      "http://www.youtube.com/*", "https://www.youtube.com/*",
      "webview" ],
    "sandbox": {
      "pages": [ "sandbox.html" ]
    },
    "webview": {
      "partitions": [
        {
          "name": "static",
          "accessible_resources": ["sandbox.html"]
        }
      ]
    }


text:
Q: Trailing colons and dash's builtin test command What's the meaning of a trailing colon to dash's builtin test (or [) command? I was surprised when I found that if [ ... ]: ; then .. ; fi works (at all) in dash, but not bash, and it seems to be because the builtin's behavior differs from the command's.
$ /usr/bin/\[ 1 ] && echo 1
1
$ /usr/bin/\[ 1 ]: && echo 1
/usr/bin/[: missing `]'
$ [ 1 ]: && echo 1
1

A: It seems to be more of an issue if parsing the commands.  bash expects the closing bracket to be the last argument and complains if it not exactly a "]" string.
bash$ [ 1 ]
bash$ [ 1 ] hi
bash: [: missing `]'
bash$ [ 1 ]hi
bash: [: missing `]'
bash$ dash
$ [ 1 ]
$ [ 1 ] hi
dash: 2: [: missing ]
$ [ 1 hi]
dash: 3: [: missing ]
$ [ 1 ]:
$ [ 1 ]hi
$

The dash shell will just make sure that the first character is "]" and ignore the rest.  If the "]" is not in the first character of the last argument, then it returns a similar error as bash.


text:
Q: How works this If statement? I'm trying to teach myself fortran so I can unravel an old program and repurpose it for our own use.  I can't figure out what this statement does:
if(s - fm) 198, 198, 197

s - fm isn't a condition that can be true or false, right?.
And when it passes control to the line marked 198, does it then continue to the end of the program?  How does it know when to come back to execute 198 again and then 197?

A: This is an "archaic" form of IF:
IF (''arithmeticExpression'') ''firstLineNumber'', ''secondLineNumber'', ''thirdLineNumber''

In the second form, the arithmetic expression is evaluated. If the expression evaluates to a negative number, then execution continues at the first line number. If the expression evaluates to zero, then execution continues at the second line number. Otherwise, execution continues at the third line number.
It's a "three-way goto" depending on the sign of the expression.
In a more traditional C-like language it wood be
/* IF(a) label1, label2, label3 */

if(a > 0)
{
   goto label3;
} else
if(a < 0)
{
   goto label1;
} else
{
   // a == 0
   goto label2;
}

Your case contains two labels 198 which works like
if(s <= fm) { goto lbl198; } else { goto lbl197; }

Ref: wikibooks

A: This obsolete feature puzzles a lot of people:
FORTRAN compiler warning: obsolete arithmetic IF statement
Fortran strange IF
strange label usage


text:
Q: How to achieve read More functionality with single div only
This is my content containing some general large text to display ...
   Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,          when an unknown printer took a galley of type and scrambled it to make a type  specimen book. It has survived not only five centuries, but also the leap into  electronic typesetting, remaining essentially unchanged. It was popularised in  the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

How can I achieve read more functionality of expanding content on clicking (...)
without any other nested Divs or Tags "Just Single Div"
Thanks in advance

A: Do something like that:
HTML

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

CSS
.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

JAVASCRIPT
$(".truncate").click(function() {
    $(this).removeClass("truncate");
});

A:

$(function() {
  var length = $("#content").text().length;
  var originalText = $("#content").text();
  var splittedText = "";

  if (length > 100) {
    splittedText = $("#content").text().substring(0, 100);
    splittedText += "...";
    $("#content").after("<input id='button_more' type='button' value='read more'/>");
  }

  $("#content").text(splittedText);

  $("#button_more").click(function() {
    $("#content").text(originalText);
    $("#content").hide(0);
    $("#content").show(1000);
    $("#button_more").hide(1000);
  });
});

<!DOCTYPE html>

    <title>read more test</title>
    <meta charset='utf-8'/>

      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur varius justo ac ante hendrerit, id convallis     felis fermentum. Fusce vehicula, eros ut blandit lobortis, dui nunc euismod massa, non placerat sapien dolor in libero. Interdum et malesuada fames ac ante ipsum primis in faucibus. Praesent nec est in sapien finibus bibendum. Proin turpis odio, pulvinar id convallis ac, condimentum ac enim. Vestibulum eu ante sit amet nisl commodo hendrerit vitae non tortor. Fusce feugiat magna at tempus dictum. Sed pharetra volutpat risus sit amet rhoncus. Morbi maximus lectus purus, venenatis sodales orci luctus eget. Ut viverra commodo tempus. Morbi varius diam id ex dignissim pulvinar. Aliquam ac tincidunt lectus. Nulla pulvinar dolor eros, at porttitor lacus sagittis ut.

This snippet cut a text by saving the first 100 caracters, adding "...", and a button which let the user show the whole text by clicking it.

A: Supposing your text has multiple paragraphs, you can split it:
var size = $("#" + read_more_id + " p").size();

and implement something like this: http://jsfiddle.net/451zncwn/1/. This example also automatically adds "read more" and "read less" links.


text:
Q: Upload zip file to spring rest controller using angular 4 I want to upload .zip file to server (spring rest controller) from angular 4.
Please suggest how to do so?
thanks in advance

A: After some learning, i have found the answer to how to upload file(.zip/.txt/ any other file format) from angular (4/5) to spring/rest controller. Writing down my learning below for those who looking same thing.:)
Front-end coding ::
1. HTML (eg. UploadFile.component.html):
<input type="file" formControlName="uploadFile" (change)="uploadFileToServer($event)"/>

2. Component (eg. UploadFile.component.ts) :
import { Component } from '@angular/core';
import { RequestOptions, Headers, Http } from '@angular/http';
@Component({
  selector: 'file-uploader',
  templateUrl: './uploadFile.component.html',
  styleUrls: ['./uploadFile.component.css'],
})
export class FileUploadComponent {

public uploadFileToServer(event) {
  let fileList: FileList = event.target.files;
  if (fileList.length > 0) {
    let file: File = fileList[0];
    let formData: FormData = new FormData();
    formData.append('uploadFile', file, file.name);
    formData.append('fileType', 'zip');
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    this.http.post('domain/urservice', formData, options)
      .map(res => res.json())
      .catch(error => Observable.throw(error))
      .subscribe(
      data => console.log('success'),
      error => console.log(error)
      )
  }
}

}

(note - this server communication call should be present in some service not in component but for simplicity i am writing it in component)
server-side coding ::
1 .  Spring/Rest controller (FileUploadController.java) :
    @RequestMapping(value = "/urservice", method = RequestMethod.POST)
    public void uploadFile(MultipartHttpServletRequest request) throws IOException {

    Iterator<String> itr = request.getFileNames();

    // directory to save file
    String tempDir = System.getProperty("jboss.server.temp.dir");

      MultipartFile file = request.getFile(itr.next());
      String fileType = request.getParameter("fileType");
      String fileName = file.getOriginalFilename();

      File dir = new File(tempDir);
      File fileToImport = null;
      if (dir.isDirectory()) {

        try {
            fileToImport = new File(dir + File.separator + fileName);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileToImport));
            stream.write(file.getBytes());
            stream.close();
        } catch (Exception e) {
            logger.error("Got error in uploading file.");
        }

}

A: 1) Have a look here:
https://angular.io/guide/http#making-a-post-request
So you can build a service which gets triggered when you press submit in a form, which attaches the file, whatever that is, a zip, img or whatever to the POST request.
2) In your template you can use something similar:
<form>
  <input type="file" accept=".zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed">
  <input type="submit">
</form>

3) Have a look here to force the file extention:
https://www.hongkiat.com/blog/css3-attribute-selector/


text:
Q: String in Switch for both upper and lower case In Switch case to take input for both upper and lower case is it correct as I have written below or is there any other better way.
 import java.util.Scanner;
public class SwitchDemo {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter 'IN' or 'OUT': \n");
    String c = sc.nextLine();
    switch(c) {
         case "IN" :
              System.out.println("\nWelcome to My PC\n");
               break;
        case "OUT":
              System.out.println("\nGood Bye\n");
              break;
        case "in" :
              System.out.println("\nWelcome to My PC\n");
               break;
        case "out":
              System.out.println("\nGood Bye\n");
              break;
       default:
          System.out.println("\nInvalid input\n");
         }
  }
}


text:
Q: Hazelcast: How to get Map Entry hit count on near cache? We ae using hazelcast enterprise edition and have a requirement to get the number of hits for an entry in a map in hazelcast. We have near cache enabled for the map. We were thinking of using the entryview object to get the number of hits for this set of keys but because of near cache the number of hits are updated in near cache but not on the hazelcast server.Is there a way to get the information of number of hits for a map entry at the client side?

A: Since you are an enterprise user, I suggest you use official Hazelcast support channel for your queries.
To answer your question quickly, here is the excerpt from documentation:

If you are using Near Cache, you should take into account that your
  hits to the keys in the Near Cache are not reflected as hits to the
  original keys on the primary members. This has for example an impact
  on IMap's maximum idle seconds or time-to-live seconds expiration.
  Therefore, even though there is a hit on a key in Near Cache, your
  original key on the primary member may expire.

Here is the documentation: https://docs.hazelcast.org/docs/3.10.5/manual/html-single/index.html#near-cache


text:
Q: How to create nested JSON data type? I want to creat the JSON file of the following data to create dropdown menues in using JavaScript code.
The user first chooses the item, this will limit the size options. Then, he/she will use the size, and based on the selection price will be determined.
After choosing all the required elements, the final price will be calculated.
item   size             price ($)
 A      less than 3      5
 A      greater than 3   4
 B      less than 10     6
 B      between 10 & 20  5
 B      greater than 20  4

Here is what I have written so far:
items = [
    {
        "item" : "A",
        "size_1"  : "less than 3",
        "size_2"  : "greater than 3",
        "price_1"     : "5"
        "price_2"     : "4"
    },
    {
        "item" : "B",
        "size_1"  : "less than 10",
        "size_2"  : "between 10 & 20",
        "size_3"  : "greater than 20",
        "price_1"     : "6"
        "price_2"     : "5"
        "price_3"     : "4"
    }
]

Is this how I should have done it? What is the best way to do so?

A: It's really up to you how you want to model your data. The way you have is fine, but there are benefits to having every item's data-model looking the same. I would probably do the following:
var items = [
  {"item": "A", "size": "less than 3", "price": 5},
  {"item": "A", "size": "greater than 3", "price": 4},
  {"item": "B", "size": "less than 10", "price": 6},
  {"item": "B", "size": "between 10 & 20", "price": 5},
  {"item": "B", "size": "greater than 20", "price": 4},
];

If you didn't need items to be a list with order, you could make it a map where item seems to be a key:
var items = {
  "A": [
    {"size": "less than 3", "price": 5},
    {"size": "greater than 3", "price": 4}
  ],
  "B": [
    {"size": "less than 10", "price": 6},
    {"size": "between 10 & 20", "price": 5},
    {"size": "greater than 20", "price": 4}
  ]
];

Etc. You could come up with tons of ways to represent your data. Only you know what makes the most sense for your implementation.


text:
Q: Create an extension to the browser to acces local scanner I would like to access a special hardware (a penta scanner, for the wisest ;) ) from a web page.
The aim is to retrieve the information from the scanner and compute it on server side.
The problem here, is that I have to summon functions from a DLL that has to be on the client side. I have two leads for that:

*

*Develop a COM DLL and use ActiveX

*Try to get through a homemade extension for a web browser in order to communicate with the local DLLs.

I've tried the first option, and I got stuck and I've posted another thread about it. Anyway, even if it works, there are too many constraints about it (as to use IE or the fact that even Microsoft is not fond of this feature and banned it from edge).
The second method is something that I found on another forum but, I do not understand how I can interact with a browser extension (whatever the browser).
So what I am asking is:
Is it possible to use a web browser extension as a medium to a local DLL and if so, would you be so kind as to give a hint about how to do ar anything that might look like a start about how to do it (even just some key words to use on google, since mine didn't get anything)....
Thanks.

A: Based on my understanding, the motive to develop an Extensions is to enhance the feature and functionality for particular web browser.
You cannot control any hardware devices like printer or scanner with it.
So if your goal is to control the scanner from your web page with the help of any kind of extension than I think you cannot do this with Extension.


text:
Q: Kadane algorithm in Scala explanation I am interested in learning how to implement the Kadane (maximum subarray sum) algorithm in scala with foldLeft function. I run through this example on stack overflow, however I am not sure I understand what the algorithm does exactly. This is how the algorithm looks like:
someArray.foldLeft(0 -> 0) {
      case ((maxUpToHere, maxSoFar), n) => val maxEndingHere = 0 max maxUpToHere + n
        maxEndingHere -> (maxEndingHere max maxSoFar)
    }._2

Is the content included in the {} the lambda function that needs to be applied on every element? and also what does this line do exactly maxEndingHere -> (maxEndingHere max maxSoFar)? Why are the brackets in the parenthesis separated by space? I appreciate any help, sorry if my question comes across as too ignorant, but I am new to Scala

A: First, you need to understand what foldLeft is. The meaning of this function is to fold over collection into a single value, by passing combining operation and initial element:
// Think of applying op(op(op(…), z) from left to right:
def foldLeft[B](z: B)(op: (B, A) ⇒ B): B

Now, let's see what's happening in your foldLeft. First, the 0 -> 0 is passed. It means that the type B of the initial element is a tuple (Int, Int) with the value (0, 0).
Second, the opening brackets define a function. In scala you can pass it with curly braces. So, the function expects arguments of (B, A) in our case the type B is a tuple (Int, Int) and the type A is the type of an Array elements which is Int.
So, when you can translate your code like this:
someArray.foldLeft(0 -> 0) {
  (tuple: (Int, Int), element: Int) => //the body
}

Now, in Scala you can create partial functions with case keyword by applying provided pattern. The pattern in our case matches the provided argument by binding the variables maxUpToHere and maxSoFar to the tuple elements and the n to the element of an array.
So, the function will take each element from an array, apply it with the provided tuple and pass it to the next application until the array was processed fully. Now, let's see what's happening in function body:
val maxEndingHere = 0 max maxUpToHere + n
maxEndingHere -> (maxEndingHere max maxSoFar)

Remember, that our function should return the next B to apply for invocation with element from an array. The B is a tuple in our case. So, the idea is to store the overall max and the local max of the sequence in a tuple.
The maxEndingHere takes the max between 0 and the sum of the previous calculation with the current element of an array n. If the current element will be negative, it will reduce the max sequence hence produce 0 on the max comparison result, thus resetting the accumulated value.
Then we just create new tuple with the new calculated sum of the sequence maxEndingHere and the maximum between current value and the one that is calculated so far (hence the name maxSoFar).
And lastly, we just take the second value of the calculated tuple by calling ._2.

A: {}

lambda function will be applied on every element in array
maxEndingHere -> (maxEndingHere max maxSoFar)

It will set maxUpToHere to maxEndingHere and maxSoFar to result of maximum between maxEndingHere and maxSoFar for the next iteration
So to dry run the code: for the below array the code with run as follows for each element of array
someArray: Array[Int] = Array(5, 2, -10, 6, 8)

For element n = 5
maxUptoHere = 0
maxSoFar = 0
n = 5
maxEndingHere = 5

For element n = 2
maxUptoHere = 5
maxSoFar = 5
n = 2
maxEndingHere = 7

For element n = -10
maxUptoHere = 7
maxSoFar = 7
n = -10
maxEndingHere = 0

For element n = 6
maxUptoHere = 0
maxSoFar = 7
n = 6
maxEndingHere = 6

For element n = 8
maxUptoHere = 6
maxSoFar = 7
n = 8
maxEndingHere = 14

res15: Int = 14


text:
Q: Is there a library for UNSIGNED integers with 256 or 512 bits for .Net? I know there is Bigmath, but those ints are signed. Is there a lib for unsigned integers with 256 or 512 bits in .net? (Not unlimited like BigInt...)

A: Googling UInt256 I easily found https://github.com/pmlyon/BitSharp/blob/master/BitSharp.Common/UInt256.cs.


text:
Q: How to kill a sleep process using a script I want to write a script that will do the following things:

*

*start a sleep 500 command in the foreground.

*then send the sleep 500 command in the background so that I can get my prompt back

I have tried doing this inside the script:
sleep 500
kill `pidof sleep`

But when I am running the script, the sleep command does not stop and I do not get my prompt back.

A: I can't find the exact dup I was looking for so here is a short example. If I understand what you are wanting, you want to start a sleep process and then at any time you want to be able to quit the sleep process returning you to your prompt. You say "background" the sleep process, but I'm not sure whether you actually need to background it to let it expire on its own in the future, or if just need a way out of the sleep whenever you choose (that would make more sense)
While you can simply use Ctrl + C to interrupt the process, you won't be returned to your script. So if you need a way to return to your script, you need to trap SIGINT. When you set a trap 'some command' SIGINT your script will intercept and process the interrupt and control will return to the point following the sleep command, e.g.
#!/bin/bash

## set trap
trap 'printf "\n[Ctrl + C] SIGINT intercepted\n"' SIGINT

printf "sleeping 500...\n"

sleep 500

## rest of script after sleep
printf "control returned to script\ncontinuing to process commands\n"

Example Running Script Above
$ bash trap_int.sh
sleeping 500...
^C
[Ctrl + C] SIGINT intercepted
control returned to script
continuing to process commands

That may or may not satisfy what you need. However, you can build on that to control what happens after an interrupt a bit further. When you set the trap you can have it call a separate function within your script that can conditionally execute code and end the script on that separate branch by calling exit. That has the effect of transferring control back to your script to only execute commands from the path that starts with the function you specify. This provides away to avoid executing code that follows the sleep, while providing a separate execution path in your script to run whatever is needed after interrupt from sleep.
Conditionally Executing Commands After Interrupt
Rather than just sleep 500, in the next example we will repeatedly call two functions sleep_a which calls a nested sleep function sleep_b. Following SIGINT control will be passed to a function named handle_interrupt where additional commands can be executed calling exit to exit the script and return you to your prompt. An additional function called actual_exit is called to perform the exit.
#!/bin/bash

## function called to exit, returning you to prompt
function actual_exit
{
    printf "  Exiting after '%s'\n\n" "$1"
    exit
}

## function called after SIGINT, calls actual_exit to disply signal caught
function handle_interrupt
{
    printf "\n  Signal SIGINT Caught! [ctrl + c]\n\n"
    actual_exit 'SIGINT'
}

## set trap
trap handle_interrupt SIGINT      # calls handle_interrupt on [ctrl + c]

declare -i idx=0    ## loop counter

function sleep_b
{
    printf "\nentering sleep_b\n"
    sleep 2
    printf "executing post sleep_b index: %s\n" $((idx++))
}

function sleep_a
{
    printf "\nentering sleep_a\n"
    sleep 2
    printf "executing post sleep_a index: %s\n" $((idx++))
    sleep_b
}

## repeatedly call nested sleep until signal received
while :; do
    sleep_a
done

## rest of script after sleep
printf "control returned to script\ncontinuing to process commands\n"

When the script is interrupted, the command following below the while loop are never reached as the script exits through the code path provided by the function called on SIGINT.
Providing Common Commands On exit
You can add yet another layer of execution by setting a trap on EXIT. If you have a collection of signal you set a trap for, you can have all end though a common function. For example if you monitored multiple signals each returning to a function ultimately calling exit, you can set a trap on EXIT calling a final function holding commands to be executed before the script exits.
For example, you could do:
trap final_function EXIT  # calls final_function on exit() from script

where a call to exit anywhere within the script would invoke the trap on EXIT calling final_function before returning control back to you.
Let me know if something like one of the incremental levels of handling canceling sleep though an interrupt will do what you need. Technically it doesn't "background" sleep, but does allow you to cancel the sleep at any moment conditionally returning control within your script to wherever you choose.


text:
Q: A loop to check a value multiple rows with conditions Database Image
I'm struggling with how to approach this problem.
What I have working:
I want to print all 3 rows in my table (Will attach example), and display the value in the EID column.

*

*I want to test if the value of EID1 (first row) Starts with 8. (Done)

*I want to test if the value of CID1 (first row) Starts with "M". (Done)

*Now I want to loop the entire table and check the following conditions for each row, as an example:(Done)

*If EID1 =< 8 and CID1 starts with M, print pass, else, print fail.

*If EID2 =< 8 and CID2 starts with M, print pass, else, print fail.

I'm getting the following error: Cannot invoke "String.startsWith(String)" because the return value of java.util.Map.get(object) is null.
I think this is probably because row (0) is actually null. I probably need to work out a way to skip the first iteration or there's an issue with my logic.
    query = "select * FROM PSA.SECOND where T_DATE >'2202-10-10'";

    resultSet = statement.executeQuery(Query)
    ResultSetMetaData rsmd = resultSet.getMetaData();
    long pId = 1:
    while (resultSet.next()) {
    for int col = 1; col <= rsmd.getColumnCount(); col ++) {
    result.put(rsmd.getColumnLabel(col)+pId, resultSet.getString(col)); }
    pId ++;
    }
    //print all results in col
    for (int i=0; i<pId;i++)
    System.out.println("EID: "+result.get("EID"+i));

    //problem
    for (int i=0; i<pId;i++)
    if (result.get("EID1").startsWith("8")){
    if result.get("CID1").startsWith("M") {
    System.out.println ("true");
    }
    }

A: You should be using your database to do searching. So search for the failure criteria and then if there are no results, then print "true".
The below is a example based on some data assumptions that searches for your 'fail' criteria.
select 1
FROM PSA.SECOND
WHERE T_DATE >'2202-10-10'
    AND CID LIKE 'M%'
    AND EID <= 800
LIMIT 1

The advantage is that with indexing on CID,EID this can be a search that doesn't involve the entire dataset, and stops at the first failure.

A: Look at this loop:
for (int i=0; i<pId;i++)
    System.out.println("EID: "+result.get("EID"+i));

Each key value takes the form EID1, EID2 and so on.
In your second loop you do:
for (int i=0; i<pId;i++)
    if (result.get("EID1").startsWith("8")){
        if result.get("CID1").startsWith("M") {
            System.out.println ("true");
        }
    }

You are using EID1 every time.
You need to change your loop to:
for (int i=0; i<pId;i++)
    if (result.get("EID" + i).startsWith("8")){
        if result.get("CID" + i).startsWith("M") {
            System.out.println ("true");
        }
    }

exactly as you are doing in your first loop.


text:
Q: How is zig zag scan carried out in sampled components in JPEG? A data block is 8x8 in JPEG. We zig zag scan it and then encode it using run length and huffman coding.
If a component is subsampled, that means some of the samples are going to be ignored. Does that mean that the zigzag scan is done on a 4x4, or 2x2 block? Or even 8x4 or 4x2 block?

A: The next level of the Minimum Coded Unit (MCU). An MCU consists of 8x8 blocks. If you subsample components, you increase the size of the MCU and don't reduce the 8x8 block.


text:
Q: how to send content from viewmodel to new page I have a pivot like this
<PivotItem Header="Product">
    <GridView ItemsSource="{x:Bind ProductViewModel.Products}">
        <GridView.ItemTemplate>
            <DataTemplate x:DataType="models:Product">
                <StackPanel FlyoutBase.AttachedFlyout="{StaticResource FlayoutBase1}" RightTapped="StackPanel_RightTapped">
                    <TextBlock Text="{x:Bind Name, Mode=OneWay}"/>
                    <TextBlock Text="{x:Bind Price, Mode=OneWay}"/>
                </StackPanel>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</PivotItem>

I also have a flyout in every Product with a button and when I press it I want to send the values for Name and Price to a new page for the order of that product.
I don't know how to do it because they have different ViewModels and the fields are not the same.

A: While navigating you can send parameters.
Check this for reference.
http://www.geekchamp.com/tips/how-to-pass-data-between-pages-in-windows-phone-alternatives


text:
Q: Append a dictionary into a list in Dynamodb I am using DynamoDB for my Lambda function and to update any item I am using this function ,
def update_title(title, val, dynamodb=None):
    if not dynamodb:
        dynamodb = boto3.resource('dynamodb')

    table = dynamodb.Table('variable')

    try:
        response = table.update_item(
        Key={'var_name': title},
        UpdateExpression="set var_value=:p",
        ExpressionAttributeValues={':p': val},
        ReturnValues="UPDATED_NEW"
        )
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        return response['Attributes']

I want to append a dictionary into a item(list) without requesting the whole item from the server. Is there any way to do ???

A: This modified function with list_apend works for me.
def update_list_title(title, val, dynamodb=None):
if not dynamodb:
    dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('coindcx_variable')

try:
    response = table.update_item(
    Key={'var_name': title},
    UpdateExpression="set var_value=list_append(var_value, :p)",
    ExpressionAttributeValues={':p': val},
    ReturnValues="UPDATED_NEW"
    )
except ClientError as e:
    print(e.response['Error']['Message'])
else:
    return response['Attributes']


text:
Q: facebook open graph ios post button is disabled, content fades off I'm trying to share some stuff through my ios app, everything was working ok and was able to post using open graph api, however, now whenever I tap share and I'm taken to the fb app to compose the post, first the content is there and the navbar is blue, then the navbar turns white, and the preview of the post below the "say something about this..." textfield vanishes, and the "post" button at the top right corner of the screen is disabled.
Has anyone encountered a similar issue?
Thanks in advance

A: Are you using any form of source control? It might be a good idea to restore your earlier code as it sounds like you've broken something in the facebook share code. Re-trace your steps and try to figure out what you changed that's causing this strange behavior.


text:
Q: How to add external css and scss with bootstrap 4 in vue js 3 application? I need suggestion. I am using vue 3 rignt now. I want to convert my current web into vue application. I am using scss in my current file and I have main.css and main.scss folder.
The directory structures are below:
mian.css folder:
bootstrap.min.css
font.css
responsive.css
stye.css
main.scss folder:
_responsive.scss
style.scss

I am here very confused how to add scss and css globally along with boostrap4 in my vue app. Can anyone give me suggestions. I have checked lots of question stackoverflow but I did not able to get any point.

A: For example, you can store your css files within the src / assets folders. Then you can  import these files in the main.js file.
like below;
import "./assets/main.css"


text:
Q: Private inheritance along class hierarchy, why friend is needed all along the hierarchy Consider the following code:
#include <iostream>

class A{
    friend class C;
    int a{42};
};

class B: private A{
    friend class C;
};

class C: private B {
public:
    void print() {std::cout << a << '\n';}
};

int main() {
    C c;
    c.print();
}

According to this answer, the member variable A::a is "present" in all classes, but its visibility differ, i.e. is not visible in B or C unless we make B or C a friend of A. My question is why do I need to make C a friend of both A and B? I would've though the friend declaration in A would suffice. If I remove the friend class C; declaration from either A or B, the code fails to compile.

A:
My question is why do I need to make C a friend of both A and B?

Without B declaring C has a friend, C wouldn't see B as inheriting A. Even though C would see A::a, it would not see B::a.
Indeed:

*

*C inherits B, so anything public in B is accessible from C.

*But B inherits privately from A. C being a friend of B makes C see this inheritance.

*The access of A::a is private, so even though C sees A as its ancestor, it needs to be a friend of A to see A::a.


text:
Q: OSGI Bundle with Android I have been trying to get apache felix upnp stack working on androd using OSGI framework. I got a DMR up and running over a test OSGI framework ( knopplerfish ). However, I am unable to figure out how to make the DMR OSGI bundle working and can be activated on android.
What I need is not a source code or something else. I need a pro look to my issue. I mean what programming structure do I need to use to let bundle interact with android components ?
An interface between them ? if so what should be my way of use it ?


text:
Q: 'Direction' Pronunciation There are two ways to pronounce the word 'direction'.
dɪˈrɛkʃ(ə)n and dʌɪˈrɛkʃ(ə)n
Is one American and one British? If yes, please confirm which is which.
If not, what's the difference in usage?


text:
Q: Fastlane iOS tests pass locally but not from Jenkins I have some trouble with Fastlane execution on Jenkins.
Locally it works, build succeed and tests run.
But from Jenkins and github, the build don't succeed.
I think it's because of this line :
PhaseScriptExecution Run\ Script /Users/Shared/Jenkins/Library/Developer/Xcode/DerivedData/MyProject-bljizzbrhfznjpgjucmtarcsjmyw/Build/Intermediates.noindex/MyProject.build/Debug-iphonesimulator/Core.build/Script-FC957A9020120D68000F4790.sh

But not focus on that, I'm not sure that's it.
Here the Fastfile :
default_platform(:ios)

platform :ios do
desc "Launch Middleware tests"
lane :tests do
  run_tests(workspace: "MyProject.xcworkspace",
            clean: true,
            devices: ["iPhone 8"],
            scheme: "Middleware",
            slack_url: "https://hooks.slack.com/services/...",
            slack_channel: "#myChannel")
  end
end

Some environment variables set

The Build action :

The jenkins error

The command created by fastfile and executed by Jenkins

A: I found the answer, it appears that is that script : Script-FC957A9020120D68000F4790.sh, I was using sourcery before Swift 4.
${PODS_ROOT}/Sourcery/bin/sourcery --sources ${PROJECT_DIR}/Core --templates ${PROJECT_DIR}/Sourcery/Core/Templates --output ${PROJECT_DIR}/Core/Sourcery/

Jenkins was not able to find PODS_ROOT and PROJECT_DIR environment variables. I don't use sourcery anymore so, I commented that script but if you still use it, I think you can add environment variables to jenkins configuration


text:
Q: How to change Redactor image upload file name? I have question and answer site and I use redactor
But since I want to monitor uploaded image base on the subject and date.
how can I change imagename of redactor uploaded images?
$subject is my variable name of title of topic and
use this code
<?php
$dir = '/sitecom/images/';

$_FILES['file']['type'] = strtolower($_FILES['file']['type']);

if ($_FILES['file']['type'] == 'image/png'
|| $_FILES['file']['type'] == 'image/jpg'
|| $_FILES['file']['type'] == 'image/gif'
|| $_FILES['file']['type'] == 'image/jpeg'
|| $_FILES['file']['type'] == 'image/pjpeg')
{
// setting file's mysterious name
$filename = $subject.md5(date('YmdHis')).'.jpg';
$file = $dir.$filename;

// copying
copy($_FILES['file']['tmp_name'], $file);

// displaying file
$array = array(
    'filelink' => $sysUrl.'/assets/uploads/r/'.$filename
);

echo stripslashes(json_encode($array));

}

?>


text:
Q: ngx-loading Toggling from another component I'm using ngx-loading and want to be able to trigger it's showing/hiding from children components. Here is what I currently have:
App.Component
import { Component, Injectable } from '@angular/core';

@Injectable()
export class AppComponent implements OnInit{
  public loading = false;

  constructor() { }

  loader() {
    this.loading = !this.loading;
    console.log(this.loading);
  }
}

Child Component
import { AppComponent} from '../app/app-component';
import { MyService } from '../service/my-service';

@Component({
  selector:'child-component',
  templateUrl: './child.component.html',
  providers: [AppComponent, MyService]
})

export class ChildComponent implments OnInit {
  constructor(private loader: AppComponent, private service: MyService) {}

  ngOnInit(): void {
    this.getData();
  }

  getData() {
    this.loader.loader();
    this.service.getDataFromService().then(res => {
      this.myModel = res;
      this.loader.loader();
    }
  }
}

If I check my logs this.loader is toggle from true to false but the ngx-loading component isn't.  If I set the initial value of loading in app.component ngx-loading displays but wont hide. So I know that the loader is working.
Any ideas?

A: The reason is that change detection doesn't run. I have created a Plunker to make it work. I would recommend you to use EventEmmiter(Output). The main idea is after the promise is finished, you run setTimeout to trigger changeDetection.
this.getData().then(() => {
   setTimeout(() => {
      this.load.emit()
   })


text:
Q: Doesn't show the JOptionPane when a condition is met Im trying to make a Login Gui where it searches a text file for the password and username and if it doesn't find any that match the input then they display a JOptionPane but for some reason it never shows it. This is the code:
int determine=0;
try{
    String p1;
    String p2;
    String password =PasswordEntered.getText();
    String username =UsernameEntered.getText();
    FileReader reader=new FileReader("LoginPages.txt");
    FileReader read=new FileReader("LoginPages.txt");
    BufferedReader cr=new BufferedReader(read);
    BufferedReader br=new BufferedReader(reader);

    ArrayList<String> numbs = new ArrayList<String>();
    while (cr.readLine()!=null){
        numbs.add(br.readLine());
    }
    for (int i=0;i<=numbs.size();i=i+2){
        p1=numbs.get(i);
        p2=numbs.get(i+1);
        if(password.equals(p2)&&(username.equals(p1))) {
            determine=i;
            MainGUI x=new MainGUI();
            x.setVisible(true);
            dispose();
        }
    }
    if (determine==numbs.size()) {
        JOptionPane.showMessageDialog(this, "try again");
    }
} catch(IOException ex){
    JOptionPane.showMessageDialog(this, "File Not Found");
}

It was supposed to pop up saying "try again" but instead it doesn't do anything. Please help or explain anyone.

A: The file is found, otherwise a JOptionPane would have shown up. You can test that by renaming the file and running the code again.
After that, the condition to display a JOptionPane would be determine==numbs.size(), but determine is initialized to zero and only set on successful login to the index at which it was found. Even if the last entry (pair of user/password) were found, it would match with i=size-2, so the condition never applies.
Change your code into something like
boolean found = false;
for (int i=0;i<=numbs.size();i=i+2){
    p1=numbs.get(i);
    p2=numbs.get(i+1);
    if(password.equals(p2)&&(username.equals(p1))) {
        found = true;
        break;
    }
}
if (found) {
    MainGUI x=new MainGUI();
    x.setVisible(true);
    dispose();
} else {
    JOptionPane.showMessageDialog(this, "try again");
}


text:
Q: RESTful webservice in PHP .htaccess issue I built a simple RESTful webservice in PHP. I'm having trouble with the .htaccess though.
My primary file lies at http://example.com/webservice/api.php with different functions like login, search, deleteuser etc.. I can access the API as follows (with the verbs in the []):

*

*http://example.com/webservice/login/ --- [POST uname=bob&password=123]

*http://example.com/webservice/search?name=bob   --- [GET name=bob]

*http://example.com/webservice/deleteuser/  --- [DELETE id=2]

I want to add a rewrite rule so that I can access the search API as
 - http://example.com/webservice/search/name/bob
Here's my .htaccess file now:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ api.php?request=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ api.php [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>

A: Yout .htaccess file will convert the search URL
http://example.com/webservice/search/name/bob

into this:
http://example.com/api.php?request=/search/name/bob

So, when processing parameters in PHP you should "explode" the request parameter into an array of parameters, like this:
$params=array_explode("/",$_GET['request']);

This way, you would apply the same code that you used for the [GET name=bob] request, using $params[1] for "name" and $params[2] for the value ("bob", in this case). Of course, $params[0] contains the request action ("search", in this case).


text:
Q: Querying up tree for a particular value I'm a bit of a SQL novice, so I could definitely use some assistance hashing out the general design of a particular query. I'll be giving a SQL example of what I'm trying to do below. It may contain some syntax errors, and I do apologize for that- I'm just trying to get the design down before I go running and testing it!
Side note- I have 0 control over the design scheme, so redesign is not an option. My example tables may have an error due to oversight on my part, but the overall design scheme of bottom-up value searching will remain the same. I'm querying an existing database filled with tons of data already in it.
The scenario is this: There is a tree of elements. Each element has an ID and a parent ID (table layouts below). Parent ID is a recursive foreign key to itself. There is a second table that contains values. Each value has an elementID that is a foreign key to the element table. So to get the value of a particular variable for a particular element, you must join the two tables.
The variable hierarchy goes Bottom-Up by way of inheritance. If you have an element and want to get its variable value, you first look at that element. If it doesn't have a value, then check the element's parent. If that doesn't check the parent's parent- all the way to the top. Every variable is guaranteed to have a value by the time you reach the top! (if I search for variableID 21- I know that 21 will exist. If not at the bottom, then definitely at the top) The lowest element on the tree gets priority, though- if the bottom element has a value for that variable, don't go any farther up!
The tables would look roughly like this:
Element_Table
--------------
elementID (PK)
ParentID (FK to elementID)

Value_Table
--------------
valueID (PK)
variableID
value (the value that we're looking for)
elementID (FK to Element_Table.elementID)

So, what I'm looking to do is create a function that cleanly (key word here. Nice, clean and efficient code) search, bottom-up, across the tree looking for a variable value. Once I find it- return that value and move on!
Here is an example of what I'm thinking:
CREATE FUNCTION FindValueInTreeBottomUp
(@variableID int, @element varchar(50))
RETURNS varchar(50)
AS
BEGIN
DECLARE @result varchar(50)
DECLARE @ID int
DECLARE @parentID int

SET @result = NULL, @ID = @element
WHILE (@result IS NULL)
    BEGIN
       SELECT @result = vals.value, @parentID = eles.ParentID
       FROM Value_Table vals
       JOIN Element_Table eles
       ON vals.elementID = eles.elementID
  WHERE eles.elementID = @ID AND vals.variableID = @variableID
  IF(@result IS NULL)
      @ID = @parentID
      CONTINUE
  ELSE
      BREAK
END

RETURN @result
END

Again, I apologize if there are any syntactical errors. Still a SQL novice and haven't run this yet! I'm especially a novice at functions- I can query all day, but functions/sprocs are still rather new to me.
So, SQL gurus out there- can you think of a better way to do this? The design of the tables won't be changing; I have NO control over that. All I can do is produce the query to check the already existing design.

A: I think you could do something like this (it's untested, have to try it in sql fiddle):
;with cte1 as (
    select e.elementID, e.parentID, v.value
    from Element_Table as e
        left outer join Value_Table as v on e.elementID = e.elementID and v.variableID = @variableID
), cte2 as (
    select v.value, v.parentID, 1 as aDepth
    from cte1 as v
    where v.elementID = @elementID
    union all
    select v.value, v.parentID, c.aDepth + 1
    from cte2 as c
    inner join cte1 as v on v.elementID = c.ParentID
    where c.value is null
)
select top 1 value
from cte2
where value is not null
order by aDepth

test infrastructure:
declare @Elements table (ElementID int, ParentID int)
declare @Values table (VariableID int, ElementID int, Value nvarchar(128))
declare @variableID int, @elementID int

select @variableID = 1, @elementID = 2

insert into @Elements
select 1, null union all
select 2, 1

insert into @Values
select 1, 1, 'test'

;with cte1 as (
    select e.elementID, e.parentID, v.value
    from @Elements as e
        left outer join @Values as v on e.elementID = e.elementID and v.variableID = @variableID
), cte2 as (
    select v.value, v.parentID, 1 as aDepth
    from cte1 as v
    where v.elementID = @elementID
    union all
    select v.value, v.parentID, c.aDepth + 1
    from cte2 as c
        inner join cte1 as v on v.elementID = c.ParentID
    where c.value is null
)
select top 1 value
from cte2
where value is not null
order by aDepth


text:
Q: Session not persisting on bare IP address website 111.222.333.444:5566 The same PHP script I'm using works fine with sessions on a domain website like example.com but not so when it's uploaded and accessed on a bare IP address website with an arbitrary HTTP port number like this:
111.222.333.444:5566
Variables can be set in $_SESSION which is accessible in the same PHP request but they are gone with the next page load.
Tried this:
session_set_cookie_params(
    0,
    '/',
    '111.222.333.444:5566'
);

session_start();

But it's not working. Also checked phpinfo() and the bare IP site's session is enabled. My browser does support cookie when both of the tests are run.
This is weird. What could be wrong here? Is PHP session meant to not persist on bare IP site with exotic HTTP port?

A: One of the requirements for cookies is:

The string is a host name (i.e., not an IP address).

You can't associate a cookie with an IP address, only with a hostname.
PHP sessions depend on session cookies to work.


text:
Q: Website is down and unable to login via SSH / Putty on Ubuntu 14.04 x64 Digitalocean I have a Magento website on degitalocean.com and I am unable to login via SSH or SFTP. Almost every alternate day I'm facing this problem and I have to restart my droplet via digitalocean account to make website working. Few days ago it was giving MYSQL connectivity error which i resolved by increasing droplet RAM to 2GB and by creating SWAP file.
Can anyone please suggest solution for this issue? Also let me know if you want to see any code files.

I have added few lines from error.log please see if this can be help
 150808 10:18:38 [Note] Plugin 'FEDERATED' is disabled.
 150808 10:18:38 InnoDB: The InnoDB memory heap is disabled
 150808 10:18:38 InnoDB: Mutexes and rw_locks use GCC atomic builtins
 150808 10:18:38 InnoDB: Compressed tables use zlib 1.2.8
 150808 10:18:38 InnoDB: Using Linux native AIO
 150808 10:18:38 InnoDB: Initializing buffer pool, size = 128.0M
150808 10:18:38 InnoDB: Completed initialization of buffer pool
150808 10:18:47 InnoDB: highest supported file format is Barracuda.
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!
150808 10:18:47  InnoDB: Database was not shut down normally!
InnoDB: Starting crash recovery.
InnoDB: Reading tablespace information from the .ibd files...
InnoDB: Restoring possible half-written data pages from the doublewrite
InnoDB: buffer...
150808 10:18:49  InnoDB: Waiting for the background threads to start
150808 10:18:50 InnoDB: 5.5.38 started; log sequence number 976719446
150808 10:18:50 [Note] Server hostname (bind-address): '178.**.42.108'; port: 3306
150808 10:18:50 [Note]   - '178.**.42.108' resolves to '178.**.42.108';
150808 10:18:50 [Note] Server socket created on IP: '178.**.42.108'.
150808 10:19:01 [Note] Event Scheduler: Loaded 0 events
150808 10:19:01 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.5.38-0ubuntu0.14.04.1'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  (Ubuntu)
150808 10:21:00 [Warning] IP address '221.211.62.106' could not be resolved: Name or service not known
150808 11:17:09 [Warning] IP address '115.238.245.12' could not be resolved: Name or service not known

My.cnf
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port        = 3306
socket      = /var/run/mysqld/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#
user        = mysql
performance_schema             = off
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address        = 127.0.0.1
#
# * Fine Tuning
#
key_buffer      = 32M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover-options  = BACKUP
#max_connections        = 100
#table_cache            = 128
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit   = 1M
query_cache_size        = 32M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
#log_slow_queries   = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id      = 1
#log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size         = 100M
#binlog_do_db       = include_database_name
#binlog_ignore_db   = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem

[mysqldump]
quick
quote-names
max_allowed_packet  = 256M

[mysql]
#no-auto-rehash # faster start of mysql but no tab completition
socket      = /var/run/mysqld/mysqld.sock

[isamchk]
key_buffer      = 256M

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/

A: Digital Ocean provides console access from the control panel. Use that to login when the system is down and gather information, When you have information use it to decide what to do. Anything else is guessing and with the information you have provided I guess Perseid Meteor shower.

Being structured and methodical in your approach is much better than flapping around wildly.
Personally I find Scientific Method (others call it something different) a wonderful tool to pull out of the system administration kitbag when diagnosing problems.

*

*What is the actual problem you're trying to solve ?

A service stops responding.

*So, now we know what the actual problem is we're solving we have some direction. Let's gather some information to help us figure out a solution.

*

*Is the problem time related? Does it happen regularly or randomly.

*Check your logs, all of them, not just the particular services's logs as something else may be causing the problem. Log entries generally have timestamps, this is to help you correlate events across multiple applications and services - use them.  If necessary increase the log verbosity too.

*Watch what your system is doing. Use tools like top, vmstat, iostat, sar, ps,tcpdump or even full blown monitoring systems.

*Analyse the information you have gathered. What is actually happening on the system when the service stops responding? What is the state of the system's resources ?

*Take appropriate action to remediate. Hopefully it's pretty obvious what's going on, you're running out of memory and OOM killer comes out to play, your swap activity is too high, your run queue is too long, you're iobound etc. If it's not obvious then you're probably not gathering the correct data - you know what to do, go back to 2.

*Monitor what the changes introduced at 4. do.

*Did the changes fix the problem ? Is it better? Is it worse ? Is there no difference ? Where you go from here depends on what you find. You may need to go back to 2. and gather more pertinent data or 3. to reanalyse what data you have or 4. because you identified a number of potential solutions.

*Document your findings and the changes you made.

*Go back to bed/home from work/to the pub.

A: I agree with the above. Take a methodical approach to troubleshooting this, flapping wildly doesn't usually help.
It would seem like the SSH daemon is stopping so get onto the box with console access through your hosts control panel (If they don't provide console access, then move host) and restart the service. Now get going through the logs, monitor system performance with tools such as top or iotop and try to figure out what happens to the box right before SSH dies.
Its important you document any changes you made and what you ultimately did to fix it.
Tom


text:
Q: Is there any method to hide or remove checkout step 3,4,5 in opencart I am developing a simple website in opencart and I need to remove a different step on checkout. Customer can simply checkout and fill account information to confirm checkout or direct checkout after.
Modify on checkout.php :
 $.ajax({
                    url: 'index.php?route=checkout/payment_method',
                    dataType: 'html',
                    success: function(html) {
                        $('#collapse-payment-method .panel-body').html(html);

                        $('#collapse-payment-method').parent().find('.panel-heading .panel-title').html('<?php echo $text_checkout_payment_method; ?> ');

                        $('a[href=\'#collapse-payment-method\']').trigger('click');
                        $('#button-payment-method').trigger('click');
                        $('#collapse-checkout-confirm').parent().find('.panel-heading .panel-title').html('<?php echo $text_checkout_confirm; ?>');
                        //$('a[href=\'#collapse-checkout-confirm\']').trigger('click');
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                    }
                });

It works, but how can I solve it in a better way?


text:
Q: How to drop entire row if string of one column contains the word from another column in pandas dataframe Dataframe contain columns called "product_description" and "manufacturer". I need to remove all rows where 'product_description' has 'manufacturer' in it.
I tried this code:
df[~df.product_description.str.contains(df.manufacturer)]

and it gave me error
TypeError: 'Series' objects are mutable, thus they cannot be hashed

Is there any other way to do it?
Very much appreciate for any help!

A: If need test all values from column manufacturer per each value of column product_description use join with | for regex or:
df[~df.product_description.str.contains('|'.join(data.manufacturer))]

Or if need test per rows:
df[df.apply(lambda x: x.product_description not in x.manufacturer, axis=1)]


text:
Q: Forwarding message to syslog server There are various network devices that would like to send syslog messages to Syslog-NG server, listening at port 514.
Below is the architecture for client-server communication.

Is the device suppose to install Syslog-NG client to forward the message to Syslog-NG server?
What does it take for a device(client) to send message to Syslog-NG server?

A: syslog-ng can receive and parse messages from a lot of different sources and formats. You can install syslog-ng on the clients, but it is not mandatory. If the device has a logging application installed that can send standard syslog messages (RFC3164 or RFC5424), that's enough. Most networking devices and Linux/UNIX servers have such applications installed by default.


text:
Q: Creating Vector in R (multiple conditions) Need to create and print a vector in R that includes the following in this order:

*

*A sequence of integers from 6 to 10 (inclusive)

*A twofold repetition of the vector c(2, -5.1, -33)

*The value of the sum of 7/42 and 2

a) Then extract the first and last elements of the vector to form another vector
b) Form a third vector from the elements not extracted above
* Use the vectors from (a) and (b) to reconstruct and print the original first vector

A: That should do it:

a.vec<-c(seq(6,10,1),rep(c(2,-5.1,-33),times=2),(7/42+2))
b.vec<-a.vec[c(1,length(a.vec))]
c.vec<-a.vec[-c(1,length(a.vec))]
a.vec<-c(b.vec[1],c.vec,b.vec[2])


text:
Q: In Excel, is there a shortcut to hide a wide range of columns without mouse-dragging? I have a spreadsheet I frequently use , where I always want to hide the D:CE columns  . And since that's over 40 columns, I was wondering if there was a keyboard shortcut or command to hide this more quickly than the old shift + ctrl + click
thanks for any tips/guidance

A: Try the following:
Ctrl + G (open the Go To menu)
D:CE then Enter (select your range)
Ctrl + 0 (hide the selected columns)

A: If you know the columns you want to hide, you can simply type the address of the range in the Name Box and press Enter. Once it's selected, you can then right click the a column header in the selected range and choose Hide.
This is the Name Box.

Type D:CE in the Name Box and press Enter to select that range. Then right click a column header in the selected range and choose Hide.

A: If this is just 1 specific spreadsheet, then you could select the columns (once), then go to "Data" > "Group".
Once grouped, there will be a line (showing which columns are grouped) with a - which you can click to hide the entire group.  Once hidden, the button will change to +, which will unhide the entire group.
There will also be 1 (hide all groups) and 2 (unhide 1st-level groups) buttons.  You can even have groups within groups, which will create 2nd or 3rd level groups (adding 3 and 4 to the control scheme)

Once you save the file, groups will remain intact if you reopen it or send it to a colleague.
Shift + Alt + → is the shortcut to Group selected Rows / Columns, Shift + Alt + ← to Ungroup
If you have a cell in a Group selected, then Alt, A, H will hide it, and Alt, A, J will unhide it.  Alt, A, U, C will remove all Outline Groups

A: Another option you could use would be to have a Macro which hides/unhides the columns and assign this to a key combination of your choice.  -  The below Macro will hide columns D:CE if they are visible and make them visible if they are hidden. Assign this to something like Ctrl+Shift+Z And you can hide/unhide the columns with ease.
Sub column_hide()

If ActiveSheet.Columns("D:CE").EntireColumn.Hidden Then
    ActiveSheet.Columns("D:CE").EntireColumn.Hidden = False
Else
    ActiveSheet.Columns("D:CE").EntireColumn.Hidden = True
End If

End Sub


text:
Q: How to do SQL injection on Oracle I'm doing an audit of a system, which the developers insist is SQL injection proof.  This they achieve by stripping out the single-quotes in the login form - but the code behind is not parameterized; it's still using literal SQL like so:
username = username.Replace("'", "");
var sql = "select * from user where username = '" + username + "'";

Is this really secure?  Is there another way of inserting a single quote, perhaps by using an escape character?  The DB in use is Oracle 10g.

A: Maybe you can also fail them because not using bind variables will have a very negative impact on performance.

A: A few tips:
1- It is not necessarily the ' character that can be used as a quote. Try this:
select q'#Oracle's quote operator#' from dual;

2- Another tip from "Innocent Code" book says: Don't massage invalid input to make it valid (by escaping or removing). Read the relevant section of the book for some very interesting examples. Summary of rules are here.

A: Have a look at the testing guide here: http://www.owasp.org/index.php/Main_Page  That should give you more devious test scenarios, perhaps enough to prompt a reassessment of the SQL coding strategy :-)

A: No, it is not secure. SQL injection doesn't require a single-quote character to succeed. You can use AND, OR, JOIN, etc to make it happen. For example, suppose a web application having a URL like this: http://www.example.com/news.php?id=100.
You can do many things if the ID parameter is not properly validated. For example, if its type is not checked, you could simply use this: ?id=100 AND INSERT INTO NEWS (id, ...) VALUES (...). The same is valid for JOIN, etc. I won't teach how to explore it because not all readers have good intentions like you appear to have. So, for those planning to use a simple REPLACE, be aware that this WILL NOT prevent an attack.

A: So, no one can have a name like O'Brian in their system?
The single quote check won't help if the parameter is numeric - then 1; DROP TABLE user;-- would cause some trouble =)
I wonder how they handle dates...
If the mechanism for executing queries got smart like PHP, and limited queries to only ever run one query, then there shouldn't be an issue with injection attacks...

A: What is the client language ? That is, we'd have to be sure exactly what datatype of username is and what the Replace method does in regard to that datatype. Also how the actual concatenation works for that datatype. There may be some character set translation that would translate some quote-like character in UTF-8 to a "regular" quote.
For the very simple example you show it should just work, but the performance will be awful (as per Thilo's comment). You'd need to look at the options for cursor_sharing
For this SQL
select * from user where username = '[blah]'

As long as [blah] didn't include a single quote, it should be interpreted as single CHAR value. If the string was more than 4000 bytes, it would raise an error and I'd be interested to see how that was handled. Similarly an empty string or one consisting solely of single quotes. Control characters (end-of-file, for example) might also give it some issues but that might depend on whether they can be entered at the front-end.
For a username, it would be legitimate to limit the characterset to alphanumerics, and possibly a limited set of punctuation (dot and underscore perhaps). So if you did take a character filtering approach, I'd prefer to see a whitelist of acceptable characters rather than blacklisting single quotes, control characters etc.
In summary, as a general approach it is poor security, and negatively impacts performance. In particular cases, it might (probably?) won't expose any vulnerabilities. But you'd want to do a LOT of testing to be sure it doesn't.


text:
Q: Spark createDataFrame(df.rdd, df.schema) vs checkPoint for breaking lineage I'm currently using
val df=longLineageCalculation(....)
val newDf=sparkSession.createDataFrame(df.rdd, df.schema)
newDf.join......

In order to save time when calculating plans, however docs say that checkpointing is the suggested way to "cut" lineage. BUT I don't want to pay the price of saving the RDD to disk.
My process is a batch process which is not-so-long and can be restarted without issues, so checkpointing is not benefit for me (I think).
What are the problems which can arise using "my" method? (Docs suggests checkpointing, which is more expensive, instead of this one for breaking lineages and I would like to know the reason)
Only think I can guess is that if some node fails after my "lineage breaking" maybe my process will fail while the checkpointed one would have worked correctly? (what If the DF is cached instead of checkpointed?)
Thanks!
EDIT:

From SMaZ answer, my own knowledge and the article which he provided. Using createDataframe (which is a Dev-API, so use at "my"/your own risk) will keep the lineage in memory (not a problem for me since I don't have memory problems and the lineage is not big).
With this, it looks (not tested 100%) that Spark should be able to rebuild whatever is needed if it fails.
As I'm not using the data in the following executions, I'll go with
cache+createDataframe versus checkpointing (which If i'm not wrong, is
actually cache+saveToHDFS+"createDataFrame").
My process is not that critical (if it crashes) since an user will be always expecting the result and they launch it manually, so if it gives problems, they can relaunch (+Spark will relaunch it) or call me, so I can take some risk anyways, but I'm 99% sure there's no risk :)

A: Let me start with creating dataframe with below line :

val newDf=sparkSession.createDataFrame(df.rdd, df.schema)

If we take close look into SparkSession class then this method is annotated with @DeveloperApi. To understand what this annotation means please take a look into below lines from DeveloperApi class

A lower-level, unstable API intended for developers.
Developer API's might change or be removed in minor versions of Spark.

So it is not advised to use this method for production solutions, called as Use at your own risk implementation in open source world.
However, Let's dig deeper what happens when we call createDataframe from RDD. It is calling the internalCreateDataFrame private method and creating LogicalRDD.
LogicalRDD is created when:

*

*Dataset is requested to checkpoint

*SparkSession is requested to create a DataFrame from an RDD of internal binary rows

So it is nothing but the same as checkpoint operation without saving the dataset physically. It is just creating DataFrame From RDD Of Internal Binary Rows and Schema. This might truncate the lineage in memory but not at the Physical level.
So I believe it's just the overhead of creating another RDDs and can not be used as a replacement of checkpoint.
Now, Checkpoint is the process of truncating lineage graph and saving it to a reliable distributed/local file system.
Why checkpoint?

*

*If computation takes a long time or lineage is too long or Depends too many RDDs

*Keeping heavy lineage information comes with the cost of memory.

*The checkpoint file will not be deleted automatically even after the Spark application terminated so we can use it for some other process

What are the problems which can arise using "my" method? (Docs
  suggests checkpointing, which is more expensive, instead of this one
  for breaking lineages and I would like to know the reason)

This article will give detail information on cache and checkpoint. IIUC, your question is more on where we should use the checkpoint. let's discuss some practical scenarios where checkpointing is helpful

*

*Let's take a scenario where we have one dataset on which we want to perform 100 iterative operations and each iteration takes the last iteration result as input(Spark MLlib use cases). Now during this iterative process lineage is going to grow over the period. Here checkpointing dataset at a regular interval(let say every 10 iterations) will assure that in case of any failure we can start the process from last failure point.

*Let's take some batch example. Imagine we have a batch which is creating one master dataset with heavy lineage or complex computations. Now after some regular intervals, we are getting some data which should use earlier calculated master dataset. Here if we checkpoint our master dataset then it can be reused for all subsequent processes from different sparkSession.

My process is a batch process which is not-so-long and can be
  restarted without issues, so checkpointing is not benefit for me (I
  think).

That's correct, If your process is not heavy-computation/Big-lineage then there is no point of checkpointing. Thumb rule is if your dataset is not used multiple time and can be re-build faster than the time is taken and resources used for checkpoint/cache then we should avoid it. It will give more resources to your process.

A: I think the sparkSession.createDataFrame(df.rdd, df.schema) will impact the fault tolerance property of spark.
But the checkpoint() will save the RDD in hdfs or s3 and hence if failure occurs, it will recover from the last checkpoint data.
And in case of createDataFrame(), it just breaks the lineage graph.


text:
Q: detecting client OS using Applet I need to detect client side OS version and whether it's 32 bit/64 bit (Windows XP (32-bit) / Mac OS X 10.3.x  / Linux OpenSUSE 11.2  etc.) using Applet.
I will have to load the applet automatically when the JSP will be loaded and it will show all the correct information regarding user's OS.
Please help me.

A: You can use java.lang.System to get basic information about the system your code is running on. Not sure if you want something more detailed than that.
System.out.println(System.getProperty("os.name"));
System.out.println(System.getProperty("os.arch"));
System.out.println(System.getProperty("os.version"));

Properties available via java.lang.System.getProperties() are listed here.
Edit:
The system properties for os.name, os.arch and os.version are not garaunteed to give you useful information. It depends highly on the platform and JVM you are using. If you want an analogy you can think of it as being roughly as useful as the user agent property property sent in HTTP requests (so, barely useful). There are some third party tools you can use for getting better system information, but you will have to sign your applet in order to get them to work, as they require permissions on the system that fall outside the Applet Security Sandbox. For example, SIGAR by HyperInc which was mentioned on this SO post.
Finally, to get your Applet to load on your page you need to include it on the page using applet tags. Heres an example:

Some more examples of applet tags are shown on Oracle's site.
Hope this helps.

A: You'll probably have as much luck parsing the User-Agent http header. You can either pass them to the applet using JavaScript or have the applet directly read them.


text:
Q: FUSE (Bazil-Go): how to implement MkDir request? I am trying to implement the function mkdir in a fuse, written in Go,and I'm using Bazil library. I have successfully implemented a simple read-only fs, and I now want to be able to call mkdir inside any existing directory to make a new one.
I have made sure that all the existing directories are writable,(attr.Mode = os.ModeDir | 0777).
Right now I have just added the function:
func (d Dir) MkDir(ctx context.Context, req *fuse.MkdirRequest) (fs.Node, error) {
    dir := &Dir{name: req.Name, files: 0, inode: 10 /*a random inode*/,mode: os.FileMode(0777),nextdir: nil, nextfile: nil}
    d.nextdir = dir
    return dir, nil
}

in my own implementation of the hello fs example of Bazil's library. But that doesn't seem to make any difference.
When I call mkdir new_dir_name from the terminal,  I get the error: "mkdir: cannot create directory 'new_dir_name': Operation not permitted", even though I have added the mkdir function.
Any insights as to why this is happening, and what else should I add to my code to make this working would be great. Also, this is my first stackoverflow question, so I'm sorry if I didn't ask in a clear way.

A: the correct function for make directory like this
func (d *Dir) Mkdir(ctx context.Context, req *fuse.MkdirRequest) (fs.Node, error) {

}


text:
Q: How do I install pywebkitgtk on Windows? How do you install pywebkitgtk on Windows? (Windows 7)
I've seen the answer to this question: Python + webkit + gtk on windows
But it refers to a binary that is out of date.


text:
Q: Why is Flask not printing german umlauts? I have a problem regarding the german umlauts when trying to print a shopping list from alexa with flask.
The code I use is:
#!flask/bin/python
#IMPORT THE FLASK AND PRINTER LIBRARIES
from flask import Flask, request
from escpos.printer import Usb
#ASSIGN VARIABLES FOR THE PRINTER AND FLASK
p = Usb(0x0416, 0x5011)
app = Flask(__name__)
#CREATE 'INDEX' PAGE
@app.route('/')
def index():
    return 'Your Flask server is working!'
#CREATE "PAGE" CALLED "LIST" FOR PRINTING ALEXA SHOPPING LIST
@app.route('/list')
def list():
    #CAPTURE "GET" DATA FROM IFTTT WEBOOKS
    content = request.get_data()
    #CONVERT RAW DATA TO STRING
    str_content = str(content)
    #DIVIDE DATA INTO SEPERATE LINES
    str_split = str_content.splitlines()
    #SEPERATE WORDS BY COMMA AND ADD TO A NEW LIST
    newlist = []
    for word in str_split:
        word = word.split(',')
        newlist.extend(word)
    #REMOVE FORMATTING MARKS
    rmv_marks = [s.strip("b'") for s in newlist]
    #PRINT HEADER
    #print("Shopping List\n")
    p.text("Shopping List:\n")
    #ENUMERATE AND PRINT EACH ITEM IN LIST
    r = 1
    for x in rmv_marks:
        #print(str(r) + ". " + x + "\n")
        p.text(str(r) + ". " + x + "\n")
        r += 1
    #RETURN RESULTS
    return 'x'
#RUN THE PROGRAM
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')`

It works but when the item on the list has an umlaut in it (e.g. Spülmittel), it always prints it like "4. Sp\xc3\xbclmittel"
I am completely new to this so i hope someone can help me.
Thank you very much!

A: Your content is bytes, not a string, and calling str() on it will convert it into a string, but stupidly based on the __repr__. Instead, call get_data differently:
content = request.get_data(as_text=True)

Now this will be a correctly decoded string already, you can then also get rid of your b'-stripping.


text:
Q: Open New Tab & Focus from Lightning Component in Console I currently have a LWC that is embedded within an Aura component. When a user clicks a button on the LWC it will convert a lead and return the new account id. The the Aura component is supposed to then close the lead tab (current tab) and open (then focus) on the new account tab. I have been able to make it so the lead tab closes and the account tab opens but it does not focus on the newly opened tab.
Here is the code for the Aura component:
    openTab: function(component, event, helper) {

        console.log('Opening Tab 2');
        component.set('v.recordId', event.getParam('value'));
        console.log('Record Id:' + component.get('v.recordId'));
        var recId = component.get('v.recordId');
        console.log(recId);

        var workspaceAPI = component.find("workspace");
        workspaceAPI.openTab({
            recordId: recId,
            focus: true
        }).then(function(response) {
            workspaceAPI.getTabInfo({
                  tabId: response
            }).then(function(tabInfo) {
            console.log("The url for this tab is: " + tabInfo.url);
            })
            .catch(function(error){
                console.log('oh no: ' + error);
            });
        })
        .catch(function(error) {
               console.log(error);
        });
        console.log('Tab Opened');
    }
})

When Logging, I see the record ids in console but do not see anything after the console.log(recId).
Any assistance that can be provided would be appreciated.
Thanks,