text:
Q: c# convert byte array of ascii values to integer array I have a byte array of 50 bytes representing 5 integers as ascii characters values. Every integer value is represented as 10 bytes:
byte[] receiveBytes = new byte[] {
  20, 20, 20, 20, 20, 20, 20, 20, 20, 49,  // 9 spaces then '1'
  20, 20, 20, 20, 20, 20, 20, 20, 20, 50,  // 9 spaces then '2'
  20, 20, 20, 20, 20, 20, 49, 50, 51, 52,  // 6 spaces then '1' '2' '3' '4'
  20, 20, 20, 20, 20, 20, 53, 56, 48, 49,  // 6 spaces then '5' '8' '0' '1'
  20, 20, 20, 20, 20, 20, 20, 57, 57, 57}; // 7 spaces then '9' '9' '9'

Please, notice that 20 is an ascii code of space and [48..57] are ascii codes of 0..9 digits.
How can I convert the byte array to an integer array (int[] intvalues == [1, 2, 1234, 5801, 999])?
I have tried first to convert byte array to string and then string to integer like this:
string[] asciival = new string[10];
int[] intvalues = new int[5];

Byte[] receiveBytes = '20202020202020202049  //int value = 1
                       20202020202020202050  //int value = 2
                       20202020202049505152  //int value = 1234
                       20202020202053564849  //int value =5801
                       20202020202020575757';//int value = 999

asciival[0] = Encoding.ASCII.GetString(receiveBytes, 0, 10);
asciival[1] = Encoding.ASCII.GetString(receiveBytes, 10, 10);

intvalues[0] = int.Parse(asciival[0]);
intvalues[1] = int.Parse(asciival[1]);

But isn't there a simpler way to copy the byte array into the string array?

A: A for loop can simplify the writing:
byte[] recv = new byte[]{ /* ... */ }

int[] intvalues = new int[recv.Length / 10];

for(int pos = 0; pos < recv.Length; pos += 10)
    intvalues[pos / 10] = int.Parse(Encoding.ASCII.GetString(recv, pos, pos + 10));

A: I suggest using Linq:

*

*Split initial array on 10-items (i.e. 10-byte) chunks

*Filter digits ('0'..'9' )  in each chunk

*Aggergate digits into a single integer

Implementation:
  using System.Linq;
  ...

  Byte[] receiveBytes = new byte[] {
    20, 20, 20, 20, 20, 20, 20, 20, 20, 49,  // 9 spaces then '1'
    20, 20, 20, 20, 20, 20, 20, 20, 20, 50,  // 9 spaces then '2'
    20, 20, 20, 20, 20, 20, 49, 50, 51, 52,  // 6 spaces then '1' '2' '3' '4'
    20, 20, 20, 20, 20, 20, 53, 56, 48, 49,  // 6 spaces then '5' '8' '0' '1'
    20, 20, 20, 20, 20, 20, 20, 57, 57, 57}; // 7 spaces then '9' '9' '9'

  int[] intvalues = Enumerable.Range(0, receiveBytes.Length / 10)
    .Select(index => receiveBytes
       .Skip(index * 10) // Skip + Take: splitting on 10-items chunks
       .Take(10)
       .Where(b => b >= '0' && b <= '9') // just digits
       .Aggregate(0, (s, a) => s * 10 + a - '0'))
    .ToArray();

Test
  Console.Write(string.Join(", ", intvalues));

Outcome:
  1, 2, 1234, 5801, 999

Please, notice, that 10 digits number can well overflow int since maximum int value (int.MaxValue) is 2147483647 only. To represent the initial byte[] as a string you can use Linq once again:
  var result = Enumerable
    .Range(0, receiveBytes.Length / 10)
    .Select(index => receiveBytes
       .Skip(index * 10) // Skip + Take: splitting on 10-items chunks
       .Take(10)
       .Select(b => b.ToString("00"))) // enforce leading "0" if necessary
    .Select(items => string.Concat(items));

  string text = string.Join(Environment.NewLine, result);

  Console.Write(text);

Outcome
20202020202020202049
20202020202020202050
20202020202049505152
20202020202053564849
20202020202020575757

A: You can try this :-
using System;
using System.Text;
class Example
{
  public static void Main()
  {
  // Define a string.
  String original = "ASCII Encoding";
 // Instantiate an ASCII encoding object.
   ASCIIEncoding ascii = new ASCIIEncoding();
// Create an ASCII byte array.
  Byte[] bytes = ascii.GetBytes(original);
// Display encoded bytes.
  Console.Write("Encoded bytes (in hex): ");
  foreach (var value in bytes)
    Console.Write("{0:X2} ", value);
    Console.WriteLine(); // Decode the bytes and display the resulting Unicode string.
    String decoded = ascii.GetString(bytes);
    Console.WriteLine("Decoded string: '{0}'", decoded);
  }
}


text:
Q: How can I access the attribute from the template? In this example i'm expecting it to say "hello world" but the world isn't picked up from the saying attribute.
(function () {
    'use strict';

    $(function () {
        // Set up a route that maps to the `filter` attribute
        can.route(':filter');

        // Render #app-template
        $('#app').html(can.view('appTemplate', {}));

        // Start the router
        can.route.ready();
    });

    can.Component.extend({
        tag: "say",
        scope: {
            saying: function(){
                return this.attr('saying')
            },
            greeting: 'salutations'
        },
        template: can.view("sayTemplate")
    });

})();

Templates:

A: You need to tell the component that you want to access the attributes plain value like this:
can.Component.extend({
  tag: "app-say",
  scope: {
    saying: '@',
    greeting: 'salutations'
  },
  template: can.view("sayTemplate")
});

See this Fiddle. What you eventually might want to do use an observable attribute from your application state instead of the plain string value. This might look like:
var appState = new can.Map({
    name: 'World'
});

$(function () {
    // Set up a route that maps to the `filter` attribute
    can.route(':filter');

    // Render #app-template
    $('#app').html(can.view('appTemplate', appState));

    // Start the router
    can.route.ready();
});

can.Component.extend({
    tag: "app-say",
    scope: {
        greeting: 'salutations'
    },
    template: can.view("sayTemplate")
});

And a template like:

This also creates a cross-bound input field that will update the name everywhere whenever you update the text field. Fiddle is here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UDP torrent trackers not replying I've finally gotten to the stage of getting a response from a UDP tracker.
Here's an exmaple, that I split into an array:

[ 1,   3765366842, 1908, 0, 2, 0 ]

Action, request ID, interval, leechers, seeders, peers.

No matter which torrent I chose, I get 1/2 seeders, which I'm assuming is the server tracking me, and no peers / leechers.
Am I not using the correct info hash?
This is how I retrieve it from a magnet link:
magnet:?xt=urn:btih:9f9165d9a281a9b8e782cd5176bbcc8256fd1871&dn=Ubuntu+16.04.1+LTS+Desktop+64-bit&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969

...

h = 9f9165d9a281a9b8e782cd5176bbcc8256fd1871

Now I split this into chunks of two, and parse them, for hex bytes:
bytes = [];
for (var i = 0; i < h.length; i++) bytes.push(parseInt((h[i]) + h[i++], 16));

[153, 153, 102, 221, 170, 136, 170, 187, 238, 136, 204, 85, 119, 187, 204, 136, 85, 255, 17, 119]

There's no need to encode this, so I send it along with my request.
This is the only point causing trouble, yet it seems so simple...
http://xbtt.sourceforge.net/udp_tracker_protocol.html

A: As the8472 says, your decoding is incorrect:
for (var i = 0; i < h.length; i++) bytes.push(parseInt((h[i]) + h[i++], 16));

i and i++ will have the same value here. (One of the reasons to avoid clever inline stuff.) You can use i and ++i, or maybe expand it all to multiple lines for readability:
for (var i = 0; i < h.length; i += 2) {
    var hex = h.substr(i, 2);
    bytes.push(parseInt(hex, 16));
}

And if you're using Node, just parse it into a Buffer, which can easily be converted to an array if necessary:
var bytes = Buffer.from(h, 'hex');

A:
9f91

should result in the first two bytes being 159, 145, so your hex-decoding is incorrect.
Beyond that you should compare your implementation with a working one through wireshark.

http://xbtt.sourceforge.net/udp_tracker_protocol.html

As was already mentioned in an answer to another question official and up-to-date specs reside at bittorrent.org, that includes the UDP tracker spec. The xbtt page is not maintained.


text: Q: C# form image transparency I am making a level editor for a platform game where the level is set up in a grid type display on a form. At the click of a button the form is supposed to add the image as a pictureBox of the player, an enemy, or whatever. I can successfully do this but when I add in the image on top of the grid my grid image completely disappears underneath it when I made my sprites(player, enemy, etc.) backgrounds transparent I still can't see the grid underneath. Can any one help me.


text:
Q: RUnnin a customized plan in Bamboo I often have to run a customized plan in Bamboo (the same one every time).  So I find the plan, do a run customized and change the environment variables and test file and do a run.  This is OK but it gets old.  Is there a way to save the customized plan so I can run it?  Or save the changes so when I run customize plan I can select that?

A: You can create plan branch and override variable for it


text:
Q: Libraries for obtaining usage data and connection speed for a specific period of time Am getting to do a project that consists of a cross-platform(windows, linux, mac) native desktop app that measures a user's data usage (in KB, MB, GB) and the link connection  speed(in kbps or mbps) for either wi-fi, ethernet or 3G modem connectivity options.
Am confortable with java, python, C++ in that order. Done some googling, but i wasn't satified. So am looking for any recommendations on libraries, frameworks in any of these languages that will enable me accomplish the above task.  Thanks alot.

A: The task can be split into two parts:

*

*Gathering the data and storing them somewhere.

*Presenting them to the user.

Often RRDtool (RRD = round-robin database) is used for both parts. It depends on your requirements, you could for example use RRDtool to gather the data you need and them use some Python or Java RRD library for displaying the results.
See also:

*

*Java RRD library

*rrd4j

*PyRRD


text:
Q: Вопросы по передаче параметров в Java Здравствуйте! Пересев с С# узнал, что в Java все параметры передаются по значению.
1) Ссылка ссылается на имеющийся объект, и если до передачи на него ссылалась одна ссылка, то теперь их две?
2) Создаётся новый объект в куче, и в пределах блока кода метода работаешь с новосозданным объектом. При этом после завершения работы метода, изначальный объект остаётся не изменённым? Созданный объект в методе уже стал на учёте у сборщика мусора?
Прочитав пару статей про передачу параметров в Java, решил поэкспериментировать.
Есть свой класс со строковым полем и двумя методами. Первый метод меняет поле объекта, а второй меняет значение скопированной ссылки.
Вот класс:
class MyClass {

String s;

public MyClass(String s) {
    this.s = s;
}

public static void changeField(MyClass other) {
    other.s = "**********";
}

public static void changeRef(MyClass other) {
    other = new MyClass("----------");
}

Однако почему-то, метод changeField изменяет объект, в то время как changeRef - нет.
    MyClass obj1 = new MyClass("1");
    MyClass obj2 = new MyClass("2");

    MyClass.changeField(obj1);
    MyClass.changeRef(obj2);

    System.out.println(obj1.s);
    System.out.println(obj2.s);

Вывод исполнения программы:
**************
2

A: Как вы сказали, в Java передаётся ссылка на объект(за исключением примитивных классов типа int, long and etc.) при этом, под эту ссылку выдается своя память.
В методе changeField происходит изменение самого объекта. И вы видите эти изменения за пределами функции.
В методе changeRef происходит создание нового экземпляра класса и ссылку на него записываете в ту область памяти которая была выделена для копии ссылки передаваемого объекта. Таким образом вы не меняете исходную ссылку и исходный объект.
И да, при передаче объекта в метод, создаётся дополнительная ссылка, т.е. их становится две, как вы написали в вашем вопросе.

A: В java нет передачи по ссылке в том смысле, что члены ссылочных типов вы менять можете, а вот сами ссылки, указывающие на экземпляры этих типов - нет.
В C# по сути все точно так же: тот же самый код, что вы написали, будет точно так же работать и там. При вызове changeField вы меняете поле экземпляра, но не сам экземпляр. А при вызове changeRef вы пытаетесь изменить саму ссылку, но ссылки остаются неизменными, так как в метод вы передаете только их копии.
Отличие между Java и C#  будет в том, что C# с помощью ключевых слов ref и out позволяет менять и сами ссылки на объекты. В java этого нет

A: Всетаки букварь по Java прочитать стоит. Все передается по значению. В java нет передачи по ссылке. Вот только MyClass obj1 = new MaClass("1") означает что в obj1 лежит не объект а ссылка на него. В тоже время long val = 1l означает что в val храниться 1, но Long val = new Long(1) - уже будет означать что val храниться ссылка на объект типа Long ( не путать с примитивным типом long)
Вот тут подробнее https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html
Т.е. разница между Reference types и Primitive Types


text:
Q: How to auto load textview on a list view and strikethrough some of the textview I am making a todo app. I made a shared preference to save the data to internal storage an an arryadapter to manage my data. Everything works well. I added a strikethrough functionality and it works, but when I exit and reopen the app the strikethrough is gone and I don't know how to restrike through the todos in my listview.
I can populate my listview with the data I extracted from my shared preferences. It shows but it does not strikethrough.
When I tried to access listview getchild, I get a null exception

A: Whenever you are checking the task, save its check status in the shared preference depends on check status you can perform strikethrough


text:
Q: How to extract list of ids and set to output parameter in stored procedure? I read through this article, but O think there must very simple way,which i am not able to figure out how i can get objects or array list of strings or integers.
Say I have table Employee and it has id. I just need list of ids and store it in output parameters like
select id from Employee //This gives a list of integers

I currently have a working code
IF OBJECT_ID('temp16', 'P') IS NOT NULL
    DROP PROCEDURE temp16
GO
CREATE PROCEDURE temp16(  @res int output)
AS
begin
SELECT @res=count(*) from [dbo].[Employee]
end;

//Calling this..

declare @res int;
exec dbo.temp16 @res=@res output ;
select @res

Instead of count(*),i need all list of ids. so something like this is needed,I am PSUEDOCODE
IF OBJECT_ID('temp16', 'P') IS NOT NULL
    DROP PROCEDURE temp16
GO
CREATE PROCEDURE temp16(  @res List<Id> output)
AS
begin
SELECT @res= id from [dbo].[Employee]
end;

declare @res list<int>;
exec dbo.temp16 @res=@res output ;
select @res


text:
Q: AS3 MovieClip name ambiguity Summary: I create instances of various MovieClips via AS3, using MovieClip class objects that are defined in the library.
As each MC is instantiated, I push it into an array for later reference.
Finally I create an XML file that contains data related to each MC, including its name. This is the problematic part – the name has to be able to identify the respective MC when the XML is read back in. I don't want "instance17" etc, which I assume will be meaningless in another session.
Background: I am not a career OO programmer and this is a temporary assignment, forming only a very small part of my long-term interests. It will probably be a couple of years before my next Flash project.
Create instance
Library object
Type: MovieClip, linkage _brakepipe
Instantiation

var brakepipe: _brakepipe = new _brakepipe();
shapes.push(brakepipe);

Then later

var clip: MovieClip = shapes(i);
Trace (clip);

This yields

[object _breakpipe]

So it is giving me the class name, not the MC instance name. What property or method of MC would yield "breakpipe"? (Or even "_breakpipe" - without the "object" prefix?)

A: You can use an associative array. It could look like this:
var shapes:Array = new Array();

and then
shapes.push({item:_brakepipe,_name:"brakepipe"};

Essentially the curly brackets create an Object instance and the name before the colon (:) is the name you create that you want associated with the value after the colon.
so now you can do this in a loop
trace(shapes[i]._name+"\n"+shapes[i].item);
// output:
// brakepipe
// [object _brakepipe]

The nice thing about this method is you can extend it for any number of properties you want to associate with your array element, like this:
shapes.push({item:_brakepipe,_name:"brakepipe",urlLink:"http://www.sierra.com",_status:"used",_flagged:"false"};

and now
shapes[i]._status

would return the string "used".  And you could change that value at runtime to "new" by doing
shapes[i]._status = "new";

A: The Instantiation / Then later / This yields... Seems to be unclear for me, but you may try this and change the code...
Because I'm not sure not sure about the instance name you want to store...
In your loop you may do this if clip is a MovieClip! :
var clip: MovieClip = shapes(i);
clip.name = "breakpipe_" + i
trace (clip.name);

// will output : breakpipe_1 - > breakpipe_n...

You may deal with the clip.name later by removing the extra "_number" if you want.
If i == 13
var clip: MovieClip = new MovieClip();
clip.name = "breakpipe_" + 13
trace(clip.name);
// output breakpipe_13
var pattern:RegExp = /_\d*/g;
trace(clip.name.replace(pattern,""));
//output :
//breakpipe

So here, you may push your Array or Vector with the instance name.
Am I wrong?


text:
Q: Parsing a String into List of information KOTLIN I am an amateur Kotlin programming. And I have one task which I am not sure how to solve.
So any help would come in handy.
More about this task:
I get this message via HTTP post request

AL:OK:XX:XX:XX:XX:XX:YY~~TYPE:3~~FOF:v1.0~~RSSI:-68~~PORT:8215~~TEMP:34.22~~CH1:OK~~CH2:KS~~CH3:PR~~CH4:VL~~CH5:KS~~CH6:OK~~AUX1:OK~~AUX2:KS~~AUX3:OK

And I need to parse this message into following output format.

*

*XX:XX:XX:XX:XX:XY - MAC ADDRESS

*3 - Type of device

*v1.0 - Version of device

*-68 - Signal strenght

*8215 - Server Port

*34.22 - Processor temperature

I only need to get this output in console
I would be really thankfull for any kind of help or hints about this problem.
Thank you in advance,

A: You can use regex group for this purpose and get each part with index. also you can Assign name to each group and then select each part you want with name.
import java.util.regex.Pattern

fun main() {

    val request = "AL:OK:XX:XX:XX:XX:XX:YY~~TYPE:3~~FOF:v1.0~~RSSI:-68~~PORT:8215~~TEMP:34.22" +
            "~~CH1:OK~~CH2:KS~~CH3:PR~~CH4:VL~~CH5:KS~~CH6:OK" +
            "~~AUX1:OK~~AUX2:KS~~AUX3:OK"

    extractValues(request)
}

fun extractValues(request: String) {
    val patternWithName = "AL:OK:(?<macAddress>.+)~~TYPE:(?<type>\\d+)~~FOF:(?<fof>v\\d+.\\d+)~~RSSI:(?<rssi>[-+]\\d+)~~PORT:(?<port>\\d+)~~TEMP:(?<temp>\\d+.\\d+)" +
            "~~CH1:(?<ch1>.+)~~CH2:(?<ch2>.+)~~CH3:(?<ch3>.+)~~CH4:(?<ch4>.+)~~CH5:(?<ch5>.+)~~CH6:(?<ch6>.+)" +
            "~~AUX1:(?<aux1>.+)~~AUX2:(?<aux2>.+)~~AUX3:(?<aux3>.+)"

    val patternWithoutName = "AL:OK:(.+)~~TYPE:(\\d+)~~FOF:(v\\d+.\\d+)~~RSSI:([-+]\\d+)~~PORT:(\\d+)~~TEMP:(\\d+.\\d+)" +
            "~~CH1:(.+)~~CH2:(.+)~~CH3:(.+)~~CH4:(.+)~~CH5:(.+)~~CH6:(.+)" +
            "~~AUX1:(.+)~~AUX2:(.+)~~AUX3:(.+)"

    val matcher = Pattern.compile(patternWithoutName).matcher(request)

    if (matcher.find()) {
        // get with their name --> use [patternWithName]
        // val macAddress = matcher.group("macAddress")
        // val type = matcher.group("type")
        // val fof = matcher.group("fof")

        // or
        // get with index -- use [patternWithName] or [patternWithoutName]
        for (i in 1..matcher.groupCount()) {
            println(matcher.group(i))
        }
    } else {
        error("$request doesn't match.")
    }
}


text:
Q: Display all the same elements Simple HTML DOM Parser I have a problem, i'm parsing IMDB web page using Simple HTML DOM Parser, and my code is the next one:
<?php
require('../simple_html_dom.php');

$url = 'http://www.imdb.com/search/name?gender=female';
$html = file_get_html($url);

foreach ($html->find('table.results tbody') as $div) {
    $extractname = $div->find('tr.detailed td.name a', 0);
    $extractimg = $div->find('tr.detailed td.image', 0);
    $name = $extractname->innertext;
    $img = $extractimg->innertext;
    echo $img, $name;
};
?>

This script returns me that:
Link to image
Well so my problem is that i don't know why my script only returns me one element, and not all the elements.
Thanks!

A: You are getting one element because <tbody> is only one on that page.
You probably want to get result for each tr row.

foreach ($html->find('table.results tbody tr') as $div) {}

A: I usually use XPATH to do things like this, so forgive me if I am wrong.
To me it looks like find() gets an array, you should be looping over the $extractname as an array of elements just as you are doing with the $html find for tbody tags, and the same with $extractimg.
So to me a) you find all the tbody tags and loop them b) inside each tbody you are looking for the other elements which become their own arrays.


text:
Q: Send HTTP Unauthorized (401) from ChannelInterceptorAdapter with Spring I'm trying to figure out how to respond with a 401 Status within a ChannelInterceptorAdapter in case a WebSocket connect is unauthorised.
@Component
public class ConnectInterceptor extends ChannelInterceptorAdapter {

final AuthorizationService mAuthService;

@Autowired
public ConnectInterceptor(final AuthorizationService authService) {
    mAuthService = authService;
}

@Override
public Message<?> preSend(final Message<?> message, final MessageChannel channel) {
    final StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(message);
    if (StompCommand.CONNECT.equals(headerAccessor.getCommand())) {

        final String authValue = (String)headerAccessor.getHeader("Authorization");

        ApiPrincipal principal;
        try {
            principal = mAuthService.authorize(authValue);
        } catch (final UnauthorizedException e) {

            //response.sendError(HttpServletResponse.SC_FORBIDDEN, "AdditionalInformationIfAvailable")??
        }

        headerAccessor.setUser(principal);
    }
    return message;
}

}


text:
Q: Pass JSON var from route to ejs I have some codes in express+EJS,
1) in app.js , the mongo collection object is created,
app.locals.userCollection = db.get('userData');

2) in user.js express route file, I get the data from this DB connection and want to pass it to EJS to render,
exports.list = function(req, res){
   req.app.locals.userCollection.find({},function(err , returnValue){
       if(returnValue.length>0){
          res.render('user', res.locals.returnValue);
       }
       return err;
       });

};
3) In user.ejs I try access it using
<div><script>
var test = <%- returnValue %>;

It gives me returnValue is not defined error.
May I know if i want to access returnValue[0].attr1, what I should code in route and EJS?
Regards
Hammer

A: You can try following:
In Node.js:
res.render('user', data: res.locals.returnValue);
In EJS:
<script type='text/javascript'>
  var rows =<%-JSON.stringify(data)%>
  alert(rows);
</script>

Update (as per questions asked in comments):
If you want to loop over the rows then you should not use JSON.stringify() since it converts your object into String and you may try doing the following (following code works if the data put by server is array object).
<script type='text/javascript'>
    <% data.forEach(function(dataRow, idxOfRow, orgnlAryObject) {
        // You can directly use the dataRow to get each row from the array Object `data`
        //alert(JSON.stringify(dataRow)); // <== You can try this
    }); %>
</script>


text:
Q: Get true color from photo I have following problem. I am developing android app, that would allow you to get real color from photo that was captured by phone camera. You just pick a pixel and get a real color.
How I was trying to solve it: I captured a photo of real black and get its color in photo. Obviously it was not same every time I captured, because of light and etc. But it something close to (0, 0, 0) in RGB. Last time I got (12, 13, 45). And then I captured image where I want to get true colors and when I pick a pixel there I tried to do some vector math. I know that (0, 0, 0) was converted by camera to (12, 13, 45), and so any other color (x, y, z) should be something like (x + 12, y + 13, z + 45). But now I see that it is not right assumption.
So does anybody know how to solve this problem?
EDIT
Not real color. I want to get a color that is very close to the real one.

A: A good place to test your theory would be generating a color with paint and then go into the color picker and slightly adjust the original color.
You can watch the respective RBG vector change and analyse the impact.
(I'm looking to do the same thing and I was actually gonna just add or subtract based on the white in the image but reading your question made me realise I'll have to figure it out another way)


text:
Q: How do I 'better' my paths to lsp server binaries whilst using nvim-lsp-install? At the moment, every time I install a new LPS server using nvim-lsp-installer, I add an entry to my .zshenv, so that the bin folder of the server is available to $PATH:
PATH="$HOME/.local/share/nvim/lsp_servers/python/node_modules/.bin:$PATH"

The nvim-lsp-installer documentation recommends setting up the path with the cmd option in each individual LSP configuration. The thing is that I have never seen that in any of my favorite dotfiles from my favorite fellow neovimers that use lsp-config.
Am I missing something? Is there a way to automate the process? Is there a way to add the bin folders to $PATH during server installation? Or am I doing it the "normal" way?

A: You shouldn't need to modify your PATH manually when using nvim-lsp-installer. The minimal setup recommends the following (there's more in the README):
local lsp_installer = require("nvim-lsp-installer")

lsp_installer.on_server_ready(function (server)
   server:setup {}
end)

By setting up the server via the above interface, nvim-lsp-installer will be able to modify the settings with the necessary properties before passing it onwards to lspconfig.
If you'd like to be able to run the language server executables from a shell, you'd probably be better off installing them manually into a location on your PATH rather than going through nvim-lsp-installer.


text:
Q: Scraping all comments under an Instagram post my previous questions was closed, but the suggested answer doesn't help me. Instagram comments has a very specific behaviour! I know how to programatically scroll a website down, but with the comments on Instagram is a bit different! I would appreciate if my question was not closed immediately because it really doesn't help. Woule ba grateful for help and not shutting me down! Thank you.
Here it is again:
I am trying to build a scraper that is saving the comments under an Instagram post. I manage to log in to the instagram through my code so I can access all comments under a post, but I seem to cannot scroll down enough times to view all comments in order to scrape all of them. I only get around 20 comments everytime.
Can anyone please help me? I am using selenium webdriver.
Thank you for your help in advance! Will be greatfull.
This is my function for saving the comments:
import time
from selenium.webdriver.firefox.options import Options
from selenium.webdriver import Firefox
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

class Instagram_comments():
    def __init__(self):
        self.firefox_options = Options()
        self.browser = Firefox(options=self.firefox_options)

    def get_comments(self, url):
        self.browser.get(url)
        time.sleep(3)

        while True:
        try:
            self.load_more_comments = self.browser.find_element_by_class_name(
                    'glyphsSpriteCircle_add__outline__24__grey_9')
            self.action = ActionChains(self.browser)
            self.action.move_to_element(self.load_more_comments)
            self.load_more_comments.click()
            time.sleep(4)
            self.body_elem = self.browser.find_element_by_class_name('Mr508')
            for _ in range(100):
                self.body_elem.send_keys(Keys.END)
                time.sleep(3)
        except Exception as e:
            pass

        time.sleep(5)
        self.comment = self.browser.find_elements_by_class_name('gElp9 ')
        for c in self.comment:
            self.container = c.find_element_by_class_name('C4VMK')
            self.name = self.container.find_element_by_class_name('_6lAjh').text
            self.content = self.container.find_element_by_tag_name('span').text
            self.content = self.content.replace('\n', ' ').strip().rstrip()
            self.time_of_post = self.browser.find_element_by_xpath('//a/time').get_attribute("datetime")
            self.comment_details = {'profile name': self.name, 'comment': self.content, 'time': self.time_of_post}
            print(self.comment_details)
            time.sleep(5)

    return self.comment_details

A: This chunk worked multiple times for me:
def scroll():

SCROLL_PAUSE_TIME = 1

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)
    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
        print('page height:', new_height)
    last_height = new_height
scroll()

and for some sites you will need to scrape as you scroll as not all elements will appear when you get to the bottom(such as twitter).
This is what my code looked like for twitter:
account_names = []
account_tags = []
account_link = []

def scroll():

SCROLL_PAUSE_TIME = 1
global account_name

# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)
    account_name = driver.find_elements_by_xpath('//*[@id="react-root"]/div/div/div/main/div/div/div/div/div/div[2]/div/div/section/div/div/div/div/div/div/div/div[2]/div[1]/div[1]/a/div/div[1]/div[1]/span/span')
    for act_name in account_name:
        global acctname
        acctname = act_name.text
        account_names.append(acctname)

    account_handle = driver.find_elements_by_xpath('//*[@id="react-root"]/div/div/div/main/div/div/div/div/div/div[2]/div/div/section/div/div/div/div/div/div/div/div[2]/div[1]/div[1]/a/div/div[2]/div/span')
    for act_handle in account_handle:
        global account_tags
        acct_handles = act_handle.text
        account_tags.append(acct_handles)

    soup = BeautifulSoup(driver.page_source, 'lxml')
    account_links = soup.find_all('a', href=True, class_='css-4rbku5 css-18t94o4 css-1dbjc4n r-1loqt21 r-1wbh5a2 r-dnmrzs r-1ny4l3l')
    for acct_links in account_links:
        global act_link
        act_link = acct_links['href']
        account_link.append(act_link)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

scroll()

Just a note: as another user commented, Instagram is very difficult to scrape because of the dynamic html variables, so they would be correct to say no one, myself included is too interested in writing that for instagram.

A: The first function returns True if an element is found
The second function is used to scroll to the bottom till the last comment and then BeautifulSoup is used to scrape all comments
def check_exists_by_xpath(self,xpath):
    try:
        self.driver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True

def get_comments():
        while self.check_exists_by_xpath("//div/ul/li/div/button"):
            load_more_comments_element = self.driver.find_element_by_xpath("//div/ul/li/div/button")
            load_more_comments_element.click()
            sleep(1)

        sleep(2)
        soup = BeautifulSoup(self.driver.page_source,'lxml')
        comms = soup.find_all('div',attrs={'class':'C4VMK'})
        print(len(comms))
        soup_2 = BeautifulSoup(str(comms),'lxml')
        spans = soup_2.find_all('span')
        comments = [i.text.strip() for i in spans if i != '']
        print(comments)

I hope this helps - be aware I'm also still learning.

A: This worked for me, this programmatically clicks the "load more" button, as many times it is displayed.
try:
    load_more_comment = driver.find_element_by_css_selector('.MGdpg > button:nth-child(1)')
    print("Found {}".format(str(load_more_comment)))

    while load_more_comment.is_displayed():
        load_more_comment.click()
        time.sleep(1.5)
        load_more_comment = driver.find_element_by_css_selector('.MGdpg > button:nth-child(1)')
        print("Found {}".format(str(load_more_comment)))

except Exception as e:
    print(e)
    pass


text:
Q: Vizframe chart - type dual_timeseries_combination binding issue I am looking to create vizframe chart of type dual_timeseries_combination but encountered some problem. I took reference from sapui5 explored and kept my code possibly same as the source, but when I run the application system is throwing below error.

[50053] - Incomplete dimensions binding.

Please help me to identify and resolve the issue of rendering vizframe chart on view.
xyz.view.xml
<viz:Popover id="idPopOver1"></viz:Popover>
<viz:VizFrame
    id="idVizFrame1"
    uiConfig="{applicationSet:'fiori'}"
    height='16rem'
    width="100%"
    vizType='dual_timeseries_combination'>
    <viz:dataset>
        <viz.data:FlattenedDataset
            data="{viewModel>/vizData1}">
            <viz.data:dimensions>
                <viz.data:DimensionDefinition
                    name="Date"
                    value="{Date}"
                    dataType="date" />
            </viz.data:dimensions>
            <viz.data:measures>
                <viz.data:MeasureDefinition
                    name="Revenue"
                    value="{Revenue}" />
                <viz.data:MeasureDefinition
                    name="Cost"
                    value="{Cost}" />
            </viz.data:measures>
        </viz.data:FlattenedDataset>
    </viz:dataset>

    <viz:feeds>
        <viz.feeds:FeedItem
            uid="valueAxis"
            type="Measure"
            values="[Revenue, Cost]" />
        <viz.feeds:FeedItem
            uid="timeAxis"
            type="Dimension"
            values="[Date]" />
    </viz:feeds>
</viz:VizFrame>

xyz.controller.js
onInit : function () {
     var oViewModel;
     oViewModel = new JSONModel({
        vizData1 : [
            { "Date": "12/9/2012", "Revenue": 1884613.732, "Cost": 318748.33 },
            { "Date": "12/10/2012", "Revenue": 4682139.01563249, "Cost": 724396.2295 },
            { "Date": "12/11/2012", "Revenue": 3487569.9375, "Cost": 172863.976 },
            { "Date": "12/12/2012", "Revenue": 1046946.00408699, "Cost": 544135.4995 },
            { "Date": "12/13/2012", "Revenue": 1230392.932, "Cost": 467009.594 },
            { "Date": "12/14/2012", "Revenue": 1633524.08, "Cost": 214320.01 },
            { "Date": "12/15/2012", "Revenue": 1235093.22603004, "Cost": 345418.05 },
            { "Date": "12/16/2012", "Revenue": 1251657.04, "Cost": 730441.86 },
            { "Date": "12/17/2012", "Revenue": 1702039.7007113, "Cost": 237474.96 },
            { "Date": "12/18/2012", "Revenue": 2688478.71, "Cost": 631441.19 },
            { "Date": "12/19/2012", "Revenue": 4405105.20883591, "Cost": 355841.326666667 },
            { "Date": "12/20/2012", "Revenue": 2784207.65540919, "Cost": 440651.7895 },
            { "Date": "12/21/2012", "Revenue": 4935443.7925, "Cost": 839335.0875 },
            { "Date": "12/22/2012", "Revenue": 2351452.9805, "Cost": 348700.144 },
            { "Date": "12/23/2012", "Revenue": 2389202.283, "Cost": 364298.4475 },
            { "Date": "12/24/2012", "Revenue": 2526567.4655, "Cost": 442957.047 },
            { "Date": "12/25/2012", "Revenue": 4992077.4605, "Cost": 825631.82 },
            { "Date": "12/26/2012", "Revenue": 2642847.69879874, "Cost": 443445.405 },
            { "Date": "12/27/2012", "Revenue": 4553299.2245, "Cost": 794032.6225 },
            { "Date": "12/28/2012", "Revenue": 2884613.732, "Cost": 418748.33 },
            { "Date": "12/29/2012","Revenue": 3682139.01563249, "Cost": 524396.2295 },
            { "Date": "12/30/2012", "Revenue": 3187569.9375, "Cost": 472863.976 },
            { "Date": "12/31/2012", "Revenue": 2046946.00408699, "Cost": 344135.4995 },
            { "Date": "1/1/2013", "Revenue": 3230392.932, "Cost": 467099.594 },
            { "Date": "1/2/2013", "Revenue": 1733524.08, "Cost": 274320.01 },
            { "Date": "1/3/2013", "Revenue": 2235093.22603004, "Cost": 245418.05 },
            { "Date": "1/4/2013", "Revenue": 4251657.04, "Cost": 739441.86 },
            { "Date": "1/5/2013", "Revenue": 3702039.7007113, "Cost": 637474.96 },
            { "Date": "1/6/2013", "Revenue": 3688478.71, "Cost": 639441.19 },
            { "Date": "1/7/2013", "Revenue": 3405105.20883591, "Cost": 555841.326666667 },
            { "Date": "1/8/2013", "Revenue": 4459242.84574778, "Cost": 748885.11 },
            { "Date": "1/9/2013", "Revenue": 3189469, "Cost": 568303.033333333 },
            { "Date": "1/10/2013", "Revenue": 3004443.98688375, "Cost": 560890.43 }
        ]
    });
    this.setModel(oViewModel, "viewModel");

    var oVizFrame = this.getView().byId("idVizFrame1");
    oVizFrame.setVizProperties({
        plotArea: {
            window: {
                start: "firstDataPoint",
                end: "lastDataPoint"
            },
            dataLabel: {
                formatString:ChartFormatter.DefaultPattern.SHORTFLOAT_MFD2,
                visible: false
            }
        },
        valueAxis: {
            visible: true,
            label: {
                formatString:ChartFormatter.DefaultPattern.SHORTFLOAT
            },
            title: {
                visible: false
            }
        },
        timeAxis: {
            title: {
                visible: false
            },
            interval : {
                unit : ''
            }
        },
        title: {
            visible: false
        },
        interaction: {
            syncValueAxis: false
        }
    });
    var oPopOver = this.getView().byId("idPopOver1");
    oPopOver.connect(oVizFrame.getVizUid());
}

Expected

A: I need to make following code additions in my program and it worked
js
oVizFrame.setVizProperties({
    plotArea: {
        window: {
            start: "firstDataPoint",
            end: "lastDataPoint"
        },
        dataLabel: {
            formatString:ChartFormatter.DefaultPattern.SHORTFLOAT_MFD2,
            visible: false
        }
    },
    valueAxis: {
        visible: true,
        label: {
            formatString:ChartFormatter.DefaultPattern.SHORTFLOAT
        },
        title: {
            visible: false
        }
    },
    valueAxis2: {
        visible: true,
        label: {
            formatString:ChartFormatter.DefaultPattern.SHORTFLOAT
        },
        title: {
            visible: false
        }
    },
    timeAxis: {
        title: {
            visible: false
        },
        interval : {
            unit : ''
        }
    },
    title: {
        visible: false
    },
    interaction: {
        syncValueAxis: false
    }
});


text:
Q: Passing value to EJS I'm facing issue when passing a value from my express app.js file to ejs page.
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");

const app = express();

app.set("view engine", "ejs");

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

app.get("/", function(req, res) {
  res.render("index")
});

app.post("/", (req, res) => {
  const value = req.body.value;

  function RoundTo(number, roundto){
    return roundto * Math.round(number/roundto);
  }

  const a = RoundTo(((((value / 10) + 2) + (value * 1.1)) * 1.05), .25);
  const b = RoundTo(((((value / 10) + 2.3) + (value * 1.4)) * 1.05), .25);
  const c = ((value * 1.12) + 0.5).toFixed(2);
  const d = ((value * 1.17) + 1).toFixed(2);
  const e = (((value * 1.15) * 1.05) + .7).toFixed(2);
  const f = RoundTo(((((value / 10) + 4) + (value * 1.1)) * 1.2), 0.25);
  const g = RoundTo(((((value / 10) + 4) + (value * 1.2)) * 1.5), 0.50);

  res.render("index", {
    rp4you: a,
    cp4you: b,
    b2b4youa: c,
    b2b4youb: d,
    valueptsb: e,
    rptsb: f,
    cptsb: g,
  });

});

app.listen(3000, function() {
  console.log("Server is Up and Running on Port 3000");
})

And here is my ejs file

<form class="" action="/" method="post">
  <input type="number" step="any" name="value" value="">
  <button type="submit" name="submit">Submit</button>
</form>

<%=rp4you%>

<%=cp4you%>

<%=b2b4youa%>

<%=b2b4youb%>

<%=costtsb%>

<%=rptsb%>

<%=cptsb%>

When I run the server. it given an error in ejs file.

20| <%=rp4you%>

21|

22|

23|     Label

rp4you is not defined
at eval (eval at compile (C:\Users\sherg\desktop\price_calculator\node_modules\ejs\lib\ejs.js:662:12), :12:25)
at index (C:\Users\sherg\desktop\price_calculator\node_modules\ejs\lib\ejs.js:692:17)
at tryHandleCache (C:\Users\sherg\desktop\price_calculator\node_modules\ejs\lib\ejs.js:272:36)
at View.exports.renderFile [as engine] (C:\Users\sherg\desktop\price_calculator\node_modules\ejs\lib\ejs.js:489:10)
at View.render (C:\Users\sherg\desktop\price_calculator\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\sherg\desktop\price_calculator\node_modules\express\lib\application.js:640:10)
at Function.render (C:\Users\sherg\desktop\price_calculator\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\sherg\desktop\price_calculator\node_modules\express\lib\response.js:1012:7)
at C:\Users\sherg\desktop\price_calculator\app.js:15:7
at Layer.handle [as handle_request] (C:\Users\sherg\desktop\price_calculator\node_modules\express\lib\router\layer.js:95:5)

A: Its because you are making a GET request which is handled by this
app.get("/", function(req, res) {
  res.render("index")
});

and not this
app.post("/", (req, res) => {
  const value = req.body.value;

  function RoundTo(number, roundto){
    return roundto * Math.round(number/roundto);
  }

  const a = RoundTo(((((value / 10) + 2) + (value * 1.1)) * 1.05), .25);
  const b = RoundTo(((((value / 10) + 2.3) + (value * 1.4)) * 1.05), .25);
  const c = ((value * 1.12) + 0.5).toFixed(2);
  const d = ((value * 1.17) + 1).toFixed(2);
  const e = (((value * 1.15) * 1.05) + .7).toFixed(2);
  const f = RoundTo(((((value / 10) + 4) + (value * 1.1)) * 1.2), 0.25);
  const g = RoundTo(((((value / 10) + 4) + (value * 1.2)) * 1.5), 0.50);

  res.render("index", {
    rp4you: a,
    cp4you: b,
    b2b4youa: c,
    b2b4youb: d,
    valueptsb: e,
    rptsb: f,
    cptsb: g,
  });

});

Which means it doesn't have access to any of the variables.


text:
Q: Query to Linked Server Ignores Configured Timeout Connection I need to know where to set the timeout for a login or a query to a linked server. If the server is down I don't want to waste too much time waiting for a timeout. (Our servers are on the same network with a gigabit connection. All are running SQL Server 2017.)
For example,
SELECT * FROM SERVER_A.master.sys.databases
runs instantaneously if the linked server is up. If the linked server is down, e.g. if I stop the SQL Server service on SERVER_A, it takes 21 seconds to timeout with the following message:

OLE DB provider "SQLNCLI11" for linked server "SERVER_A" returned
message "Login timeout expired".
OLE DB provider "SQLNCLI11" for
linked server "SERVER_A" returned message "A network-related or
instance-specific error has occurred while establishing a connection
to SQL Server. Server is not found or not accessible. Check if
instance name is correct and if SQL Server is configured to allow
remote connections. For more information see SQL Server Books
Online.".
Msg 2, Level 16, State 1, Line 2
Named Pipes Provider: Could not open a connection to SQL Server [2].

EXEC sp_testlinkedserver SERVER_A times out in the same 21 seconds with the same message.
I can't figure out where the timeout is set. Here is what I've tried:

*

*Linked Server Properties for SERVER_A\Advanced, I set the Connection Timeout to 1.

*Linked Server Properties for SERVER_A\Advanced, I set the Query Timeout to 1.

*Local server Properites\Advanced, I set Remote Login Timeout to 1. (Same as EXEC sp_configure 'remote login timeout', 1)

*Local server Properites\Connections, I set Remote query timeout to 10.(Same as EXEC sp_configure 'remote query timeout', 10)

*I looked through all of the settings in sys.configurations and couldn't find any that are anywhere near 21.

Regardless of what settings I change, the timeout still takes 21 seconds and returns the above error message.
What am I missing?

UPDATE:
I tried setting the linked server connection timeout to 43. After that, it took 63 seconds to timeout. We're getting somewhere! Setting it to 30 or 33 times out in 42 seconds, etc. Something is adding either 12 or 20 seconds to the login timeout.
After more testing, it appears that the timeouts I'm experiencing are in multiples of 21 seconds. It's taking 21, 42 or 63 seconds to timeout. It takes longer as I increase the Connection Timeout past a multiple of 21. e.g. if I set the Connection Timeout to 21, it takes 42. If I set it to 50, it takes 63.

A: I was able to achieve it in two ways:
Configuring a timeout for the whole server
You should configure the server timeout option (remote login timeout) using sp_configure:
EXEC sp_configure 'remote login timeout', 1 ;
GO
RECONFIGURE ;
GO

Configuring a timeout for the specified Linked Server
You should configure the Connection Timeout with the value 1 or more:

If you query sys.servers by now, you should see the specified value for the column connect_timeout.

I noticed a strange behavior after configuring it. SQL Server seems to try the remote connection longer than the specified connection timeout the first time you try to run a query using a linked server (as if it was insisting to be sure it can't reach the remote server). But the following attempts of running a query it threw the connection error quickly as specified.


text:
Q: UICollectionView cell leaves huge gaps all settings set to 0 Hi there i have a slight problem with my UICollectionView. i don't currently have any settings set for spacing yet i seem to have a huge gap between my cells of which is very annoying if would be helpful if someone could tell me how to resolve this? id assume its something very simple.
Below is an example of whats happening to my CollectionViewCells:

Custom cell.h
#import <UIKit/UIKit.h>

@interface CustomCell : UICollectionViewCell

@property (weak, nonatomic) IBOutlet UIImageView *IconImage;

@property (weak, nonatomic) IBOutlet UILabel *IconLabel;

@property (weak, nonatomic) IBOutlet UILabel *IconDescription;

@end

groupsviewcontroller.m
#import "GroupsViewController.h"
#import "CustomCell.h"

@interface GroupsViewController ()
{
    NSArray *arrayOfImages;
    NSArray *arrayOfDescriptions;
}

@end

@implementation GroupsViewController
{
    NSString *reuseIdentifier;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    reuseIdentifier= @"SmallIcon";
    [[self GroupsCollectionView]setDataSource:self];
    [[self GroupsCollectionView]setDelegate:self];

    arrayOfImages = [[NSArray alloc]initWithObjects:@"sin.png", nil];

    arrayOfDescriptions = [[NSArray alloc]initWithObjects:@"Sin", nil];

}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [arrayOfDescriptions count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    CustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    [[cell IconImage]setImage:[UIImage imageNamed:[arrayOfImages objectAtIndex:indexPath.item]]];
    [[cell IconLabel]setText:[arrayOfDescriptions objectAtIndex:indexPath.item]];

    return cell;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    //Dispose of any resources that can be recreated.
}

- (IBAction)cellToggleAction:(id)sender {
//need to add toggle button to toggle between three different views

    //small icon
    //list view
    //large icon
}

@end

A: 1) You should check your CustomCell class, see if any size constraint is applied. Simply set your cell's background as some color and the actual cell size will be highlighted.
2) Use (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath to help yourself set the proper cell size. This func comes with UICollectionViewDelegateFlowLayout :)


text:
Q: What is the use of multiple Jenkins plugin directory? I was trying to create a Jenkins master slave system using Helm Charts. [ https://github.com/jenkinsci/helm-charts/blob/main/charts/jenkins/README.md ].
After deploying I can see the plugins are stored in two locations in the pod/ docker container.
1. /var/jenkins_home/plugins

2. /usr/share/jenkins/ref/plugins

What's the relation between these two? JENKINS_HOME is configured as /var/jenkins_home/. If I need to backup the plugins which directory should I backup ?
For a plugin named ace-editor, I can see these many files in respective folders.
/usr/share/jenkins/ref/plugins contains (1 file) -> ace-editor.jpi
/var/jenkins_home/plugins contains (4 file) -> ace-editor.jpi, ace-editor.jpi, ace-editor.jpi.pinned, ace-editor.jpi.version_from_image
What does this mean?

A: The directory to back up is always /var/jenkins_home. It is meant to be a persistent volume with all the data. /var/jenkins_home/plugins contains the downloaded .jpi plugin files and directories where each plugin has been unpacked.
The directory /usr/share/jenkins/ref is a "reference" directory on the container image. This means /usr/share/jenkins/ref/plugins is used as a starting point to install a base set of plugins into /var/jenkins_home/plugins the first time you run Jenkins.
The log file containing info about installed reference files is /var/jenkins_home/copy_reference_file.log.
The files with suffix .pinned or .version_from_image are used to control subsequent behaviour for example when plugins have been updated in jenkins_home from the UI and/or to the reference directory in a newer container image. Some users might want to use the bundled plugins in the image only for initial startup, others as the definitive source of all updates. See also environmental variables described in the documentation.
If you want to examine the inner workings you can find shell script jenkins.sh and functions source jenkins-support in the repository root or in /usr/local/bin on the image.


text:
Q: Imprimir datos repetidos en un arreglo en php Tengo el siguiente arreglo con valores repetidos y después los ordeno por valor más alto, en el condicional se imprime el valor mas alto del arreglo "Es 2" pero también quiero que se imprima el valor repetido.
<?php
   $fPro = ["0" => 10, "1" => 20, "2" => 40, "3" => 40];
    arsort($fPro);
   foreach($fPro as $key => $value){
    $mayorProK = $key;
    $mayorrPro = $value;
    break;
}

    if($mayorProK == 0){
        print_r("Es 0");
    }
    if($mayorProK == 1){
        print_r("Es 1");
    }
    if($mayorProK == 2){
        print_r("Es 2");
    }
    if($mayorProK == 3){
        print_r("Es 3");
    }

?>

A: Esta es mi aproximación a tu pregunta:
$fPro = [
    "0" => 10,
    "1" => 20,
    "2" => 40,
    "3" => 40
];
arsort($fPro);

echo "Es ".key($fPro)." (".current($fPro).")\n";

foreach (array_count_values($fPro) as $valor => $repeticiones) {
    if ($repeticiones>1) {
        echo "Valor repetido: $valor \n";
    }
}

Explicación:
Para conseguir la clave del valor más alto después de la ordenación, he usado esto:
key($fPro)

pues justo después de la ordenación con arsort, el puntero del array se encuentra en el primer elemento, y la función key, en el manual de php, dice:

La función key() simplemente devuelve la clave del elemento del array
que está apuntando actualmente el puntero interno.

Del mismo modo, para conseguir su valor, he puesto esto:
current($fPro)

pues la función current, de nuevo en el manual, dice:

La función current() simplemente devuelve el valor del elemento del
array que está siendo apuntado por el puntero interno.

Y de ahí la sentencia completa, similar a la que ya tenias:
echo "Es ".key($fPro)." (".current($fPro).")\n";

donde he agregado el valor entre paréntesis para que se vea más claro.
Luego, para las repeticiones, he usado la función array_count_values, que en el manual dice:

Retorna un array asociativo de valores a partir de array como keys y
su respectivo recuento como valores.

Por lo tanto, he recorrido ese array asociativo mediante un foreach sacando sus pares clave/valor como $clave => $repeticiones.
Es decir:
foreach (array_count_values($fPro) as $valor => $repeticiones) {

Y dentro de este bucle, en cada iteración, compruebo si el valor de $repeticiones es superior a 1, pues si lo es entonces estará indicando que efectivamente hay repeticiones de ese valor, así:
if ($repeticiones>1) {
    echo "Valor repetido: $valor \n";
}

y como ves, si se cumple la condición, la salida me muestra el mensaje del valor repetido.


text:
Q: TinyMCE Editor -How to integrate the customization scrollbar I need to integrate the custom scroll bar to TinyMCE Editor.Can you please guid me how to integrate it.
Url:http://manos.malihu.gr/tuts/jquery_custom_scrollbar.html

A: You get rid of the defaukt scollbar you may apply this css to the editor iframe (you might need to be more precise, otherwise you could remove scrollbars from other iframes as well)
iframe {
    overflow:hidden;
}

This is the necessay code to get css files into the tinymce editor iframe head
var ed = tinymce.get('your_editor_id');
ed.dom.loadCSS( 'url_to_css_file');


text:
Q: [textRPG]How to keep random creating of class and class atrributes every time i run a program[Python] I am trying some text based rpg game as a beginner in python. But i am struggling to  get done one thing.
If i use while loop to run program 5 times. So i want repeat killing monster but without saving his attributes.
If you run this code, character kills a monster in couple of moves and appends his experience to himself and monster hp decreases to <= 0 and dies.
Looping whole program does not work, randomly created monster is still the same, i just want to create new monster with new random attributes every time i loop program. It is possible? I am new to this and can't figure it out at this moment. Some tips ?
Here is some code but without while loop:  final output is to loop this menu and fight simulator to gain exp and items from random monsters.
import random
import time

# List of items to drop
normal_items = ['Copper ore', 'Apple', 'Animal skin', 'Stone', 'Feather', 'Rotten egg', 'Bag of sand', "Simple dagger", "Blue flower"]
rare_items = ['Energized wand', 'Staff of purity', 'Enhanced gloves', 'Adamant chest plate']
legendary_items = ['Crown of Immortality', 'Robe of fire-dragon']

drop_chance_dice = random.randint(1, 100)

# Simple drop chance function

def dice():

    if drop_chance_dice <= 70:
        random_choice = (random.choice(normal_items))
        print(f"You got: {random_choice} ")
    if 70 <= drop_chance_dice <= 98:
        random_choice = (random.choice(rare_items))
        print(f"You got: {random_choice} ")
    if 99 <= drop_chance_dice <= 100:
        random_choice = (random.choice(legendary_items))
        print(f"Congratulations! You got an legendary item: {random_choice}")
# Instances and mobs

rat_nest= ['Rat', 'Giant Rat', 'Leader of Rats']

northern_forest = ['Snake', 'Wolf', 'Witch']

# My Character Class
class YourCharacter:

    def __init__(self, intro, name, attack, exp, level, hp):
        self.intro = intro
        self.name = name
        self.attack = attack
        self.exp = exp
        self.level = level
        self.hp = hp

# Creating my character(preset)
my_character = YourCharacter("Your character \n", 'FroGres', 16, 0, 1, 100)

# Introduction
def introduction_of_player(my_character):
    print(f"{my_character.intro}")
    print(f"{my_character.name}")
    print(f"Attack: {my_character.attack}")
    print(f"Experience: {my_character.exp}")
    print(f"Level: {my_character.level}")
    print(f"HP: {my_character.hp}")

# Monsters class build
class Monster:

    def __init__(self, intro, name, attack, exp, level, hp):
        self.intro = intro
        self.name = name
        self.attack = attack
        self.exp = exp
        self.level = level
        self.hp = hp

# Monsters attributes  + list of mobs (for testing - to be upgraded)
# rat nest
rat = Monster("You fight vs: \n", "Rat", random.randint(4, 6), random.randint(8, 14), random.randint(1, 3),
              random.randint(50, 100))
giant_rat = Monster("You fight vs: \n", "Giant Rat", random.randint(6, 8), random.randint(10, 18), random.randint(2, 4),
                    random.randint(80, 130))
rat_boss = Monster("You fight vs: \n", "Leader of Rats", random.randint(4, 6), random.randint(8, 14),
                   random.randint(1, 3),
                   random.randint(50, 100))

# northern forest
#Witch = Monster("You fight vs: \n", "Witch", random.randint(8, 12), random.randint(12, 20), random.randint(3, 6), random
               # .randint(120, 200))

list_of_mobs = [rat, giant_rat, rat_boss]

event_mob = random.choice(list_of_mobs)   # Random pick monster , USED in function
# Introduction of Monster

def introduction_of_monster_ratnest(list_of_mobs):
    print(f"{list_of_mobs.intro}")
    print(f"{list_of_mobs.name}")
    print(f"Attack: {list_of_mobs.attack}")
    print(f"Experience: {list_of_mobs.exp}")
    print(f"Level: {list_of_mobs.level}")
    print(f"HP: {list_of_mobs.hp}")

def escape_or_fight():

    take_input = input("[a]ttack or [r]un?")
    if take_input == 'a':
        return attack()
    if take_input == 'r':
        print("You run as fast as possible.. ")
        print("You returning to your hideout..")
    else:
        print("Something wrong")

# Menu of actions
def menu_dungs():
    asking = input("Where do you want to go?: 1.Rat Nest or 2.Northern Forest :")
    if asking == "1":
        print("You entering rat nest.. good luck!\n")
        time.sleep(1)
        print("Some ugly creature stays on your way!")
        print(f"{event_mob.name} is looking at you!")
        if event_mob == rat:
            introduction_of_monster_ratnest(rat)
            escape_or_fight()
        elif event_mob == giant_rat:
            introduction_of_monster_ratnest(giant_rat)
            escape_or_fight()
        elif event_mob == rat_boss:
            introduction_of_monster_ratnest(rat_boss)
            escape_or_fight()
        else:
            print("Something went horribly wrong.. Don't even ask..")

    elif asking == "2":
        print("You entering northern forest.. good luck!\n")
        print("Dungeon unavailable at this moment, try another one")
        pass
        # Not in use
    else:
        print("Try again and choose correct location\n")
        menu_dungs()

def attack():

    gain_exp = event_mob.exp + my_character.exp
    rounds = 0
    while event_mob.hp > 0:
        event_mob.hp = event_mob.hp - my_character.attack
        rounds += 1
        print(f"You hit with: {my_character.attack} damage.  Enemy HP is {event_mob.hp}")
        print(f"Enemy HP after your attack is {event_mob.hp}", "\n")

    if event_mob.hp <= 0:
        print(f"{event_mob.name} has died..")
        print(f"It tok you: {rounds} moves to kill that creature! \n")
        print("Congratulations! Here is your loot")
        dice()
        print(f"You got: {event_mob.exp} experience from that fight.")
        print(f"Your experience is now: {gain_exp}")

menu_dungs()

I tried: to create  new unique monster with new randomly created attributes every time i run program. I used while loop but monster is not "respawning"
I expect: Some sort of simulator, after i kill monster, program creates new one and my character gains experience and items every fight.
I wonder: If there is some method to makes this class unique every loop.

A: Here is HOW-TO to achieve all goals in your question:

*

*each time generate monsters with different parameters

*respawn monsters

First you create 3 sepreate functions that would return a new monster - the class of returned value is always the same (Monster) but they return new instances on each call:
def get_rat():
    return Monster("You fight vs: \n", "Rat", ...)

def get_giant_rat():
    return Monster(...)

def get_rat_boss():
    reutrn Monster(...)

You will also need to modify how you select monsters. I would suggest to create list of functions - so instead of selecting a monster you select a function, that generates monster:
# This should replace the list_of_mob
list_of_mob_generators = [get_rat, get_giant_rat, get_rat_boss]

And the last - you should select monster on each loop interation in main menu (so the monster could respawn). The shortest way is to change your global variable:
event_mob = None  # we change event_mob initially to None - we will select in later

def menu_dungs():
    global event_mob  # this is new
    asking = input("Where do you want to go?: 1.Rat Nest or 2.Northern Forest :")
    if asking == "1":
        event_mob_generator = random.choice(list_of_mob_generators)  # get one of the functions
        event_mob = event_mob_generator()  # call the function to get monster

        print("You entering rat nest.. good luck!\n")
        time.sleep(1)
        print("Some ugly creature stays on your way!")
        print(f"{event_mob.name} is looking at you!")
        # and this condition has changed, since we do not have one instance of each monster anymore
        if event_mob.name == 'Rat':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        elif event_mob.name == 'Giant Rat':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        elif event_mob.name == 'Rat Boss':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        else:
            print("Something went horribly wrong.. Don't even ask..")
    ... # and so on

and of course do not forget a while loop for main menu =)
while True:
    menu_dungs()

A: Thanks for help, program works as i wanted but still shows me 8 yellow errors in attack() function. Cannot find reference 'hp' in  'None'  etc.
maybe because this event_mob = None ?
Could you run this code and see what is going on ? very likely i  did put something in wrong place..
import random
import time

# List of items to drop
normal_items = ['Copper ore', 'Apple', 'Animal skin', 'Stone', 'Feather', 'Rotten egg', 'Bag of sand', "Simple dagger", "Blue flower"]
rare_items = ['Energized wand', 'Staff of purity', 'Enhanced gloves', 'Adamant chest plate']
legendary_items = ['Crown of Immortality', 'Robe of fire-dragon']

drop_chance_dice = random.randint(1, 100)

# Simple drop chance function

def dice():

    if drop_chance_dice <= 70:
        random_choice = (random.choice(normal_items))
        print(f"You got: {random_choice} ")
    if 70 <= drop_chance_dice <= 98:
        random_choice = (random.choice(rare_items))
        print(f"You got: {random_choice} ")
    if 99 <= drop_chance_dice <= 100:
        random_choice = (random.choice(legendary_items))
        print(f"Congratulations! You got an legendary item: {random_choice}")
# Instances and mobs

rat_nest= ['Rat', 'Giant Rat', 'Leader of Rats']

#not in use
northern_forest = ['Snake', 'Wolf', 'Witch']

# My Character Class
class YourCharacter:

    def __init__(self, intro, name, attack, exp, level, hp):
        self.intro = intro
        self.name = name
        self.attack = attack
        self.exp = exp
        self.level = level
        self.hp = hp

# Creating my character(preset)
my_character = YourCharacter("Your character \n", 'FroGres', 16, 0, 1, 100)

# Introduction
def introduction_of_player(my_character):
    print(f"{my_character.intro}")
    print(f"{my_character.name}")
    print(f"Attack: {my_character.attack}")
    print(f"Experience: {my_character.exp}")
    print(f"Level: {my_character.level}")
    print(f"HP: {my_character.hp}")

# Monsters class build
class Monster:

    def __init__(self, intro, name, attack, exp, level, hp):
        self.intro = intro
        self.name = name
        self.attack = attack
        self.exp = exp
        self.level = level
        self.hp = hp

# Monsters getting functions
# rat nest
def get_rat():
    return Monster("You fight vs: \n", "Rat", random.randint(4, 6), random.randint(8, 14), random.randint(1, 3),
              random.randint(50, 100))
def get_giant_rat():
    return Monster("You fight vs: \n", "Giant Rat", random.randint(6, 8), random.randint(10, 18), random.randint(2, 4),
                    random.randint(80, 130))
def get_rat_boss():
    return Monster("You fight vs: \n", "Rat Boss", random.randint(4, 6), random.randint(8, 14),random.randint(1, 3),
                   random.randint(50, 100))

# northern forest
# def get_witch():
#   return Monster("You fight vs: \n", "Witch", random.randint(8, 12), random.randint(12, 20), random.randint(3, 6), random
               # .randint(120, 200))

list_of_mobs_generators = [get_rat, get_giant_rat, get_rat_boss]

def escape_or_fight():

    take_input = input("[a]ttack or [r]un?")
    if take_input == 'a':
        return attack()
    if take_input == 'r':
        print("You run as fast as possible.. ")
        print("You returning to your hideout..")
    else:
        print("Something wrong")

# Menu of actions
event_mob = None
def menu_dungs():
    global event_mob
    asking = input("Where do you want to go?: 1.Rat Nest or 2.Northern Forest :")
    if asking == "1":
        event_mob_generator = random.choice(list_of_mobs_generators)
        event_mob = event_mob_generator()
        def introduction_of_monster_ratnest(event_mob):
            print(f"{event_mob.intro}")
            print(f"{event_mob.name}")
            print(f"Attack: {event_mob.attack}")
            print(f"Experience: {event_mob.exp}")
            print(f"Level: {event_mob.level}")
            print(f"HP: {event_mob.hp}")

        print("You entering rat nest.. good luck!\n")
        time.sleep(1)
        print("Some ugly creature stays on your way!")
        print(f"{event_mob.name} is looking at you!")
        if event_mob.name == 'Rat':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        elif event_mob.name == 'Giant Rat':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        elif event_mob.name == 'Rat Boss':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        else:
            print("Something went horribly wrong.. Don't even ask..")

    elif asking == "2":
        print("You entering northern forest.. good luck!\n")
        print("Dungeon unavailable at this moment, try another one")
        pass
        # Not in use
    else:
        print("Try again and choose correct location\n")

def attack():
    gain_exp = event_mob.exp + my_character.exp
    rounds = 0
    while event_mob.hp > 0:
        event_mob.hp = event_mob.hp - my_character.attack
        rounds += 1
        print(f"You hit with: {my_character.attack} damage.  Enemy HP is {event_mob.hp}")
        print(f"Enemy HP after your attack is {event_mob.hp}", "\n")

    if event_mob.hp <= 0:
        print(f"{event_mob.name} has died..")
        print(f"It tok you: {rounds} moves to kill that creature! \n")
        print("Congratulations! Here is your loot")
        dice()
        print(f"You got: {event_mob.exp} experience from that fight.")
        print(f"Your experience is now: {gain_exp}")

while True:
    menu_dungs()


text:
Q: VMware Fusion - How to SSH into a VM when not on a network? So I have a MacBook Pro here running Mavericks and VMWare Fusion 6.
I have an Ubuntu Server VM I need for a project running. It snags a static IP on the network.
Now I like to completely ignore / hide the VM window itself and instead SSH into the machine using Terminal. On Windows I could do this with VMware Workstation without issue using PuTTy. I didn't even have to have a window open.
On the Mac, well it's a laptop to be fair and laptops go places, places without WiFi on occasion.
So how can I SSH into a VM running locally without being on any external network?
EDIT: After switching the VM to NAT, this is my ifconfig:

A: You would set the networking mode of the VM to NAT in Virtual Machine => Network.

Then reboot or reinitialize the network in the virtual machine.
From there, you can use the NAT address of the virtual machine from your Mac.
The ifconfig command in your VM will reveal the NAT'ed address you could use for communication between the systems.


text:
Q: Show that if $H$ is a subgroup of the group $(G, *)$ that contains all natural numbers $k\ge4$ then $H$ contains all rational numbers $q>3$. Consider the group $(G, *)$ with underlying set $G = (3, \infty)\subset\Bbb R\,$ and operation
$$x * y = (x-3)(y-3)+3$$
I have to show that if $H$ is a subgroup of the group $(G, *)$ that contains all natural numbers $k \ge 4$, then $H$ contains all rational numbers $q > 3$.
I'm not really sure how to interpret this. What is asked, really? And how to solve that? I mean, if $H$ contains only natural numbers that are greater that $4$, wouldn't the binary operation:
$$x * y = (x - 3)(y - 3) + 3$$
yield natural numbers only, since $x$ and $y$ are natural numbers and greater than $4$? Where do rational numbers come into the picture? And how can I show what is asked?

A: Compute the identity element $e$ and furthermore the inverse $x^{-1}$ of an element $x$. That should give you an argument of why the group contains rational numbers.


text:
Q: PHP extension upload progress - returning negative total bytes and time remaining I'm using the PHP upload progress extension to retrieve information about files being uploaded to my web system. However for files larger than 2GB the total bytes and time remaining fields are being returned as negative numbers.
Apache has been setup to ensure that files of a size up to 3GB can be uploaded to the website. I have tested this and it works. However it is purely the reporting that is coming back incorrectly.
I was wondering if this was anything to do with a limit on the PHP values and what could be done to fix it. I believe the system is using 64bit integers. As the following shows:
echo "PHP_INT_MAX: " . PHP_INT_MAX;
// PHP_INT_MAX: 9223372036854775807

Here's some extra information on how the progress bar works and is installed: http://www.ultramegatech.com/blog/2010/10/create-an-upload-progress-bar-with-php-and-jquery/
To get the information I simply call the extension function:
$status = uploadprogress_get_info($unique_form_id);

Which returns the total bytes, est time remaing, current bytes and more as shown below (with negative total bytes):
array(11) {
    ["upload_id"]=> string(32) "ec75a30c24177ec1579aea93b56224f2"
    ["fieldname"]=> string(9) "comp_data"
    ["filename"]=> string(15) "Size_2-09GB.zip"
    ["time_start"]=> string(10) "1325851749"
    ["time_last"]=> string(10) "1325851758"
    ["speed_average"]=> string(5) "93011"
    ["speed_last"]=> string(6) "112618"
    ["bytes_uploaded"]=> string(6) "837105"
    ["bytes_total"]=> string(11) "-2048166056"
    ["files_uploaded"]=> string(1) "1"
    ["est_sec"]=> string(9) "-76260228"
}

Update (6th Jan 2012): I have also contacted the developer of this extension to see if they can share any insight.
Update (9th Jan 2012): Developer of the extension has responded pointing out that there is an existing ticket regarding this issue: https://bugs.php.net/bug.php?id=59918
Update (16th Jan 2012): Have managed to get rid of the negative value being returned by the extension. However the number returned is way off what the actual number of total bytes in comparison to what Windows says it is in the properties window.

A: Use a float and remove the decimals - this will work for these larger numbers:
$filesize = filesize($large_file);
printf(Filesize: %.0f\n", $filesize);

This answer will confirm if you are using 64bit Integers : how to have 64 bit integer on PHP?
Note: although there is another answer to that question which seems to indicate that 64bit integers are not available on windows - what OS are you using ?


text:
Q: IRI as parameter for filtering ressources We use IRI for identifying ressource in our API. When we want to filter another ressource with a ressource we have to use the ID part of the IRI. Is that normal?
Exemple :
GET /api/authors
[{
  @id: "/api/authors/45gfd654d",
  name: "John Doe",
}]

GET /api/books?authors=[45gfd654d]

It seems complicated to use because we have to split the IRI to be able to use the last part in others API calls. My question is : What are the guidelines in such case? The ressource must have an id (with only the last IRI part) or to we allow to filter with IRI?
Thank

A: Indeed a pain! We opted to try and actually use (relative) uris in query parameters.
In many cases we'll also create specialized endpoints like /api/authors/[id]/books. Although ultimately similar, our clients don't ever construct or deconstruct urls. Urls are discovered, so a client will find a 'list of books' link on the author resource.


text:
Q: CSS flex layout and intruding footer issue I started my adventure with flex (Angular Material version to be precise) and approached a difficult problem to solve. Basically I would have a cake and eat the cake :) So I wish my footer was always in the bottom but in the small resolutions while page is very short, I would like avoid floating by footer over main content and not setting hard height for the content.
My page markup is like:

   <ui-view layout="column" layout-fill>
       <md-toolbar>top menu</md-toolbar>

           <md-sidenav flex="15" md-component-id="left" md-is-locked-open="$mdMedia('gt-sm')">left menu</md-sidenav>
           <md-content flex>page content</md-content>

       footer
   </ui-view>

A: Do I understand you correct with this solution? ... and when content exceed the viewport it pushes either the footer down and all page will scroll

html, body {
  margin: 0;
}
body {
  display: flex;           /*  IE 11/10 min-height bug fix  */
}
ui-view {
  min-height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
}
.main-content {
  flex: 1;
  display: flex;
}
md-sidenav {
  background: lightgray;
}
md-content {
  background: lightblue;
  flex: 1;
}

   <ui-view layout="column" layout-fill>
       <md-toolbar>top menu</md-toolbar>

           <md-sidenav flex="15" md-component-id="left" md-is-locked-open="$mdMedia('gt-sm')">left menu</md-sidenav>
           <md-content flex>
             page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
         </md-content>

       footer
   </ui-view>

or the main-content starts to scroll

html, body {
  margin: 0;
}
body {
  display: flex;           /*  IE 11/10 min-height bug fix  */
}
ui-view {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
}
.main-content {
  flex: 1;
  display: flex;
  overflow: auto;
  background: lightgray;
}
md-sidenav {
  width: 120px;
}
md-content {
  background: lightgreen;
  flex: 1;
}
.wrapper {
  background: lightblue;
}

   <ui-view layout="column" layout-fill>
       <md-toolbar>top menu</md-toolbar>

           <md-sidenav flex="15" md-component-id="left" md-is-locked-open="$mdMedia('gt-sm')">left menu</md-sidenav>
           <md-content flex>

             page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content
 page content

           </md-content>

       footer
   </ui-view>


text:
Q: jQuery File Upload, specifying FormData I'm working to use the following jQuery File Upload plugin:
https://github.com/blueimp/jQuery-File-Upload/wiki/Options

I need to specific extra formdata which it says there is an option for, but I'm getting a JS error "Uncaught SyntaxError: Unexpected identifier" and there are no FormData examples, which is making it hard to get to work.
Here is what i have:
$(function () {
    $('.upload').fileUploadUI({
        uploadTable: $('.upload_files'),
        downloadTable: $('.download_files'),
        buildUploadRow: function (files, index) {
            var file = files[index];
            return $(
                '
' +
                '' + file.name + '<\/td>' +
                '
<\/div><\/td>' +
                '' +
                '
' +
                'Cancel<\/span>' +
                '<\/div>' +
                '<\/td>' +
                '<\/tr>'
            );
        },
        buildDownloadRow: function (file) {
            return $(
                '
' + file.name + ' ' + file.type + ' ' + file.size + '<\/td><\/tr>'
            );
        },
  formData:
   [
     {
       name: '_http_accept'
       value: 'application/javascript'
     },
     {
       name: '<%= session_key_name %>'
       value: encodeURIComponent('<%= u cookies[session_key_name] %>'),
     },
     {
       name: 'authenticity_token'
       value: encodeURIComponent('<%= u form_authenticity_token %>')
     }
   ]
    });
});

A: You don't have commas in the right places in your formData, I think you want it to be like this:
formData: [
    {
        name: '_http_accept',
        value: 'application/javascript'
    }, {
        name: '<%= session_key_name %>',
        value: encodeURIComponent('<%= u cookies[session_key_name] %>')
    }, {
        name: 'authenticity_token',
        value: encodeURIComponent('<%= u form_authenticity_token %>')
    }
]

Note that there are commas after the name: ... parts but not the value: ... parts.
Also, I don't think encodeURIComponent() is the appropriate escaping/encoding mechanism here and <%= u ... already URI encodes. All you need to do is make sure the string doesn't contain an unescaped single quote so something more like this would probably work (assuming that this JavaScript is going through ERB):
value: '<%= cookies[session_key_name].gsub(/'/, "\'") %>'

The appropriate encoding should be handled by the plugin and it is almost certainly doing a POST anyway so URL encoding doesn't even apply.
Also, you don't need to escape slashes in JavaScript strings, they're not special so you can just say '	' where you say '<\/td>'.
I don't know anything about jQuery-File-Upload but fixing your commas should at least get you past your immediate problem (and on to new and more interesting problems!).


text:
Q: Select text and autocopy whithout ctr+c I need an js or php script who can help me to "select text and autocopy" without press ctrl + c, just select and copy in my html table columns page, could I do that?
Thank you so much for your help

A: I would recommend using this:
https://clipboardjs.com/
It is a javascript library that does ecactly what you want.

A: I need just while selecting the text, this selection can copy my text without using an Submit Button / or copy button.
Thank you


text:
Q: Compare DateTime with 24 hours ``I have a method to retrieve DateTime from MS Acesss. I want to allow a client to cancel his booking up to 24 hours prior to the date. How can I code this using if else statement?
this is my method.
    public static string Date(int c)
    {
        string a;
        OleDbConnection myconn = DBConn();
        string myQ = "SELECT DateTime FROM Booking WHERE movie_ID=" + c;
        OleDbCommand myCmd = new OleDbCommand(myQ, myconn);
        try
        {
            myconn.Open();

            a = myCmd.ExecuteScalar().ToString();

            return a;

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception in DBHandler", ex);
            return null;
        }
        finally
        {
            myconn.Close();
        }
    }

How to code if else statement like
       string d = db.date(id);
       DateTime n = Convert.toDateTime(d);
       if ( n <= 24 hours???){
       do.this....
      }

A: make a method like this
public static bool canCancel(string date)
{
    DateTime booking = Convert.ToDateTime(date);
    DateTime ending = booking.AddHours(23).AddMinutes(59).AddSeconds(59);

    var n = DateTime.Compare(ending, DateTime.Now);
    if(n == -1)
    {
       // within 24 hour from booking
       // so can not cancel
       return false;
    }
    else
    {
       // greater than 24 hour
       // so can cancel
       return true;
    }

}

then call it
public static string Date(int c)
    {
        string a;
        OleDbConnection myconn = DBConn();
        string myQ = "SELECT DateTime FROM Booking WHERE movie_ID=" + c;
        OleDbCommand myCmd = new OleDbCommand(myQ, myconn);
        try
        {
            myconn.Open();

            a = myCmd.ExecuteScalar().ToString();

            var can_cancel = canCancel(a);
            return a;

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception in DBHandler", ex);
            return null;
        }
        finally
        {
            myconn.Close();
        }
    }

A: You can modify you function as per your requirements but hope below gives you an idea:
try
    {
        myconn.Open();
        a = myCmd.ExecuteScalar().ToString();
        DateTime DateFromAccess = Convert.ToDateTime(a);

       TimeSpan difference = DateFromAccess.Subtract(DateTime.Now);
       if (difference.TotalHours > 24)
          //Your Code to Cancel Booking
       else
          //"Booking can not be cancelled now";

        return a;
    }

catch(Exception){
    //Handle exception
}


text:
Q: Resizing a 100GB Recovery HD Partition Some time ago, I used BootCamp to set up a partition for Windows 7 on my MacBook Pro (13" late 2014 if it matters) so I could dual-boot. I have since removed the partition using BootCamp, but still can't reclaim the disk space.
The new Disk Utility doesn't show the partition (I'm using the 10.11 Public Beta, but have also checked in the Recovery partition which is still using the old Yosemite Disk Utility).
However, the diskutil Terminal command shows this:
cwatson@ragnarok:~$ diskutil list
/dev/disk0 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *500.3 GB   disk0
   1:                        EFI EFI                     209.7 MB   disk0s1
   2:                  Apple_HFS Macintosh HD            398.6 GB   disk0s2
   3:                 Apple_Boot Recovery HD             101.5 GB   disk0s3

It seems the resize has screwed up somewhere, and made the Recover HD over 100GB.
cwatson@ragnarok:~$ sudo gpt -r show /dev/disk0
Password:
      start       size  index  contents
          0          1         PMBR
          1          1         Pri GPT header
          2         32         Pri GPT table
         34          6
         40     409600      1  GPT part - C12A7328-F81F-11D2-BA4B-00A0C93EC93B
     409640  778422104      2  GPT part - 48465300-0000-11AA-AA11-00306543ECAC
  778831744  198273280      3  GPT part - 426F6F74-0000-11AA-AA11-00306543ECAC
  977105024          3
  977105027         32         Sec GPT table
  977105059          1         Sec GPT header

Is there any way of (safely) resizing this back down to something sensible, so I can reclaim the space?

A: If it hadn't been 10.11 Public Beta (2) on the main volume, I would have advised to boot to Internet Recovery Mode (IRM) (altcmdR) or a bootable thumb drive (BTD), just delete the 3rd partition with gpt remove -i 3 /dev/disk0 and fully expand the main partition with Disk Utility. After rebooting to the main volume I would have reinstalled the latest OS X (Yosemite 10.10.4 as of this writing) which recreates the Recovery HD while preserving all non-Apple apps and user-created data.
Instead you have to dd the Recovery HD from a second Mac running Yosemite. Copy the resulting file to the first Mac. Then boot Mac1 to IRM/BTD, delete the 3rd partition with gpt, reboot to IRM/BTD, resize the main volume with diskutil resizeVolume /dev/disk0s2 size, create a 3rd partition with:
 gpt add -b first_freeblock -i 3 -s 1269536 -t 426F6F74-0000-11AA-AA11-00306543ECAC /dev/disk0

and finally dd the previously made copy of Recovery HD (Mac2) back to /dev/dis0s3.
To get size in diskutil ... size you have to do some math considering that the last blocks of a Yosemite drive containing the Recovery HD usually look like this:
....                      2  GPT part - 53746F72-6167-11AA-AA11-00306543ECAC
975503592    1269536      3  GPT part - 426F6F74-0000-11AA-AA11-00306543ECAC
976773128          7
976773135         32         Sec GPT table
976773167          1         Sec GPT header

Recheck this with sudo gpt -r show /dev/disk0 on Mac2.
The example here is a 500.1 GiB (976773168 blocks à 512 B) disk.
Accordingly "size" has to be smaller than or the same size as (total blocks - 409640 - 1269576 blocks). The second term is block0 - block409639 containing PMBR, the primary GPT header and table and the EFI partition. The third term is the size of the Recovery HD and the secondary GPT header and table. Please consider that block counting starts with 0: block 0 is the the first block or block 975503592 is the 975503593rd block.
If you are to lazy to do the math, you may first create the third partition and dd the Recovery HD file and then - after a restart - expand the main volume using Disk Utility.

A second more risky method (not risky regarding your data on the main volume but I'm not sure if it is successful) is just moving the partition borders of disk0s3. This method presumes that no files of the old Recovery HD were moved "physically" on disk0s3 after deleting the Boot Camp partition with the Boot Camp assistant.
Boot to IRM/BTD and enter in Terminal:
gpt remove -i 3 /dev/disk0

and reboot to IRM/BTD. Then add a third partition with the following command (already adapted to the size of your disk!):
gpt add -b 975835488 -i 3 -s 1269536 -t 426F6F74-0000-11AA-AA11-00306543ECAC /dev/disk0

and reboot to IRM/BTD. Open Disk Utility and verify/repair the hard drive (and not the main volume!). Then enlarge the main volume to max size and verify /repair the main volume. Finally try to boot to Recovery Mode (cmdR).

A: Reference
Prepare a USB disk,
diskutil erasedisk jhfs+ Make_Recovery disk3
sudo asr restore --source /Volumes/Recovery HD/com.apple.recovery.boot/BaseSystem.dmg --target /dev/disk0s3 --erase
sudo asr adjust --target /dev/disk3s2 --settype Apple_Boot`

then delete Recovery HD partition.
Besides, you can backup BaseSystem.dmg, and restore to new partition.


text:
Q: Android - progress dialog does not close I have a ListActivity class, and when any item on the list is clicked, a new activity is displayed. The new activity takes time to load, so i would like the users to know that there is something happening (in the form of a progress dialog)
So, in order to do this, i implemented Runnable in my class like this -
public class ProtocolListActivity extends ListActivity implements Runnable {
private ProgressDialog progDialog;
....
protected void onListItemClick(ListView l, View v, int position, long id) {
                    progDialog.show(this, "Showing Data..", "please wait", true, false);

    Thread thread = new Thread(this);
    thread.start();
}
....
public void run() {
     // some code to start new activity based on which item the user has clicked.
}

Initially, when i click, and the new activity is being loaded, the progress dialog works nicely, but when i close the previous activity (to get back to this list) the progress dialog is still running. I want the progress dialog to show up only for the time the new activity is being started.
Can someone please guide me on how to do this correctly.

A: Dialogs needs to be explicitly removed by programmer (or close by user). So, it should be done in this way:
in Activity A (calling activity)
protected void onListItemClick(ListView l, View v, int position, long id) {
    progDialog.show(this, "Showing Data..", "please wait", true, false);

    Thread thread = new Thread(this){
        // Do heavy weight work

        // Activity prepared to fire

        progDialog.dismiss();
    };
    thread.start();
}

Although in most use case, the heavy work should be on the callee Activity. In case, the heavy work is done onCreate of the callee, it should be like:
Activity B (Callee):
onCreate(){
    progDialog.show(this, "Showing Data..", "please wait", true, false);

    Thread thread = new Thread(this){
        // Do heavy weight work

        // UI ready

        progDialog.dismiss();
    };
    thread.start();
}

Anyway, the idea is still the same.


text:
Q: Android gradle build failed with an exception when include firebase and gms service I just created an empty android project while including the dependencies I need for the project I got an error only when I add com.google.firebase or com.google.android.gms it will generate error below.

/Users/macbookair/Desktop/ANDROID/APPTEST/app/src/main/AndroidManifest.xml:22:18-91
  Error:    Attribute application@appComponentFactory
  value=(android.support.v4.app.CoreComponentFactory) from
  [com.android.support:support-compat:28.0.0]
  AndroidManifest.xml:22:18-91  is also present at
  [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86
  value=(androidx.core.app.CoreComponentFactory).   Suggestion: add
  'tools:replace="android:appComponentFactory"' to  element
  at AndroidManifest.xml:5:5-21:19 to override.

Please can anyone help me out, I have be trying for very long time to fix this error.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.fexample.android.appz"
        minSdkVersion 18
        targetSdkVersion 28
        versionCode 2
        versionName "2.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'org.apache.httpcomponents:httpcore:4.4.10'
    implementation 'com.squareup.okhttp3:okhttp:3.13.1'
    implementation 'com.facebook.android:facebook-login:4.41.0'

     //If I uncomment the below line it will trigger error
    //implementation 'com.google.android.gms:play-services-safetynet:17.0.0'
    //implementation 'com.google.android.gms:play-services-auth:17.0.0'
    //implementation 'com.google.firebase:firebase-core:17.2.0'
    //implementation 'com.google.firebase:firebase-messaging:20.0.0'

}
android {
    useLibrary 'org.apache.http.legacy'
}
apply plugin: 'com.google.gms.google-services'

android { sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/public'] } } }

From the below screenshot this implementation 'com.android.support:appcompat-v7:28.0.0' also has an error but when I build apk it create successfully, I don't think is good.

Dependencies using groupId com.android.support and androidx.* can not
  be combined but found
  IdeMavenCoordinates{myGroupId='com.android.support',
  myArtifactId='support-fragment', myVersion='28.0.0', myPacking='aar',
  myClassifier='null'} and
  IdeMavenCoordinates{myGroupId='androidx.swiperefreshlayout',
  myArtifactId='swiperefreshlayout', myVersion='1.0.0', myPacking='aar',
  myClassifier='null'}

A: I'll suggest you try one of the following:
1) Migrate the whole project to use the androidx libraries which you can do under Refactor > Migrate to AndroidX from the menu bar.
2) Downgrade the versions of com.google.firebase and com.google.android.gms from 17.x.x to a lower version


text:
Q: How to avoid duplicating business logic across multiple different presentation layers I am currently designing the architecture for an multi-channel commerce system which will have multiple different frontend presentations which are tailored to device and channel (user type and location). The challenge I'm facing is how to best ensure we are developing the core commerce platform in a way that reduces duplication in the frontend presentation tiers.
Here is a sampling of the different frontend presentations tiers we will need to support:

*

*Traditional desktop based website for consumer

*Mobile optimized website for consumer

*Native mobile applications (iOS/Android) for consumer

*Customer Support Center website for customer support representatives

*Instore kiosk based website for consumers shopping in brick-mortar locations

*Other (microsites and other utilizing various technologies such as Angular, PHP, .NET, etc)

Now, I know the best practices around a layered architectures (presentation, business, data tiers) and common design patterns to address frontend challenges within a single app (such as MVC, validators, interceptors). However, none of these principles explain how and where to best encapsulate your presentation specific business logic when faced with supporting multiple frontends.
So, my question is what are some good practices and principles to follow when developing such a system to ensure each frontend application is not duplicating frontend business logic?
I have developed many applications with requirements like this in the past using different approaches...some of which worked fairly well and some which worked not so great. But each time I felt like I was inventing a solution for a common problem and that there must be some best practices and principles to leverage.
A Quick example of the specific challenges I am asking about
All of our frontend applications must support the ability to register a new customer account. The registration form will take in information such as email, password, and customer address information (street, city, zip, etc). When the form is submitted there will be certain trivial and non-trivial validations that need to occur before the account is created in the system and a verification email is sent to the user. For example:

*

*Email address pattern validation rules

*Ensuring the email address doesn't exist in the system

*Password complexity rules

*Address validation (via third party address validation/standardization system)

For the most part, these validations rules need to be enforced across all frontend systems, though each frontend's registration flow might be slightly different and might only contain a subset of the fields. So, what are some good practices to provide an API to the frontends such that each frontend does not duplicate the various steps required to properly validate and process the registration? For example, if we decide to change the password complexity rules or address validation rules, etc - how, might we best design the system such that we will not have to go out and change all the various frontend applications with this new validation logic.
Just to be clear, I'm not concerned about where to put core business logic which is shared across all frontends (i.e. account creation services, address validation services, account lookup services, etc). Those patterns are commonly discussed in blogs, books, and forums. My questions are specifically related to the business logic which is commonly tightly coupled to the presentation tier. Some questions that always come to my head.

*

*Should we provide a presentation service layer which supports all frontend operations including form validations and processing via web services? Or should each frontend owns it's presentation logic because "no two frontends are alike"?

*If we do create a presentation service layer, how do we provide services which address the subtle differences of each frontend? Do we provide different services/endpoints for each of these frontends or provide simply have different 'contexts' that each frontend passes when they invoke our services?

*Does this presentation service layer control the error messaging and return the appropriate contextually aware message to each frontend, or should we just pass back error codes and let the frontend own this?

*etc

A: There is no magic way of having consistent validation rules across all of yours frontends, especially if you're mixing different technologies and environments (PHP, JS, native apps). If your validation rules are complex, the code implementing it will always be complex.
What you can do is to make your validation a core functionality. You can get rid of all validation in the presentation layers and move it to the common application layer used by all frontends. This way your presentation will just a have a form and send it to the server to get validation errors while the user is filling the form. This could be done using AJAX from web or REST API call from native app. If done right user experience won't be compromised.
There is always a trade off in such cases: you'll spend less time on maintaining the validation code at the cost of slightly worse responsivenes and/or user experience.

A: If I understood your question properly, I'd do like this:
Use the Strategy pattern to implement each of presentations according to the abstraction. Use a Factory to instantiate your concrete strategies. Use MVC to separate your tiers, and use Observer to update your strategies in your view layer.
Hope it helps.