text:
Q: How much overhead is usual while distributing processing?
For impatient readers: this is a work in progress, where I ask for
  help, during the process. Please do not judge the tools by my
  temporary data, as they can change while I try to get better results.

We are in the middle of the decision process on the architecture for a tool to analyse the output from co-simulations.
As part of that process I was asked to write a benchmark tool, and get data on the speeds of several distributed processing frameworks.
The frameworks I tested are: Apache Spark, Apache Flink, Hazelcast Jet. And as a comparison baseline plain Java.
The test case I used was a simple "here is a list of Pojos, with one field in the pojo a double value. Find the smallest(min) value".
Simple, straightforward and hopefully highly comparable.
Three out of four tests use a simple comparator, the fourth (flink) uses a reducer that is basically identical to the comparators. The analysing functions look like this:
Java: double min = logs.stream().min(new LogPojo.Comp()).get().getValue();

Spark: JavaRDD<LogPojo> logData = sc.parallelize(logs, num_partitions);
double min = logData.min(new LogPojo.Comp()).getValue();

Hazel: IStreamList<LogPojo> iLogs = jet.getList("logs");
iLogs.addAll(logs);
double min = iLogs.stream().min(new LogPojo.Comp()).get().getValue();

Flink: DataSet<LogPojo> logSet = env.fromCollection(logs);
double min = logSet.reduce(new LogReducer()).collect().get(0).getValue();

I tested this extensively, varying the size of the test list as well as the allocated ressources. And the results blew my mind. The BEST results can be seen below (all numbers in ms, 1 mio pojos, 10 tests each):

*

*instances: how long it took to to declare and initiate the instance
of the frameworks

*list: how long it took to parse/transfer the
List to the frameworks "list"

*process: how long it took to
process the data to retrieve the min

*overall: from start to end of
each test

Outcome:
java:
Instances:
List:
Process: 37, 24, 16, 17, 16, 16, 16, 16, 16, 16,
Overall: 111, 24, 16, 17, 16, 16, 16, 16, 16, 16,

spark:
Instances: 2065, 89, 62, 69, 58, 49, 56, 47, 41, 52,
List: 166, 5, 1, 1, 2, 1, 0, 0, 0, 0,
Process: 2668, 2768, 1936, 2016, 1950, 1936, 2105, 2674, 1913, 1882,
Overall: 4943, 2871, 2011, 2094, 2020, 1998, 2172, 2728, 1961, 1943,

hazel:
Instances: 6347, 2891, 2817, 3106, 2636, 2936, 3018, 2969, 2622, 2799,
List: 1984, 1656, 1470, 1505, 1524, 1429, 1512, 1445, 1394, 1427,
Process: 4348, 3809, 3655, 3751, 3927, 3887, 3592, 3810, 3673, 3769,
Overall: 12850, 8373, 7959, 8384, 8110, 8265, 8133, 8239, 7701, 8007

flink:
Instances: 45, 0, 0, 0, 0, 0, 0, 0, 0, 0,
List: 92, 35, 16, 13, 17, 15, 19, 11, 19, 24,
Process: 34292, 20822, 20870, 19268, 17780, 17390, 17124, 19628, 17487, 18586,
Overall: 34435, 20857, 20886, 19281, 17797, 17405, 17143, 19639, 17506, 18610,

The most interesting parts are:

*

*the best results ALL come from purely local tests (one instance)

*any tests that made use of distributed mechanics (additional nodes and such), were up to an order of magnitude slower still (spark for example 2.5 slower if distributed).

Now don't get me wrong, it's basic logic that distributed processing has to be slower per core than mono-threaded processing.
But 2 orders of magnitude EVEN if used on a mono-thread? And 3 orders of magnitude if distributed? Can someone see the mistake I apparently made in all 3 distributed processes? I expected some factor < 10, so killing it with more hardware would be an option.
So is there some way to reduce the overhead of those frameworks to, hmm maybe x9 instead of x999?
I know I know, the test data I use is much to small, but even if scaling it up, I haven't seen any reduction in overhead vs. performance. And it's roughly the size of the batches of data we need to analyse (0.1M - 1M objects/s per simulation). So your help to find my error is welcome. :D
UPDATE Spark:
After some more thorough testing on Spark, I'm still not impressed. The setup was as follows:
java client on one machine in a 64 core, 480 GB RAM job
master and 7 slaves on a separate rack, 32 cors, 20 GB each
    1 mio objects, 256 tasks, 64 cpus local[*]
    java:
      Instances:
      List:
      Process: 622, 448, 68, 45, 22, 32, 15, 27, 22, 29,
    spark:
      Instances: 4865, 186, 160, 133, 121, 112, 106, 78, 121, 106,
      List: 310, 2, 2, 1, 2, 4, 2, 1, 2, 1,
      Process: 8190, 4433, 4200, 4073, 4201, 4092, 3822, 3852, 3921, 4051,

    10 mio objects, 256 tasks, 64 cpus local[*]
    java:
      Instances:
      List:
      Process: 2329, 144, 50, 65, 75, 70, 69, 66, 66, 66,
    spark:
      Instances: 20345,
      List: 258, 2, 1, 1, 1, 4, 1, 1, 1, 1,
      Process: 55671, 49629, 48612, 48090, 47897, 47857, 48319, 48274, 48199, 47516

    1 mio objects, 5.2k tasks, 64 cpus local, 32 cpus each on 1+1 Spark machines (different rack)
    java:
      Instances:
      List:
      Process: 748, 376, 70, 31, 69, 64, 46, 17, 50, 53,
    spark:
      Instances: 4631,
      List: 249, 1, 2, 2, 3, 3, 1, 1, 2, 1,
      Process: 12273, 7471, 6314, 6083, 6228, 6158, 5990, 5953, 5981, 5972

    1 mio objects, 5.2k tasks, 64 cpus local, 32 cpus each on 7+1 Spark machines (different rack)
    java:
      Instances:
      List:
      Process: 820, 494, 66, 29, 5, 30, 29, 43, 45, 21,
    spark:
      Instances: 4513,
      List: 254, 2, 2, 2, 2, 4, 2, 2, 1, 1,
      Process: 17007, 6545, 7174, 7040, 6356, 6502, 6482, 6348, 7067, 6335

    10 mio objects, 52k tasks, 64 cpus local, 32 cpus each on 7+1 Spark machines (different rack)
    java Process: 3037, 78, 48, 45, 53, 73, 72, 73, 74, 64,
    spark:
      Instances: 20181,
      List: 264, 3, 2, 2, 1, 4, 2, 2, 1, 1,
      Process: 77830, 67563, 65389, 63321, 61416, 63007, 64760, 63341, 63440, 65320

    1 mio objects, 224*i tasks, 64 cpus local, 32 cpus each on 7+1 Spark machines (different rack), i =0 to 100
    java Process: 722, 631, 62, 26, 25, 42, 26, 11, 12, 29, 40, 16, 14, 23, 29, 18, 14, 11, 71, 76, 37, 52, 32, 15, 51, 54, 19, 74, 62, 54, 7, 60, 37, 54, 42, 3, 7, 60, 33, 44, 50, 50, 39, 34, 34, 13, 47, 63, 46, 4, 52, 20, 19, 24, 6, 53, 4, 3, 68, 10, 59, 52, 48, 3, 48, 37, 5, 38, 10, 47, 4, 53, 36, 41, 31, 57, 7, 64, 45, 33, 14, 53, 5, 41, 40, 48, 4, 60, 49, 37, 20, 34, 53, 4, 58, 36, 12, 35, 35, 4,
    spark:
      Instances: 4612,
      List: 279, 3, 2, 1, 2, 5, 3, 1, 1, 1, 2, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 0, 2, 1, 1, 1, 1, 1, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
      Process: 16300, 6577, 5802, 6136, 5389, 5912, 5885, 6157, 5440, 6199, 5902, 6299, 5919, 6066, 5803, 6612, 6120, 6775, 6585, 6146, 6860, 6955, 6661, 6819, 6868, 6700, 7140, 7532, 7077, 7180, 7360, 7526, 7770, 7877, 8048, 7678, 8260, 8131, 7837, 7526, 8261, 8404, 8431, 8340, 9000, 8825, 8624, 9340, 9418, 8677, 8480, 8678, 9003, 9036, 8912, 9235, 9401, 9577, 9808, 9485, 9955, 10029, 9506, 9387, 9794, 9998, 9580, 9963, 9273, 9411, 10113, 10004, 10369, 9880, 10532, 10815, 11039, 10717, 11251, 11475, 10854, 11468, 11530, 11488, 11077, 11245, 10936, 11274, 11233, 11409, 11527, 11897, 11743, 11786, 11086, 11782, 12001, 11795, 12075, 12422

    2 mio objects, 224*i tasks, 64 cpus local, 32 cpus each on 7+1 Spark machines (different rack), i = 0 to 30
    java Process: 1759, 82, 31, 18, 30, 41, 47, 28, 27, 13, 28, 46, 5, 72, 50, 81, 66, 44, 36, 72, 44, 11, 65, 67, 58, 47, 54, 60, 46, 34,
    spark:
      Instances: 6316,
      List: 265, 3, 3, 2, 2, 6, 1, 2, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 2, 1, 1, 5, 1, 1, 1, 1, 2, 1, 1, 1,
      Process: 24084, 13041, 11451, 11274, 10919, 10972, 10677, 11048, 10659, 10984, 10820, 11057, 11355, 10874, 10896, 11725, 11580, 11149, 11823, 11799, 12414, 11265, 11617, 11762, 11561, 12443, 12448, 11809, 11928, 12095

    10 mio objects, 224*i tasks, 64 cpus local, 32 cpus each on 7+1 Spark machines (different rack), i = 5 to 30
    java Process: 1753, 91, 57, 71, 86, 86, 151, 80, 85, 72, 61, 78, 80, 87, 93, 89, 70, 83, 166, 84, 87, 94, 90, 88, 92, 89, 196, 96, 97, 89,
    spark:
      Instances: 21192,
      List: 282, 3, 2, 2, 3, 4, 2, 2, 1, 0, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1,
      Process: 60552, 53960, 53166, 54971, 52827, 54196, 51153, 52626, 54138, 51134, 52427, 53618, 50815, 50807, 52398, 54315, 54411, 51176, 53843, 54736, 55313, 56267, 50837, 54996, 52230, 52845

Results: no matter how much hardware was thrown on it, and how the tasks where clustered, it took 5-6 seconds per million pojos in the list using spark.
Java on the other hand dealed with the same amount taking 5-30 ms. So basically a factor of 200-1,000.
Does anyone have a suggestion how to "speed up" Spark for such a simple job?
UPDATE Hazel:
Now I'm starting to get impressed. While I'm still fighting with some weird problems, at least Hazelcast Jet seems to understand that local data can be processed locally if possible. With only 100% (factor x2) overhead, which is completely acceptable.
10 mio objects
java:
   Instances:
   List: 68987,
   Process: 2288, 99, 54, 52, 54, 64, 89, 83, 79, 88,
hazel:
  Instances: 6136,
  List: 97225,
  Process: 1112, 375, 131, 123, 148, 131, 137, 119, 176, 140

UPDATE Flink:
Dropped it from the benchmarking for now, as it's causing too much trouble without giving great results.
EDIT: The whole benchmark can be found under: https://github.com/anderschbe/clusterbench
The cluster setup for spark uses spark-2.1.0-bin-hadoop2.7 as it comes out of the box. With one minor change in spark_env.sh : SPARK_NO_DAEMONIZE=true
the only change necessary to make it work on the cluster is replacing "localhost" in SparcProc line 25 with "spark://I_cant_give_you_my_cluster_IP.doo"

A: When you are calculating something in cluster framework, like Spark or Flink, framework:

*

*serializes your code

*send resource request

*send your code via network

*schedule execution

*wait for result

As you can see, there are many steps peformed - not only your calculation! Distributed computing make sense if you:

*

*can split your calculation to small tasks, which can be done in parallel

*have too much data to be processed on one machine or processing on one machine can be too slow - disk I/O, some other specific factors in project OR  calculations are very specific and requires many CPUs, more than one machine usually have - but then calculation of one part of the data must be very long

Try to calculate maks occurence count of words in 10 GB text file - then Spark and Flink will beat one-node Java
Sometimes user code may cause slowness of distributed computing. Typical mistakes:

*

*user writes lambdas in clasess with many references - all other classes are serialized, serialization takes much time

*tasks are not really parallel - they must wait for each other or must proceed on large part of data

*data skewness - objects may have inproper hashCode implementation and HashPartitioner causes that all data wents to one partition = one node

*incorrect number of partition - you can add 1000 more machines, but if you still have 4 partitions, then you can archive at most 4 parallel tasks in one time

*too much network communication - in you case it's not a problem, but sometimes user are doing a lot of join and reduce
EDIT After Question edit:
In your example, Spark runs on local - which means 1 thread only! Use at least local[*] or other cluster manager. You've got overheads listed in this answer and only one thread


text:
Q: Putnam 1985 B5 Integration by Substitution Putnam 1985 B5: Evaluate $\int_{0}^\infty t^{-1/2}e^{-1985(t+t^{-1})}dt$. You may assume that $\int_{-\infty}^\infty e^{-x^2} dx=\sqrt{\pi}$.
Following the solution on https://artofproblemsolving.com/community/c1860h1093626s3_1985_putnam_b5, I arrive at the conclusion that $I=2e^{-3970}\int_{0}^\infty e^{-1985{(u-u^{-1})}^2}du$, where $u=\sqrt{t}$. Another expression for $I$ is that, $I=2e^{-3970}\int_{0}^\infty (\frac{1}{v^2})e^{-1985{(v-v^{-1})}^2}dv$, where $u=v^{-1}$. The writer then goes on to claim that, by taking the average of these two equations for $I$, and by reverting the variables back to $x$, one gets $I=e^{-3970}\int_{0}^\infty (1+\frac{1}{x^2})e^{-1985{(x-x^{-1})}^2}$. This is precisely where I lose track of the proof: I understand the idea of taking the average to get $e^{-3970}$ but I cannot understand his idea of reverting variables back to $x$ (why not $t$?) and how this process is done. Any help would be much appreciated.
Thank you.
EDIT: I have managed to now solve this problem myself case closed :)

A: This is a classic technique in the evaluation of definite integrals, which takes advantage of the fact that the value of a definite integral does not depend on the variable used in it, since it has a constant value. Hence,
$$\int_a^b f(x)dx =\int_a^b f(u)du=\int_a^b f(ñ)dñ=...$$
And the variable (often referred to as a "dummy variable") does not matter, just as the index of a sum does not affect its value:
$$\sum_{i=a}^b f(i)=\sum_{j=a}^b f(j)$$
Furthermore, if a substitution $x\to g(u)$ does not affect the bounds of the integral so that
$$\int_a^b f(x)dx=\int_a^b f(g(u))g'(u)du$$
We may write tha second integral also in terms of $x$, since the $u$ is just a "dummy variable", and average the two integrals to get
$$\int_a^b \frac{f(x)+f(g(x))g'(x)}{2}dx $$
Then we may (in problems like the one you proposed) make use of some clever cancellation or functional equation that causes the integrando to turn into something manageable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Чат-Бот VK C#, парсинг страницы Привет, задача такая. Добавляю бота в конференцию и пишу.
"Бот, погода"
Он мне выводит цифру с сайта(на самом деле другая инфа нужна, но неважно)
Ничего более, только одна команда и одна цифра
Что мне для этого изучить?
Я уже создал прилоение в вк, Настроил oauth, корректно возвращает access token.
Но дальше не знаю, как быть.
Но в идеале не хотелось бы не использовать бота, а использовать мой аккаунт. То есть мне пишут "Михаил, погода" и я автоматом выдаю погоду. Так возможно?

A: Да Михаил такое возможно.
1 шаг: API работы с погодой
Есть много сервисов работающии с API погодой (парсить html не придеться) есть платные, есть бесплатные. Вот 1 из них https://tech.yandex.ru/weather/
Одной проблемой меньше.
2 шаг: VK API прием сообщения
Если вы собираетесь реализовать бота средствами C# то знайте, сообщения приходят в неправильной кодировке. Вот я раньше писал бота и также задавал вопрос на форуме
Проблема с кодировкой C#
С кодировкой разобрались, теперь как принимать сообщения:
private string messagesGet(int count, string version)
    {
        string url = ("https://api.vk.com/method/messages.get?count=" + count + "&access_token=" + token + "&v=" + version);
        WebClient client = new WebClient();
        client.Encoding = Encoding.UTF8;
        var json = client.DownloadString(url);
        return json;
    }

Вот функция она вернет вам ответ сервера в формате {respone: бла бла бла}
Это все вам предеться перепарсить.
Для этого рекомендую использовать одинаковую версию при запроссе messagesGet и наисать собственную функцию которая принимала ответ сервера (Json) в String формате и возвращала само сообщение и id пользователя. Для реализации этой функтии понадобиться много строковых массивов и работа с разделением строку на массив. Поэтому прочитайте это.
https://msdn.microsoft.com/ru-ru/library/b873y76a(v=vs.100).aspx
Вот моя версия парсинга сообщения, но если вернеться ошибка или сообщение будет содиржать " то бот будет работать  не стабильно, рекомендую не использавать мои наработки :D
private string[] messagesGetParse(string json)
    {
        string uid, body;
        string[] massiv = json.Split(':');
        string a = massiv[8];
        string[] arrayA = a.Split('"');
        body = arrayA[1];
        string[] arrayB = massiv[5].Split(',');
        uid = arrayB[0];
        return new string[] { uid, body };
    }

3 шаг: VK API отправка сообщения
Тут все такде как и с получением сообщения только метод другой, и парамметры.
Вот мои наработки)))
Это для отправки обычного сообщения
private void messagesSend(string user_id, string message)
    {
        string url = ("https://api.vk.com/method/messages.send?user_id=" +
        user_id + "&message=" + message + "&access_token=" + token);
        WebClient client = new WebClient();
        client.Encoding = Encoding.UTF8;
        var json = client.DownloadString(url);
    }

Если же вы хотите отправить стикер то нужно перегрузить этот метод
http://mycsharp.ru/post/37/2014_02_04_peregruzka_metodov_v_si-sharp.html
Интересная статья про перегрузку)
Вот как это сделал я:
private void messagesSend(string user_id, int sticker_id)
    {
        string url = ("https://api.vk.com/method/messages.send?user_id=" +
        user_id + "&sticker_id=" + sticker_id + "&access_token=" + token);
        WebClient client = new WebClient();
        client.Encoding = Encoding.UTF8;
        var json = client.DownloadString(url);
    }

Вот и всё осталось найти хороший сервис для работы с погодой средствами API.
Удачи, надеюсь что я писал это все не зря.
Обьяснял подробно, ну если новички читать будут)


text:
Q: How to change schema name on executing LINQ query? I have a cache with one QueryEntity created as
ignite.CreateCache<long, MyEntity>(new CacheClientConfiguration("myEntityCache", queryEntity)
            {
                SqlSchema = "MYSCHEMA"
            });

And I'm trying to execute LINQ query against this cache
var result = cache
                .AsCacheQueryable()
                .Select(x => x.Value)
                .Where(predicate)
                .ToList();

But I get an error

'Failed to parse query. Schema "myEntityCache" not found; SQL statement:
  select _T0._VAL from "myEntityCache".MYENTITY as _T0 where ? [90079-195]'

Schema name should be equal to "MYSCHEMA" but instead ignite uses cache name which doesn't match with schema.
I didn't find any option how to specify schema name, so the question is how to fix this?

A: I have checked this and can confirm that there is a bug. SqlSchema is simply ignored when generating SQL from LINQ.
Ticked filed: https://issues.apache.org/jira/browse/IGNITE-9116
The fix seems to be trivial and you can expect it in the next release.
There is no apparent workaround.


text:
Q: Is there a way to communicate from a browser to a desktop or a console application without using extensions? I tried googling but couldn't find anything, any help is appreciated.
What I had before was a console application that sent information to the chrome or firefox extension, but I am trying to find a solution that would send information to the browser and back to the console app, without the hassle of installing a browser extension.


text:
Q: Nil while unwrapping an Optional value but, during print the value exist I have a strange situation in my TableViewController when I want to set up picture in m cell. My cell class is:

class TableViewCell

class TableViewCell: UITableViewCell {

/* OUTLETS */

@IBOutlet weak var pictureInRowOutlet: UIImageView!
@IBOutlet weak var postDataOutlet: UILabel!
@IBOutlet weak var titleOutlet: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization cod
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    // Configure the view for the selected state
}
}//end of class

class MyTableView

class MyTableView: UITableViewController{

var data:[[String:String]]? // data load from serwer

//code we don't need

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell

// now I want to set up picture in row

let urlAdressPhoto = (data?[indexPath.item]["picture"])!
// here, when I print urlAdressPhote I see correct value as String

cell.pictureInRowOutlet.image = UIImage(data: NSData(contentsOfURL: NSURL(string: urlAdressPhoto)!)!)
 // in this moment I recive an information about "unexpectedly found nil while unwrapping an Optional value".

return cell

}

Can somebody tell my why and how to solve this problem?

A: You force unwrap at least 3 different things. In this line,
let urlAdressPhoto = (data?[indexPath.item]["picture"])!

you force unwrap (data?[indexPath.item]["picture"]) and you get lucky. It's not nil. You gambled and won.
Perhaps intoxicated by your success, you decide to double down...here, you force unwrap twice in a single statement:
UIImage(data: NSData(contentsOfURL: NSURL(string: urlAdressPhoto)!)!)

Wow! That means that if NSURL(string: urlAdressPhoto) is nil, your program will crash. Or, if it is not nil, but the call to NSData is nil, then your program will crash.
The lesson is, and I can't say this often enough: Don't use the ! as a matter of convenience. It blows up your code. While there are occasional good reasons to use it, most people use it because they are too lazy to unwrap. And then they get the unexpectedly found nil while unwrapping an Optional value.
I would venture that that is the most common Swift-related question on Stack Overflow. There must be about 10 questions a day related to that error message, and it is all because people insist, for reasons that are totally beyond me, on using !.
Try this:
guard let urlAdressPhoto = (data?[indexPath.item]["picture"])
    , let url = NSURL(string: urlAdressPhoto)
    , let data = NSData(contentsOfURL: url) else {
        print("Something failed to unwrap..."); return cell
    }

cell.pictureInRowOutlet.image = UImage(data: data)


text:
Q: On Change event not firing in Partial View DropdownList I have a Partial View that contains a DropdownList and a Label. The initial value of the Label is blank and the Dropdown says "Select option". I have a script at the bottom of the Partial View to handle the On Change event of teh dropdown list but it never gets fired. I have put a breakpoint at the start of it but the IDE just shows that this breakpoint will never be hit.
Code for Partial View:
@*model IEnumerable<ArdentTestv6.Repositories.SelectProjectTypes_Result>*@
@*model ArdentTestv6.Repositories.ProjectListEntities*@

@Html.DropDownList("ProjTypeName",
(IEnumerable<SelectListItem>)ViewBag.ptName, "Select option", new {
@id="pType" })

When the Parent View is loaded the Dropdown is populated and rendered correctly. The HTML Source code for the Rendered Parent View as follows:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create - My ASP.NET Application</title>
<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

Home

About

Contact

Projects

Housekeeping

<form action="/ProjectLists/Create" method="post">

Create New Project

        Project Type

<select id="pType" name="ProjTypeName"><option value="">Select option</option>
<option value="1">DCO</option>
<option value="2">CPO</option>
<option value="3">TWA</option>
</select>

        ProjectReference

            <input class="form-control text-box single-line" id="ProjectReference" name="ProjectReference" type="text" value="" />

        ProjectName

            <input class="form-control text-box single-line" id="ProjectName" name="ProjectName" type="text" value="" />

        ProjectDescription

            <input class="form-control text-box single-line" id="ProjectDescription" name="ProjectDescription" type="text" value="" />

        ProjectManager

            <input class="form-control text-box single-line" id="ProjectManager" name="ProjectManager" type="text" value="" />

        DateStart

            <input class="form-control text-box single-line" data-val="true" data-val-date="The field DateStart must be a date." id="DateStart" name="DateStart" type="datetime" value="" />

        DateCompleted

            <input class="form-control text-box single-line" data-val="true" data-val-date="The field DateCompleted must be a date." id="DateCompleted" name="DateCompleted" type="datetime" value="" />

            <input type="submit" value="Create" class="btn btn-default" />

</form>

Back to List

© 2018  - Logged in as Ardent-HP\Ardent


text:
Q: OneSignal Get Player Id I'm doing an app for a homework in my school and I'm using Onesignal REST API, but I want to save the player id in my database to use it in another application like a server sender. My application is in intel xdk and I'm using Cordova to build on Android. The problem is that I can't find any example getting the player id. Can anybody help me with this problem ?
I'm using JavaScript
Thanks.
this is what I have in my .js :
document.addEventListener('deviceready', function () {

  var notificationOpenedCallback = function(jsonData) {
    console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
  };

  window.plugins.OneSignal
    .startInit("XXXXXX-XXXX-XXX-XXXX-XXXXXXXXX") // <- api id
    .handleNotificationOpened(notificationOpenedCallback)
    .endInit();

  OneSignal.push(function() {
    OneSignal.getUserId(function(userId) {
      console.log("OneSignal User ID:", userId);
    });

    OneSignal.getUserId().then(function(userId) {
      console.log("OneSignal User ID:", userId);
    });
  });
}, false);

A: Here's a working code snippet:
window.plugins.OneSignal
    .startInit("YOUR-APP-ID")
    .handleNotificationOpened(notificationOpenedCallback)
    .endInit();

window.plugins.OneSignal.getPermissionSubscriptionState(function(status) {
    idapp = status.subscriptionStatus.userId;
});

A: Add this block of code after the endInit() method:
        window.plugins.OneSignal.getIds(function(ids) {
            // Player ID will be available at the object ids.userId
        });

Here's a complete example on how you can display the player ID in an alert!
        document.addEventListener('deviceready', function () {

            // Enable to debug issues.
            // window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});

            var notificationOpenedCallback = function(jsonData) {
                console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
            };

            window.plugins.OneSignal
                .startInit("YOUR_APP_ID_HERE")
                .handleNotificationOpened(notificationOpenedCallback)
                .endInit();

            window.plugins.OneSignal.getIds(function(ids) {
                alert("player id: " + ids.userId);
            });

        }, false);

Don't forget to replace YOUR_APP_ID_HERE by your real app id.

A: OneSignal prototype provides a function getIds which gives the player id and push token for the current device.
window.plugins.OneSignal
    .startInit("XXXXXX-XXXX-XXX-XXXX-XXXXXXXXX") <- api id
    .getIds(function(userDetails) {
        console.log(userDetails.userId); // Player ID
        console.log(userDetails.pushToken);
    })
    .endInit();

https://documentation.onesignal.com/docs/cordova-sdk#section--postnotification-

A: after installing oneSignal plugin, you can get a player id using this function in the console.
await OneSignal.getUserId();

https://documentation.onesignal.com/docs/users-and-devices#finding-users

A: In order to debug I use this snippet:
console.log("Site notification permission: ", await OneSignal.getNotificationPermission());
console.log("Push enabled: ", await OneSignal.isPushNotificationsEnabled());
console.log("Player id: ", await OneSignal.getUserId());


text:
Q: Room DB error ,Task :app:kaptDebugKotlin FAILED error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.
kotlin.coroutines.Continuation<? super java.lang.Long> continuation);
^
error: Not sure how to handle insert method's return type.
public abstract java.lang.Object insertBillProduct(@org.jetbrains.annotations.NotNull()
I build, rebuild, cleaned my project, invalidate cache and restart but nothing worked

A: Check your BillProduct to see if it is notated with @Entity or not. Also check other method in your DAOs to make sure all the parameters typed is notated with @Entity


text:
Q: How can I pass PHP variable through curl 'CURLOPT_POSTFIELDS ' dynamically I want to dynamically sent the phone number (toNumber variable) CURLOPT_POSTFIELDS to field, How can I pass this $toNumber in CURLOPT_POSTFIELDS to:"" field? Advanced thanks .....
$mobileNumber = "002233245"; //its example phone number
$prefixCode = "880";
$toNumber = $prefixCode.$mobileNumber;

//now sent message
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.sms.to/v1/sms/send",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>'{"body": "Dear customer, Your application success.","to": "Here_I_want_to_use_dynamically_phoneNumber_variable this $toNumber here","sender_id": "Bank","callback_url": "mydomain.com"}',
CURLOPT_HTTPHEADER => array(
      "Authorization: Bearer code",
      "Accept: application/json",
      "Content-Type: application/json"
 ),
));

A: Build the post data in a normal array with the appropriate data...
$postData = [ "body" => "Dear customer, Your application success.",
    "to" => $toNumber,
    "sender_id" => "Bank",
    "callback_url" => "mydomain.com"
];

pass a json_encoded string to the post fields (update this line)...
CURLOPT_POSTFIELDS => json_encode($postData),


text:
Q: How to use factor analysis results to classification? After performing factor analysis by R as below, I get the results.
PCAVar <- principal(Corr, nfactors=7, rotate="varimax")

Below are all objects I can get:
names(PCAVar)

[1] "values"       "rotation"     "n.obs"        "communality"  "loadings"     "fit"          "fit.off"
[8] "fn"           "Call"         "uniquenesses" "complexity"   "chi"          "EPVAL"        "R2"
[15] "objective"    "residual"     "rms"          "factors"      "dof"          "null.dof"     "null.model"
[22] "criteria"     "PVAL"         "weights"      "r.scores"     "rot.mat"      "Structure"

I want to use these factors in classifications. However, I do not know how to load factors to my training dataset.


text:
Q: Cannot add constraint check with function call in Mariadb I am using Mariadb 10.4.10 on Ubuntu 18.04, and the tool client is DBeaver 6.2.5
I want to make full use of the Constraint Check feature in Mariadb to ensure data integrity, since it is enforced starting from 10.2.1.
However, whenever I try to add a new constraint into an existing table, it gives me an error.
The query I tried is something like this:
ALTER TABLE mydb.users ADD CONSTRAINT `username_minlen`
  CHECK (CHAR_LENGTH(username) >= 6);

and the error message is like this:

SQL Error [4025] [23000]: (conn=47) CONSTRAINT username_minlen failed for mydb.users

My guess is that that CHAR_LENGTH is the cause of the problem, because when I ran the query like this one:
ALTER TABLE mydb.users ADD CONSTRAINT `username_no_empty_str`
  CHECK (username <> '');

this worked just fine.
I was wondering if I cannot call at all any function or procedure inside the CHECK expression, but googling on this showed me no satisfactory answers, most of them relating to other SQL systems than Mariadb.
Is calling functions syntactically impossible in Mariadb?

A: You should first check if you have data that violates it:
SELECT *
FROM `mydb`.`users`
WHERE CHAR_LENGTH(username) < 6;

Then update it:
UPDATE `mydb`.`users`
SET username = ?
WHERE CHAR_LENGTH(username) < 6;

And finally apply check constraint:
ALTER TABLE mydb.users ADD CONSTRAINT `username_minlen` CHECK (CHAR_LENGTH(username) >= 6);


text:
Q: how to pass parameters from main activity to custom view As this answer,
I need to pass a value from my main Activity to a custom View.After clicked a button, the createBall() will be called.And then pass the values to custom view.But after I click the button I get this error.
com.example.ball E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ball, PID: 12141
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.ball.customView.fresh(int, int, int)' on a null object reference

here is my MainActivity
public class MainActivity extends AppCompatActivity {

    private WindowManager wml;
    private customView myCus;
...
    private void createBall(int radius) {

        if (radius > 150) return;
        WindowManager wm1 = this.getWindowManager();
        int width = wm1.getDefaultDisplay().getWidth();
        int height = wm1.getDefaultDisplay().getHeight();
        myCus.fresh(width, height, radius);

    }
}

here is my custom view
...
public void fresh(int width, int height, int r) {
    radius = (int)r;
    x = (int)Math.random() * (width - radius * 2);
    y = (int)Math.random() * (height - radius * 2);
...
    invalidate();
}

Can you fix it for me, thx.

A: You must first create your view and then use its instance. your object of custom view is null
It's best to get an instance of the custom view from the Java code and add it to the root view of the layout using the addView() function. then call fresh on this object


text:
Q: SQL Server : convert varchar to numeric with sign at the end I have a varchar value like this:
DECLARE @TestConvert VARCHAR(MAX) = '1234.94-'

And I want to convert this value to a decimal(5,2) likes this:
SELECT CAST(@TestConvert AS DECIMAL(18, 4))

The problem is the sign at the end of the value.
If the sign is at the beginning like this:
DECLARE @TestConvert VARCHAR(MAX) = '1234.94-'

I have no problem. Is there any solution or workaround for this?
Thanks.

A: For SQL2012 and above PARSE will handle this. (My test box is running 2016 so apologies if this doesn't work for you)
DECLARE @TestConvert VARCHAR(MAX) = '1234.94-'
SELECT PARSE(@TestConvert AS  DECIMAL(18, 4)) AS Converted

Converted
---------------------------------------
-1234.9400

(1 row(s) affected)

PARSE documentation https://msdn.microsoft.com/en-us/library/hh213316(v=sql.110).aspx
and related
TRY_PARSE https://msdn.microsoft.com/en-us/library/hh213126(v=sql.110).aspx

A: Try this:
  DECLARE @TestConvert VARCHAR(MAX) = '1234.94-'
  SELECT CAST((RIGHT(@TestConvert,1)+LEFT(@TestConvert,LEN(@TestConvert)-1)) as DECIMAL(18,4))

This answer assumes the '-' symbol will always be at the end
If there are values sometimes formatted as -1234.94 then you could do:
 DECLARE @TestConvert VARCHAR(MAX) = '1234.94-'
 SELECT
 CASE WHEN ISNUMERIC(@TestConvert)=1  THEN
 CAST(@TestConvert AS Decimal(18,4) )
 ELSE
CAST((RIGHT(@TestConvert,1)+LEFT(@TestConvert,LEN(@TestConvert)-1)) as DECIMAL(18,4))
END

A: DECLARE @TestConvert VARCHAR(MAX) = '1234.94-'

if(charindex('-', @TestConvert) = len(@TestConvert))
begin
    set @TestConvert = replace(@TestConvert, '-', '')
    select 0 - cast(@TestConvert as DECIMAL(6, 2))
end
else
    select cast(@TestConvert as DECIMAL(6, 2))

A: You can try
declare @val as nvarchar(max)='5656.99-'

select case when CHARINDEX('+',reverse(@val))=1 or CHARINDEX('-',reverse(@val))=1 then
CAST(REVERSE(STUFF(REVERSE(@val),1,1,'')) as decimal(18,2)) else cast(@val as decimal(18,2)) end

hope it'll convert value for any cases.


text:
Q: User Input of Date as a Query I have a query which goes like this:
StockAnalytics.uDIX - StockAnalytics.dDIX > 0.5
    AND (Today1.uDIX - Today1.dDix) > 0.5
    AND (Today2.uDIX - Today2.dDix) > 0.5
    AND (Today1.uDIX - Today1.dDix) > (Today2.uDIX - Today2.dDIX)
    AND (Today2.uDIX - Today2.dDIX) > (Today3.uDIX - Today3.dDIX)
    AND StockAnalytics.[Date] > @Date

I am trying to take the input from the user on which date he wants to run the query. When I enter the date, it asks for the same input twice.
Anything wrong with this query?
Soham
EDIT: I don't think, I could get my problem across. When I use this code snippet, it works perfectly, except for the fact that, the dialog box, prompting the user to enter the Date, comes twice I don't want to have it pop twice. Only after the user has entered the "date" the second time, does the results come up

A: If you need to include a parameter twice as in:
 SELECT Stuff
 FROM ATable
 WHERE FirstDate > [Please enter date: ]
 AND SecondDate > [Please enter date: ]

Then include a parameter line:
 PARAMETERS [Please enter date: ] DateTime;
 SELECT Stuff
 FROM ATable
 WHERE FirstDate > [Please enter date: ]
 AND SecondDate > [Please enter date: ]

Or better yet, use a form:
 SELECT Stuff
 FROM ATable
 WHERE FirstDate > Forms!Dates!txtDate
 AND SecondDate > Forms!Dates!txtDate


text:
Q: Get same div level but different class name with jsoup I would like to get data from html

One

A

Two

B

C

Three

D

How i can get the data in new format, where A is child of One, Two is parents of B and C, and so D is parents of D. When i try use loop for ( element) i just get all of component. I have trouble to get element between One - Two - Three. There only one element (A) between "One" dan "Two". Next, 2 element (B & C) between "One" and "Two". The Last one is only 1 element, D, after "Three".
And i will show like :
One :
> A
Two :
> B
> C
Three :
> D

I use eq(0) to access them, but the result show false output.
To do that i'm simply doing this:
Elements ht = dok.select("div.one");
Elements li = dok.select("div.alpha:eq(0)");

    for(Element el : ht   ){
      System.out.println(el.ownText()+" : "+li.get(i).text());
      i++;
      }

But the result was:
One :
> A
Two :
> B
Three :
> C

based on the result, isn't like what i hope. That's it between "Two" and "Three" actually have 2 element, B and C. While the last "Three" it must have element of D. But in this result , the element D is can't display.
Thanks for any advice


text:
Q: BarCode Scanning Application Can anyone help me with this.I need a bar code scanning application for scanning product code.I am new to this.So send me an source code for the bar code scanner.

A: Hope this helps :
Android barcode scanner using Zxing

A: You can use: zxing-android-embedded.
Usage:

*

*To initiate scan:
new IntentIntegrator(this).initiateScan(); // this is the current Activity

*To get results:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (result != null) {
        if (result.getContents() != null) {
            String contents = result.getContents();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

A: you can use this link for BarCode or QRCode Scanning
Visit https://github.com/zxing/zxing/


text:
Q: creating an alert when no data was uploaded to BigQuery table in GCP I have a requirement to send an email notification whenever there is no data getting inserted into my BigQuery table. For this, I am using the Logging and Alerting mechanism But still, I am not able to receive any email. Here are the steps I followed:

*

*I had written a Query in Logs explorer as below:

*Now I had created a metric for those logs with Metric type COUNTER and in the filter section obviously I have given the above query.

*Now I created a policy in ALERTING under the MONITORING domain. And here is the screenshot attached. The alerting policy which I had selected is for the logging metrics which I had created before.

*And then a trigger as below:

And in the Notification channel, added my Email ID.
Can someone please help me if I am missing something? My requirement is to receive an alert when there is no data inserted into a Bigquery table for more than a day.
And also, I could see in Metrics Explorer, the metric which I created is not ACTIVE. Why so?

A: As mentioned in GCP docs:

Metric absence conditions require at least one successful measurement — one that retrieves data — within the maximum duration window after the policy was installed or modified.

For example, suppose you set the duration window in a metric-absence policy to 30 minutes. The condition isn't met if the subsystem that writes metric data has never written a data point. The subsystem needs to output at least one data point and then fail to output additional data points for 30 minutes.

Meaning, you will need at least 1 datapoint (insert job) to have an incident created for the metric to be missing.
There are two options:

*

*Create an artificial log entry to get the metric started and have at least one time series and data point.

*Run an insert job that would match the log-based metric that was created to get the metric started.

With regards to your last question, the metric you created is not active because there hasn't been any written data points to it within the previous 24 hours. As mentioned above, the metric must have at least 1 datapoint written to it.
Refer to custom metrics quota for more info.


text:
Q: how to print background image? when i click print option background image is not printing..could u please help me out.
here is my css
.OldNote {
    background-image: url(/images/icons/arkiv.gif);
    background-repeat: repeat;
    width: 100%;
    height: 100%;
    margin: 0px;
}

A: Usually it is up to the user and their browser settings to print or not print background images. Check your browser settings.
If you don't want to rely on that, don't place the image in the background, place it on your page in an <img>-tag.

A: You can just add an image tag like this, whereever you want the image to be displayed :
 <img src="url" class='printableonly' />

Then in the css, you can do like this :
  @media screen {
      .printableonly{
           display: none;
       }
  }

  @media print{
     .printableonly {

          display: inline;

       }
   }

A: i just add, if you want it to be background, there is no know way to make it repeat like a common backgrond. To put it under the content you may use css as adding it in other element before the content and giving both elements css  position: absolute style, together with the *z-index: .. *, where z-index of content will be bigger.
Maybe you may look into full size background solution which is made very similar


text:
Q: Publishing Outlook Calendars. What is the server-side setting for sync frequency? I'm working on a custom implementation of a server (VERY basic WebDAV) that accepts Outlook's published calendars.
Outlook seems to have a setting (see the screenshot below) where it accepts a parameter form the server that tells it how often to re-publish the calendar and that's the parameter I'm trying to figure out.

If the setting is not specified Outlook defaults to 60 minutes which doesn't work for me but I cannot find any information on what the parameter might be (I am aware that Outlook's settings can be adjusted within the UI but I need it done automatically via a response from the server). When using Wireshark I see that when first publishing the calendar Outlook sends a PROPFIND method to the URL of the server:
PROPFIND /path/to/url HTTP/1.1
X-Office-Version: 15.0.4771
Depth: 1
Content-Type: text/xml
User-Agent: Microsoft Office/15.0 (Windows NT 6.3; Microsoft Outlook 15.0.4771; Pro)
Host: example.com
Content-Length: 114
Connection: Keep-Alive
Cache-Control: no-cache

<?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"><D:prop><D:resourcetype/></D:prop></D:propfind>

which then responds with an XML (I'm assuming this is where the setting would be, but cannot find any information on it):
<?xml version="1.0"?><a:multistatus xmlns:a="DAV:"/>

I'm lost at this point and not sure where else to be looking after lots of Googling and traffic sniffing (of Outlook <->Exchange communications but none that I found seem to be using the non-default param). Any suggestion where would be a good idea to look for something like this?
The reason I'm asking this question here is because there must be some setting on Exchange/IIS that sets this option. I would like to know what it is to figure out (sniff?) it's raw code to simulate in my implementation.


text:
Q: Worker package disfunction when importing postgresql package I'm trying to use the Worker package and the PostgreSQL package.
I'm not sure why but if I run the example in
https://diegorochablog.wordpress.com/2014/02/18/worker-dart-concurrent-programming-does-not-have-to-be-hard/
After changing nothing but adding an import statement: import 'package:postgresql/postgresql.dart';,  The example stops working (the task's execute is not called).
Dart VM version: 1.17.0-dev.4.1 (Thu May 19 11:21:39 2016) on "macos_x64".
pubspec.yaml
name: fibFuturesConcu
version: 0.0.1
description: A simple console application.
dependencies:
  worker: any

Update
Apparently it does not happen with the stable version of Dart (1.16.0).

A: The problem is gone when using Dart Stable 1.16.


text:
Q: In which cases is a Gateaux differentiable function also a Fréchet differentiable function? It is well known that a function which is Fréchet differentiable is also Gateaux, but in which conditions can we be sure that the opposite is also true? And in that case, is there any proof of that?
Thanks for helping.

A: One sufficient condition that I know is when the gateaux derivative is continuous at the point. More detailed:
Let be a function $f\colon X\to Y$ and $x\in X$. If there exists a neighborhood $U$ of $x$ that $f$ is gateaux differentiable there, and $D_Gf\colon U\to \mathcal{L}(X,Y)$ is a continuous function, then $f$ is Frechet differentiable on $U$.
Some ideas of the proof are:

*

*For $h\in X$, you can define $\varphi_h(t) = f(x+th) +t\langle D_G f(x), h\rangle $ where $\{x+th\colon t\in [0,1]\}\subset U$,  then $\varphi_h$ is frechet-differentiable, so you can use the mean value theorem to get that $$ \|f(x+h)-f(x)-\langle D_G f(x), h\rangle\|=\|\varphi_h(1)-\varphi_h(0)\|\leq\sup_{t\in [0,1]} \|D\varphi_h(t)\| $$ but $D\varphi_h(t) = \langle D_Gf(x+th)-D_Gf(x),h\rangle$.

*The next step is to use the continuity supposed for $D_G f$ at $x$. Then you can prove that $f$ is frechet differentiable at $x$.


text:
Q: Extracting Text Values from XML in SQL I'm working with SQL data hosted by a 3rd party, and am trying to pull some specific information for reporting. However, some of what I need to parse out is in XML format, and I'm getting stuck. I'm looking for the syntax to pull the text= values only from the XML code.
I believe the code should something like this, but most of the examples I can find online involve simpler XML hierarchy's than what I'm dealing with.
<[columnnameXML].value('(/RelatedValueListBO/Items/RelatedValueListBOItem/text())[1]','varchar(max)')>

Fails to pull any results. I've tried declaring the spacenames as well, but again...I only ever end up with NULL values pulled.
Example XML I'm dealing with:
<RelatedValueListBO xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns="http://tempuri.org/RelatedValueListBOSchema.xsd">
    <Items>
        <RelatedValueListBOItem groupKey="Response1" text="Response1" selected="true" />
        <RelatedValueListBOItem groupKey="Response2" text="Response2" selected="true" />
        <RelatedValueListBOItem groupKey="Response3" text="Response3" selected="true" />
    </Items>
</RelatedValueListBO>

Ideally I'd like to pull response1; response2; response3 into a single column.  Allowing for the fact that multiple responses may exist. I believe I'm getting stuck with the basic code I've been trying due to the namespaces associated to RelatedValueListBO and the fact that what I want is grouped in groupKey, text, and selected, instead of the value I want just being under the Items node.

A: You can use something like this to extract the value of "text" in the first node of RelatedValueListBOItem
SELECT  extractvalue(value(rs), '//RelatedValueListBOItem[1]/@text')
  FROM TABLE (xmlsequence(extract(sys.xmltype('<RelatedValueListBO>
      <Items>
        <RelatedValueListBOItem groupKey="Response1" text="Response1"
    selected="true" />
    <RelatedValueListBOItem groupKey="Response2" text="Response2"
    selected="true" />
    <RelatedValueListBOItem groupKey="Response3" text="Response3"
    selected="true" />
     </Items>
    </RelatedValueListBO>'),'/RelatedValueListBO/Items'))) rs;

A: You have the namespaces defined in your XML, so you need to define them in the XQuery too.
Fast and dirty method is to replace all namespaces with a "*":
SELECT @x.value('(/*:RelatedValueListBO/*:Items/*:RelatedValueListBOItem/@text)[1]','varchar(max)')

To get all responses in a single column you can use:

SELECT
 Item.Col.value('./@text','varchar(max)') X
FROM @x.nodes('/*:RelatedValueListBO/*:Items/*:RelatedValueListBOItem') AS Item(Col)

If you need a better performance, you may need to define namespaces properly.


text:
Q: what does the void ** mean I haven't seen the void ** previously in the C language course.
int *dev_c;
dev_c = &val;
printf("%p\n",dev_c);  // val address
printf("%p\n",&dev_c); // get the address of dev_c
printf("%p\n",(void **)&dev_c);

is (void **) a type converter? the last two lines output the same result.

A: The (void**) is a cast. It's casting the &dev_c address (which has the type pointer to pointer to int), making it a pointer to a pointer to void instead.

A: It's a pointer to a pointer of void type.  That line is casting a reference to that type.

A: void** is pointer to a pointer.In you example dev_c is pointer so address of this &dev_c will be a pointer to pointer and this is typecasted to void**.

A: (void **) is a type cast to indicate a pointer to a pointer.
In your example code of printf it does nothing.


text:
Q: How to merge 2 third party components in VueJS I am using Form Tags components bootstrap-vue framework. I want to use vue-simple-suggest
component (from npm) with form tags to suggest words related to user's query. User can select multiple words from suggestion, and the selected word will be saved in form tags as a pill as shown in image below.

I don't know how to merge both the components as a single component (or more better way), so that I can use UI feature of bootstrap with auto-suggest feature of a third party module.
I am learning VueJs, I don't know what should I learn to do this?
Here is my code:
<template>

    <vue-simple-suggest
      v-model="chosen"
      mode="select"
      :list="simpleSuggestionsList"
      :filter-by-query="true"
      :destyled="false"
    >

    </vue-simple-suggest>

</template>

A: The following solution hacks together the two components to create an editable combobox with tag-pills.
According to the caveat docs of vue-simple-suggest, its custom input components must emit the input, focus and blur events, as well as have a value prop. In addition, there are a few undocumented events that are required from the component: click, keydown, and keyup.
b-form-tags has a value prop, but is missing several of the required events. However, you could access its internal input element to attach your own event handlers that forward-$emit the events:
export default {
  async mounted() {
    // wait a couple ticks to ensure the inner contents
    // of b-form-tags are fully rendered
    await this.$nextTick()
    await this.$nextTick()

    //
    const input = this.$refs.tags.getInput()
    const events = [
      'focus',
      'blur',
      'input',
      'click',
      'keydown',
      'keyup'
    ]
    events.forEach(event =>
      input.addEventListener(event, e => this.$refs.tags.$emit(event, e))
    )
  },
}

The changes above alone will cause the vue-simple-suggest to properly appear/disappear when typing. However, it doesn't add/remove tags when interacting with the auto-suggestions. That behavior could be implemented by the following features:

*

*ENTER or TAB keypress causes hovered auto-suggestion to be added as a tag. If nothing hovered, the keypress adds the first auto-suggestion as a tag.

*Clicking auto-suggestion adds the auto-suggestion as a tag.

*BACKSPACE on an auto-suggestion tag deletes it.

Feature 1 implementation:

*

*Add refs to the vue-simple-suggest and b-form-tags so that we could access the components in JavaScript later:

<vue-simple-suggest ref="suggest">

</vue-simple-suggest>

*Add a keydown-handler on the inner input of b-form-tags:

export default {
  mounted() {
    //...

    //
    const input = this.$refs.tags.getInput()
    input.addEventListener('keydown', e => this.onKeyDown(e))
  },
}

*Implement the handler as follows:

export default {
  methods: {
    async onKeyDown(e) {
      if (e.key === 'Enter' || e.key === 'Tab') {
        // prevent default so that the auto-suggestion isn't also
        // added as plaintext in b-form-tags
        e.preventDefault()

        // <vue-simple-suggest ref="suggest">
        if (this.$refs.suggest.hovered) {
          this.$refs.tags.addTag(this.$refs.suggest.hovered)

        } else {
          const suggestions = await this.$refs.suggest.getSuggestions(e.target.value)
          if (suggestions.length > 0) {
            this.$refs.tags.addTag(suggestions[0])

          } else {
            // no match, so clear chosen
            this.chosen = ''
          }
        }
      }
    }
  }
}

*To prevent conflict with our handler, disable b-form-tag's automatic tag-adding upon ENTER by adding no-add-on-enter prop:

Feature 2 implementation:

*

*Bind a suggestion-click-event handler:

<vue-simple-suggest @suggestion-click="onSuggestionClick">

*Implement the handler as follows:

export default {
  methods: {
    onSuggestionClick(suggestion) {
      this.$refs.tags.addTag(suggestion);
    },
  }
}

Feature 3 implementation:

*

*Add the remove-on-delete prop to b-form-tags:

full demo

As an aside, you might be better off with Vuetify's v-combobox, which supports the combination of the two components you're trying to merge, but I'll leave that to you to explore :)

A: Merging two component need to modified internal component of bootstrapvue and it take times.
Refer to documentation here https://bootstrap-vue.js.org/docs/components/form-tags.
BootstrapVue already supporting searching tags. The available list saved in options:
data() {
  return {
    options: ['Apple', 'Orange', 'Banana', 'Lime', 'Peach', 'Chocolate', 'Strawberry'],
    search: '',
    value: []
  }
},

You can achieve the suggestion by make modification to update this options list.
Add @change event in b-form-input to trigger updateOptionsList() :

Also add updateOptionsList() methods :
// Get Data From Server From URL
updateOptionsList() {
  console.log("update list");

  this.options = ["Jakarta", "London", "Birmingham", "Rome"];
  // Use  axios.get('...') then attach the result to this.options
  /**  axios.get("your-url-here").then(response => {
    // update options
    this.options = response.data;
  }); **/
}

Note: You can use axios ( https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html) to get real data from your server ada update the options list.
Complete sample code :
<template>

        <template v-slot="{ tags, disabled, addTag, removeTag }">

 0" class="list-inline d-inline-block mb-2">

              {{ tag }}

            <template v-slot:button-content>
              Choose tags
            </template>
             {}">

            {{ option }}
            There are no tags available to select

        </template>

</template>

I tried it here https://codesandbox.io/s/vue-bootstrap-tags-search-ldsqx and it looks goods.

A: Apparently, b-form-tags doesn't emit the input event until a tag has been entered. This is not the ideal case for working with vue-simple-suggest, as it would require its input to be changed every time user hits a key. As such, what you can rather do is slot vue-simple-suggest inside of b-form-tags, instead of doing it other way around. You could use something like this:
<template>

      <template v-slot="{tags, tagVariant, addTag, removeTag}">
        {{ tag }}

          <vue-simple-suggest
            placeholder="Enter Keyword"
            @input="textInput"
            :value="chosen"
            mode="select"
            @select="addSelectedWord"
            :list="simpleSuggestionsList"
            :filter-by-query="true"
            :destyled="false"
          ></vue-simple-suggest>

          Add

      </template>

</template>

You can further customize the slot or components by adding custom styling. If you do not like two input fields being displayed, you could try removing border of one by setting border property to none in the CSS.

A: I have never use these two libs, just a little bit advise.
I think the main point is don't use the UI provided by vue-simple-suggest, you know , the UI framework choosed is BootstrapVue and it wouldn't like others getting in its enviroment.
Just using the API to fetch suggestions instead.
The steps may look like this:
1. Show dropdown menu with {fetchSuggestions(something)} when typeing {something}
2. Add a pill labeled with the {suggestion} when {suggestion} being clicked

Hoping that will be helpful.


text:
Q: Cannot run Ubuntu install dual boot from USB on X1 Carbon w/Win8.1 - kernel panic, VFS I installed Ubuntu as dual-boot on X1 Carbon 3rd gen (with Windows 8.1, UEFI etc.; lets call it "Machine A"). I had some issue with Ubuntu there, so I removed like 3 partitions (from Windows tool) - one had 1MB, the other was main, the other was seemingly SWAP partition. I did not remove any other partitions that looked like the ones aimed at dealing with some internal stuff (such as deep sleep or recovery).
When I created startup disk (USB) on some other Ubuntu machine (lets call it "Machine B"), and restarted Machine A to boot from USB stick, then selected custom boot source (the mentioned USB), I saw boot loader (GRUB?) with option to "Install Ubuntu", but when I selected it, I saw the following:
[    0.329678] Error parsing PCC subspaces from PCCT
[    0.329694] ACPI PCC probe failed.
[    0.477876] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)
[    0.477900] CPU: 1 PID: 1 Comm: swapper/0 Not tainted 3.19.0-15-generic #15-Uuntu
[    0.477919] Hardware name: LENOVO 20BS0068PB/20BS0068PB, BIOS N14ET26W (1.04 ) 01/23/2015
[    0.477939]  fffea000313a480 ffff8802241efdb8 ffffffff817c2205 0000000000002892
(...)
[    0.478009] Call Trace:
(...)
[    0.478155]  [<ffffffff817b6ae0>] ? rest_init+0x80/0x80
[    0.478175] Kernel Offset: 0x0 from 0xffffffff81000000 (relocation range: 0xffffffff80000000-0xffffffffbfffffff)
[    0.478200] ---[ end Kernel panic - not syncing: VFS: unable to mount root fs on unknown-block(0,0)

So, as you see, there is some kernel panic related to this installation, and I am not sure what could I do to even debug the issue.
Windows 8.1 is starting properly, when selected as boot source. But I have some issues with virtual machines running Ubuntu (they look like experiencing same issue my machine had with that first Ubuntu installation).
Any ideas on how to fix the problem, or at least be able to fetch more information on it?
Ps. The example of exact image I am seeing is here:

A: It came out the problem is with the USB stick - after using Windows recovery and reverting all the disks to original state, reinstalling Windows etc. it still appeared. Then I just recreated installation USB on different USB drive and it started to work.
I don't know what was the reason this drive was corrupted, but in similar situation using another USB drive should be one of the easiest bets.
Ps. That original USB drive had two partitions at some point: one for SWAP. Maybe it somehow interferred with installation.


text:
Q: Pandas: plot line and bar plot in the same figure _with custom index_ I am looking to plot a line and bar charts on in pandas on the same plot.
The usual way of doing it seems to share the ax variable with the different plots, e.g.
fake_data = pd.DataFrame(np.random.uniform(-1, 1, size=(21, 6)), columns=list('ABCDEF'))
other_fake_data = pd.DataFrame(np.random.random(size=(21, 6)), columns=list('ABCDEF')) / 10
ax = fake_data.plot(kind='line', figsize=(10, 5))
other_fake_data.plot(kind='bar', ax=ax, secondary_y=True)

This works as expected. However, if I have a custom index in the two data frame, the second plot seems to cover the first one:
fake_index = range(100, 121)
fake_data = pd.DataFrame(np.random.uniform(-1, 1, size=(21, 6)), columns=list('ABCDEF'))
fake_data.index = fake_index
other_fake_data = pd.DataFrame(np.random.random(size=(21, 6)), columns=list('ABCDEF')) / 10
other_fake_data.index = fake_index
ax = fake_data.plot(kind='line', figsize=(10, 5), alpha=.8)
other_fake_data.plot(kind='bar', ax=ax, secondary_y=True, alpha=.3)

Is there a way of preventing plotting both of them using the custom index?


text:
Q: $\int \cos(w_1t)\cos(w_2t)\,dt$ integral Could you please give me a hint about how to proceed to resolve this integral? I've tried several times starting from different trigonometric rules but I don't find the answer :(
$$\int \cos(w_1t)\cos(w_2t)\,dt$$
with: $$w_2=w_1 + \Delta w$$
This is the answer it should give:

(Forget the part before the integral.)
Thank you so much in advance for your help!!
Kind regards.


text:
Q: How can I access a log4net logs folder for an azure app service with a readonly user I can access the log4net log folder via KUDU.  BUT KUDU requires contributor access.  I want to be able to access or download UAT/PROD logs without write permissions.  I'd prefer to avoid going the route of an FTP. My user can navigate the azure portal, resource groups, and see the app service, but does not have console access for an app service.  Is what I'm trying to achieve possible and how?

A: As per trailmax mentioned, the Application Insights is the easy and convenient way to collect logs / query logs. We recommend using Application Insights for this case.
Install the related application insights sdk(like Microsoft.ApplicationInsights), Microsoft.ApplicationInsights.Log4NetAppender, and with other little configuration, then application insights can work well for your site.
This is just a suggestion, but if you have any issues about this, please leave a comment here(and provide more information like it's a .NET core or .NET framework project).


text:
Q: PHP form submit and status information popup without refreshing I am creating simple CMS for uploading AR Vuforia Markers for my mobile app. I have working php form that is:

*

*Uploading one image (target) to server

*That target sending to Vuforia Cloud

*Uploading data from form to database

*Uploading other files to server

So everything is working correctly, but now I am trying to display popup after clicking submit with status informations.
Simple popup with text:

*

*Uploading target to server

*Sending target to Vuforia Cloud

*Uploading data from form to database

*Uploading other files to server

after every step is completed text is just colouring in green (in error case on red) and at the end unlocking OK button.
I trying different solutions from here with progress bar i.e. Display progress bar while the php script is running through ajax in spite of various attempts, I am still doing something wrong. I know that jquery is not my strong side.
form file (insert_gallery.php) is:

    <meta charset="UTF-8">

    <meta name="robots" content="noindex">
    <meta name="googlebot" content="noindex">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="../fontawesome-free-5.13.0-web/css/all.css" />
    <link rel="stylesheet" href="../css/main.css" />

            <form method="post" class="form-horizontal" enctype="multipart/form-data" action="vuforia/upload_gallery.php" id="upload_target">

TARGET

                        * target (.jpg)
                        <input name="markerfile" id="markerfile" type="file" class="form-control"  onchange="targetAdded()" style="border: none;" required>
                        <canvas id="markerCanvas" style="max-width: 100px; max-height: 100px"></canvas>

                        * category:
                        <select id="category" name="category" size="1" class="custom-select">
                            <option value="education">Education</option>
                            <option value="entertainment">Entertainment</option>
                            <option value="shopping"> Shopping </option>
                            <option value="contests"> Contests </option>
                            <option value="games"> Games </option>
                        </select>

                        <input type="checkbox" class="form-control" id="for_adults" name="for_adults" style="margin-right: 5px">+18

                        <input type="checkbox" class="custom-checkbox" id="is_active" name="is_active" style="margin-right: 5px">active

                        <input name="target_name" id="target_name" type="text" class="form-control-input" placeholder="Title..." required>
                        <input name="target_client" id="target_client" type="text" class="form-control-input" style="margin-left: 6px;" placeholder="Client..." required>

                        <textarea name="target_desc" id="target_desc" class="form-control-textarea" style="resize: none;" placeholder="Opis..." required></textarea>

                        * photo 1 (.jpg or .png)
                        <input name="mediafile1" id="mediafile1" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

                         photo 2 (.jpg or .png)
                        <input name="mediafile2" id="mediafile2" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

                         photo 3 (.jpg or .png)
                        <input name="mediafile3" id="mediafile3" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">
                        <canvas id="markerCanvas" style="max-width: 100px; max-height: 100px"></canvas>

                         photo 4 (.jpg or .png)
                        <input name="mediafile4" id="mediafile4" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

                         photo 5 (.jpg or .png)
                        <input name="mediafile5" id="mediafile5" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

                         photo 6 (.jpg or .png)
                        <input name="mediafile6" id="mediafile6" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

                         photo 7 (.jpg or .png)
                        <input name="mediafile7" id="mediafile7" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

                         photo 8 (.jpg or .png)
                        <input name="mediafile8" id="mediafile8" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

                         photo 9 (.jpg or .png)
                        <input name="mediafile9" id="mediafile9" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

                         photo 10 (.jpg or .png)
                        <input name="mediafile10" id="mediafile10" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

NEWSFEED

                    <input type="checkbox" class="form-control" id="newsfeed" name="newsfeed" style="margin-right: 5px">show in newsfeed

                    <input type="checkbox" class="form-control" id="time_campaign" name="time_campaign" style="margin-right: 5px">time campaign

                        photo (newsfeed) (.jpg lub .png)
                        <input name="main_photo" id="main_photo" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

                        video (newsfeed) (.mp4)
                        <input name="main_video" id="main_video" type="file" class="form-control"  onchange="targetAdded()" style="border: none;">

                        <textarea name="short_desc" id="short_desc" class="form-control-textarea" style="resize: none;" maxlength="80" placeholder="Short description..." required></textarea>

                        <textarea name="long_desc" class="form-control-textarea" style="resize: none;" placeholder="Long description..." required></textarea>

                    <input type="button" id="submit" value="Submit">

            </form>

and upload_gallery.php:
    <?php

    if(isset($_POST['submit'])){

    require '../../misc/db_connection.php';
    require '../../misc/ftp_connection.php';
    include 'vuforiaclient.php';

    if(isset($_POST['for_adults'])){$for_adults = 1;} else {$for_adults = 0;}
    if(isset($_POST['is_active'])){$is_active = 1;} else {$is_active = 0;}
    if(isset($_POST['newsfeed'])){$newsfeed = 1;} else {$newsfeed = 0;}
    if(isset($_POST['time_campaign'])){$time_campaign = 1;} else {$time_campaign = 0;}

    $db = getConnection();
    $next_id = "SELECT `AUTO_INCREMENT` FROM  INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'vuforia' AND TABLE_NAME = 'targets'";
    $stmt = $db->prepare($next_id);
    $stmt->execute();
    $target_next_id = $stmt->fetchColumn();

    $target_category = trim(htmlspecialchars($_POST['category']));
    $target_type = 'gallery';

    $markerfile = $_FILES['markerfile']['name'];
    $imageFileType = strtolower(pathinfo($markerfile,PATHINFO_EXTENSION));
    $uploadOk = 1;

    if ($_FILES["fileToUpload"]["size"] > 2000000) {
        echo "To big file.";
        $uploadOk = 0;
    }

    if($imageFileType != "jpg") {
        echo "Only JPG";
        $uploadOk = 0;
    }

    $conn_id = ftp_connect($ftp_server);

    if (!ftp_login($conn_id, $ftp_user_name, $ftp_user_pass)) {
        exit('FTP Login Failed');
    }

    ftp_pasv($conn_id, true);

    if ($uploadOk == 1) {
        $renamedFile = $target_next_id."_".$target_category."_".$target_type;
        $remote_marker_path = "/storage_gallery/targets/".$renamedFile;
        $marker_upload = ftp_put($conn_id, $remote_marker_path.'.jpg', $_FILES["markerfile"]["tmp_name"], FTP_BINARY);
    }

    ftp_close($conn_id);

    if($marker_upload){

        $imagePath = 'https://....../storage_gallery/targets/';
        $imageName = $renamedFile.'.jpg';

        $client = new VuforiaClient();

        // add a target to vuforia.
        $vuforiaTargetID = $client->addTarget($imagePath,$imageName,$target_category,$target_next_id,$target_type);

        if ($vuforiaTargetID){
            $data = [
                'target_type' => 'gallery',
                'target_id' => trim(htmlspecialchars($vuforiaTargetID)),
                'target_category' => trim(htmlspecialchars($_POST['category'])),
                'target_status' => 'Processing',
                'target_image' => 'https://....../storage_gallery/targets/'.$renamedFile.'.jpg',
                'for_adults' => trim(htmlspecialchars($for_adults)),
                'is_active' => trim(htmlspecialchars($is_active)),
                'target_name' => trim(htmlspecialchars($_POST['target_name'])),
                'target_client' => trim(htmlspecialchars($_POST['target_client'])),
                'target_desc' => trim(htmlspecialchars($_POST['target_desc'])),
                'newsfeed' => trim(htmlspecialchars($newsfeed)),
                'time_campaign' => trim(htmlspecialchars($time_campaign)),
                'short_desc' => trim(htmlspecialchars($_POST['short_desc'])),
                'long_desc' => trim(htmlspecialchars($_POST['long_desc'])),
                'is_deleted' => '0',

            ];

            $insert_marker = "INSERT INTO `targets`
                                     (`created_at`, `target_type`, `target_id`, `target_category`, `target_status`, `target_image`, `for_adult`, `is_active`, `target_name`, `target_client`, `target_desc`, `newsfeed`, `time_campaign`, `short_desc`, `long_desc`, `is_deleted`)
                                VALUES
                                     (NOW(), :target_type, :target_id, :target_category, :target_status, :target_image,  :for_adults, :is_active, :target_name, :target_client, :target_desc, :newsfeed, :time_campaign, :short_desc, :long_desc, :is_deleted)";

             $db = getConnection();
             $stmt = $db->prepare($insert_marker);
             $run_gallery = $stmt->execute($data);
        }
    }

    if($run_gallery){
        echo "";
        echo "";
    }

}


text:
Q: Congruent modulo n Given a natural number n, and two integers a and b. Show that if:
a)a ≡ b and b≡c, it follows that a≡c
b)a≡b and c≡d, it follows that a+c≡b+d and ac≡bd
c)that a≡b if and only if a and b give the same remainder when divided by n
*I solved a) by equating k_1n with k_2n (there k_1n=a-b and k_2n = b-c). Although I am not sure how to continue with examples b) and c)...


text:
Q: Updating null geometries from attribute using ArcGIS Field Calculator? I have a large point feature class and have realised that there are several hundred features with null geometry. Fortunately the coordinates are stored as an attribute. What I need to do is update the geometry of the points with the x and y stores in the attribute table.
After a little search I found an Esri Support Services Blog post on How to Update the Location of a Point Feature and Its XY Fields which includes a python function that will do this for me in the field calculator.
However, it seems that this will only work on features with a geometry. When I run it on the null geometry features it returns a syntax error. presumably this is because there is no shape or there is no shape.getpart(0).
Is there something I could add to this script to allow it to update null geometries, or does anyone have another method?


text:
Q: FortesReport access violation when trying to print I'm using FortesReport in Delphi 2007, I call "previewModal()" and it works fine but when I try to print it it gives me an Access Violation when trying to print. Anybody know if I can configure FortesReport to avoid this error?

A: I solved the problem by updating the lib at https://github.com/fortesinformatica/fortesreport-ce, but still don't know what caused the problem.


text:
Q: Android nested linear layout for custom design I want to add two linear layouts after one layouts to an activity programatically each of same width. the problem is i am not able to set the weights of these layouts programatically. I could do this within xml, but I want to do this in program. here is what i want:

first button contains full width of screen but after this two button will share equal width and so on...
obviously, need to do it programmatically.
my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:background="@drawable/background"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".HomeActivity">

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </LinearLayout>

    </ScrollView>
</LinearLayout>

code behinds:
Button button = new Button(HomeActivity.this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 564);
                        layoutParams.setMargins(60, 80, 60, 40);

 Drawable drawable = Drawable.createFromStream(getAssets().open("image/GridButton/NovoTel_IGW_lg.png"), null);
button.setBackground(drawable);
button.setLayoutParams(layoutParams);

linearLayout.addView(button);

I got output like this:

Please suggest, which is the best way.

A: The simplest way to reach that would be using LinearLayout(s) with weight. Here's a basic example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:weightSum="3">

    <Button android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/>
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:orientation="horizontal"
            android:layout_weight="1"
            android:weightSum="2">
        <Button android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"/>
        <Button android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"/>
    </LinearLayout>
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:orientation="horizontal"
            android:layout_weight="1"
            android:weightSum="2">
        <Button android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"/>
        <Button android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"/>
    </LinearLayout>
</LinearLayout>

Output:

Then you can start implementing your graphics. You don't need a ScrollView in the suggested layout, but of course you'll be able to add it later if it becomes necessary.

A: Here's the answer. I tasted it. If it fulfills then marked as answer:
try {

   DisplayMetrics dm = new DisplayMetrics();
   this.getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
    int width = dm.widthPixels;
    int j = 0 ;
    String image;
    for(int i=0;i<(**JsonArray**).length();i++) {

        JSONObject jsonObject1 = **JsonArray**.getJSONObject(i);

        if(i==0) {
            image = //DrawableImage;
            drawable = Drawable.createFromStream(getAssets().open(image), null);
            Button button = new Button(HomeActivity.this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 564);
            layoutParams.setMargins(60, 80, 60, 40);
            button.setBackground(drawable);
            button.setLayoutParams(layoutParams);
            linearLayout.addView(button);
        }
        else
        {
            if(i%2 == 1)
            {
               image = //DrawableImage;
                drawable = Drawable.createFromStream(getAssets().open(image), null);
                LinearLayout linearLayout1=new LinearLayout(this);
                linearLayout1.setOrientation(LinearLayout.HORIZONTAL);
                Button button = new Button(HomeActivity.this);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width/2-120, 564);
                layoutParams.setMargins(60, 80, 60, 40);
                button.setBackground(drawable);
                button.setLayoutParams(layoutParams);
                linearLayout1.addView(button);

                if(i+1 < data.length())
                {
                    JSONObject jsonObject2 = data.getJSONObject(i+1);
                    image = //DrawableImage;
                    drawable = Drawable.createFromStream(getAssets().open(image), null);
                    Button button2 = new Button(HomeActivity.this);
                    button2.setBackground(drawable);
                    button2.setLayoutParams(layoutParams);
                    linearLayout1.addView(button2);

                }

                linearLayout.addView(linearLayout1);

            }
            else
            {
                continue;
            }

        }

    }

}catch (IOException ex)
{
    return;
}


text:
Q: Не присваивается переменная из url <form class="form-horizontal" method="post" action="success.php">
    <input type="hidden" name="price" <?php echo 'value="'.$price. '"'; ?>>
    <input type="hidden" name="title" <?php echo 'value="'.$title. '"'; ?>>
    <input type="hidden" name="year" <?php echo 'value="'.$year. '"'; ?>>
    <input type="hidden" name="spec" <?php echo 'value="'.$spec. '"'; ?>>
    <input type="hidden" name="closes" <?php echo 'value="'.$closes. '"'; ?>>

        Имя
        <input type="text" class="form-control" id="name" name="name" required="">

        Телефон
        <input type="phone" class="form-control" id="phone" name="phone" required="">

        <button type="submit" class="btn btn-default">Заказать</button>

</form>

Первая страница, переменная со значением, при передачи на вторую не принимает значение.
<?php
$name = $_POST['name'];
$phone = $_POST['phone'];
$title = $_POST['title'];
$year = $_POST['year'];
$spec = $_POST['spec'];
$closes = $_POST['closes'];
$price = $_POST['price'];

$address = "test@gmail.com";

$article = "Защита картера двигателя";

$mes = "$article
Имя: $name
Телефон: $phone
Характеристики:
Марка: $title
Год: $year
Особенности: $spec
Покрывает $closes
Цена: $price";

$sub="Заказ обратного звонка!";
$send = mail ($address,$sub,$mes, "Content-type:text/plain; charset = utf-8
");
?>

Переменная price не принимает значение

A: может $_POST попробуй)
<form ... method="post">
...
$name = $_POST['name'];

A: Чтобы понять, что происходит в вашем собственном коде, вам надо освоить некоторые приёмы отладки.

*

*Научитесь пользоваться инструментами разработчика в браузере (обычно открывается по нажатию f12). Там есть инспектор HTML (вкладка Инспектор), который поможет подсмотреть, что находится в скрытых полях формы и есть лог сетевых запросов (вкладка Сеть), где можно посмотреть что именно у вас отправилось на сервер в теле HTTP-запроса.

*var_dump -- функция PHP, которая позволяет заглянуть в переменную. Набрав var_dump($_POST); вы увидите, что у вас в этом массиве (в том числе и ключи, вероятно price там будет, но равен он пустой строке).

И ещё один совет для вас. Не выводите HTML c помощью php (я имею ввиду echo ' value="..."'). Вставляйте только значения и обязательно экранируйте их (почитайте про XSS): <input type="hidden" name="price" value="<?= htmlspecialchars($price) ?>"> (небольшой бонус: шорттэг <?= работает всегда, а ; перед закрывающим дескриптором можно опустить, это сделает ваши шаблоны более читаемыми).


text:
Q: Problem handling an exception in GUI Regarding the following code - I'm trying to get it throw and exception if anything other than a number is entered into 'cost' when adding a book, as you can see I've gotten someway towards doing so but I just want to display a message dialog stating "enter a number please", instead of an input dialog appearing, when i try to change to an message dialog Eclipse returns errors.
Any suggestions please?
The relevant snippet is
do{
        try {
            cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
            book.setCost(cost);
            goodInput = true;
            }
            catch (NumberFormatException nfe){
            cost = Double.parseDouble(JOptionPane.showInputDialog ("Numerical entry expected. Please try again"
            ));
            }
        }while (!goodInput);

and here's the full code.  thanks.
import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import javax.swing.*;

import java.awt.event.ActionListener;
import java.util.ArrayList;

public class BookGUI extends JFrame implements ActionListener

{

    //String addBook="";
    // public ArrayList<Book> books;

    //Book books = new Book ("", "", 0, "", 0);
    Book book = new Book("", "", 0, "", 0);
    String title  = "";
    String author  = "";
    int year = 0;
    String publisher  = "";
    double cost = 0;
    double total = 0;
    boolean goodInput = false;

    public BookShelf bookShelf = new BookShelf();
    public static final int WIDTH = 300;
    public static final int HEIGHT = 200;

    //Creates & displays a window of the class FlowLayoutDemo
    public static void main(String[] args)
    {
        BookGUI gui = new BookGUI( );
        gui.setVisible(true);
    }

   // public String getTitle()
   // {
    //    return title;
    //}

    public void setTitle(String title) //this is relevant
    {
        this.title = title;
    }

    public void setAuthor(String author) //this is relevant
    {
        this.author = author;
    }

    public void setYear(int year) //this is relevant
    {
        this.year = year;
    }
    public void setPublisher(String publisher) //this is relevant
    {
        this.publisher = publisher;
    }

    public void setCost(double cost) //this is relevant
    {
        this.cost = cost;
    }

    public BookGUI( )
    {

        setSize(WIDTH, HEIGHT);
        addWindowListener(new WindowDestroyer( ));
        setTitle("GUI Assignment");
        Container content = getContentPane( );

        content.setLayout(new FlowLayout());

        JButton button1 = new JButton("Hightest Price Paid");
        content.add(button1);
        button1.addActionListener(this);
        //contentPane.add(button1);

        JButton button2 = new JButton("Cost of BookShelf");
        content.add(button2);
        button2.addActionListener(this);

        JButton button3 = new JButton("Size of BookShelf");
        content.add(button3);
        button3.addActionListener(this);

        JButton button4 = new JButton("Add Book");
        content.add(button4);
        button4.addActionListener(this);

    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getActionCommand().equals("Add Book"))
       //book = JOptionPane.showInputDialog("Add Book");
        {     //set up the book object with all the data passed in
        title = JOptionPane.showInputDialog("Title");
        author = JOptionPane.showInputDialog("Author");
        publisher = JOptionPane.showInputDialog("Publisher");
        //cost = JOptionPane.showInputDialog("Cost");
        //cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
        do{
        try {
            cost = Double.parseDouble(JOptionPane.showInputDialog("Cost"));
            book.setCost(cost);
            goodInput = true;
            }
            catch (NumberFormatException nfe){
            cost = Double.parseDouble(JOptionPane.showInputDialog ("Numerical entry expected. Please try again"
            ));
            }
        }while (!goodInput);

        book.setTitle(title);
        book.setAuthor(author);
        book.setPublisher(publisher);
        bookShelf.addBook(book);

        String message =  "The title of the book is :" + title +
        "the Author of the Book is : " + author + " and it's published by " + publisher + "and it costs" + cost + "euro";
        JOptionPane.showMessageDialog(null, message, "Book Details", JOptionPane.PLAIN_MESSAGE);
        }
        else if (e.getActionCommand().equals("Size of BookShelf")) {
            int sizeOfBookShelf = bookShelf.sizeOfBookshelf();
            String message = "The book shelf has " + sizeOfBookShelf + " book(s)";
            JOptionPane.showMessageDialog(this, message);
        }
        else if (e.getActionCommand().equals("Cost of BookShelf"))
        {
            double costOfBookshelf = bookShelf.costOfBookShelf();
            String message = "The book shelf value is " + total + costOfBookshelf + "Euro";
            JOptionPane.showMessageDialog(this, message);
        }

    }
    }

A: You shouldn't try to read what the user enters in the message dialog, when an exception occurs : a message dialog is not meant to input anything. That's why showMessageDialog returns void, and not String like showInputDialog. Replace
catch (NumberFormatException nfe){
        cost = Double.parseDouble(JOptionPane.showInputDialog ("Numerical entry expected. Please try again"
        ));

with
catch (NumberFormatException nfe){
        JOptionPane.showMessageDialog(this, "Numerical entry expected. Please try again");

Also, note that you should always pass a parent component in the showXXXDialog, in order for the dialog to be modal (i.e. to block the access) to the frame of this component.
Have you read the javadoc of JOptionPane? Have you read the tutorial about dialogs?


text:
Q: how to hide content on index page and show this when a post is opened? I use WordPress.
my idea exactly look like stackoverflow.
i want on index page content doesn't show but when opeded post content's will be shown, like stackoverflow

<?php if(have_posts()):?> <?php while(have_posts()): the_post();?>

    <div class="post" id="post-<?php the_id(); ?>">

<?php bawpvc_views_sc('post_view', 'bawpvc_views_sc'); ?>

<?php comments_popup_link();?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                <?php get_template_part( 'content', get_post_format() ); ?>
                <?php the_excerpt(); ?>

<?php the_author()." " ;?>

<?php the_modified_date();?>

<?php the_category(', '." ")?>

<?php endwhile; ?>

with the_content() :

with the_excerpt() :

but i want the content doesn't show.

A: You must create two pages 1-index.php 2-single.php
index.php
<?php if(have_posts()):?> <?php while(have_posts()): the_post();?>
<?php the_title(); ?>
<?php endwhile; ?>
<?php endif; ?>

single.php
<?php if(have_posts()):?> <?php while(have_posts()): the_post();?>
<?php the_title(); ?>

<?php the_content();?>
<?php endwhile; ?>
<?php endif; ?>

A: I thing that you mean the more tag? It can be used to truncate text on the homepage and in the archive:
http://en.support.wordpress.com/splitting-content/more-tag/


text:
Q: Case sensitive sorting with capitals last I want to sort a List< string> case sensitive with capitals last, i.e. in the order
a,aBC,b,bXY,c,A,Ax,B,C,...
I have tried
Comparison<string> c = (string x1,string x2) => StringComparer.Ordinal.Compare(x1,x2);
list.Sort(c);

but it returns
A,Ax,B,C,a,aBC,b,bXY,c,...
Is there any predefined method to do this, or will I need to fiddle something together myself?
Edit: Since "capitals last" seems difficult enough I have spared numbers for the moment.

A: Finally I have opted for the suggestion by @JohnTortugo. Thanks John, incredibly simple idea, short and easy to implement!

*

*Swap upper and lower case in a string by XOR'ing 0x20 with each byte (ASCII coding assumed):
static string swapUpperLower(string s)
{
    return System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(s).Select(c => (byte)(c^0x20)).ToArray());
}

*Swap case for every string in the list before and after sorting
    Comparison<string> c = (string x1,string x2) => StringComparer.Ordinal.Compare(x1,x2);

    sl = sl.Select(s => swapUpperLower(s)).ToList();
    sl.Sort(c);
    sl = sl.Select(s => swapUpperLower(s)).ToList();

Result:
a
aBC
b
bXY
c
A
Ax
B
C

A: try this :
byte[] ascii = Encoding.ASCII.GetBytes("aBcDEf");
        var result = ascii.OrderByDescending(b => b).ToList();
        string converted = string.Empty;
        foreach(var c in result)
        {
            converted += Char.ConvertFromUtf32(c);
        }
        Console.WriteLine(converted);

A: You can try this lengthy code It works Like A Charm
public static List<String> CustomSort(List<String> ls)
    {

        ls.Sort();
        List<String> Oint = new List<String>();
        List<String> Ocap = new List<String>();
        List<String> Osma = new List<String>();

        foreach(string s in ls)
        {
            int n;
            bool isNumeric = int.TryParse(s, out n);
            if(isNumeric)
            {
                Oint.Add(s);
            }
            else if (char.IsUpper(s[0]))
            {
                Ocap.Add(s);
            }
            else if (!char.IsUpper(s[0]))
            {
                Osma.Add(s);
            }
        }

        var r1 = Oint.Concat(Osma).Concat(Ocap);

        List<String> com = r1.ToList();
        return com;

    }

Then Call it Like
List<String> ls = new List<String>();
            ls.Add("1");
            ls.Add("Cdsd");
            ls.Add("BCCd");
            ls.Add("ADDD");
            ls.Add("3");
            ls.Add("2");
            ls.Add("aDFD");
            ls.Add("cSS");
            ls.Add("b");
        List<String> cuz = CustomSort(ls);
        foreach(String s in cuz)
        {
            Console.WriteLine(s);
        }

You can Try This Code here


text:
Q: Prevent attaching to Notes & Attachments while adding to Quote PDFs I have a trigger that will save the Quote as PDF in Quote PDFs section (QuoteDocument object) whenever the status is updated to Accepted. The problem is, it also attaches to Notes & Attachments section. Is there a way to suppress attaching to Notes & Attachments?

A: No. The system is designed to show it in both places.


text:
Q: enable or disable menu item based on permissions of the user logged in with jsp and servlet I have a jsp page which contains the same menu bar for everyone, each user has a permission depending on his status ( if he is an administrator or user ..)
i want to disable some item menu bar if the user logged in is an administrator , and enable the other ones
 How can i achieve this, please suggest.
Thanks in advance

A: Set the role in session and get it in JSP page. In servlet,
session.setAttribute("Role", "administrator");

And in JSP,
<%
 String role= (String)session.getAttribute("Role");
 pageContext.setAttribute("role",role);
%>

Here I assumed that you are using JSTL for standard (Just add this line <%@ taglib prefix="c"
           uri="http://java.sun.com/jsp/jstl/core" %>).
<c:choose>
    <c:when test="{role == 'administrator'}">
        <!-- Menu Choice 1 -->
    </c:when>
    <c:otherwise>
        <!-- Menu Choice 2 -->
    </c:otherwise>
</c:choose>

See BalusC answer for more details. Hope this helps.


text:
Q: CreatedDate and AmendDate generated by the database User class:
public class User
{
    public DateTime CreatedDate { get; private set; }
    public DateTime? AmendDate { get; private set; }
}

I need the columns CreatedDate and AmendDate have the values generated by the database (now() command)
Reading some articles on the internet, advised me to use this in DbContext class on OnModelCreating method:
Property(p => p.CreatedDate)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

Property(p => p.AmendDate)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

But does not work, saying that an error is supported types are rowversion and timespan.
How do you do with these property types?
Any tips?

A: You can make both columns nullable and Save changes with both columns with null values. You also need set the default value for the column as getdate() in the relevant column in the database. Then these columns will automatically be populated with current date if you try to insert null values. But EF will not update the property with the database generated date value.
Other solution is to set the values before you call the SaveChanges() method
public override int SaveChanges()
{
    var changeSet = ChangeTracker.Entries<User>();

    if (changeSet != null)
    {
        foreach (var entry in changeSet
       .Where(c => c.State == EntityState.Added || c.State == EntityState.Modified))
        {
            entry.Entity.CreatedDate = entry.Entity.AmendDate = DateTime.Now;
        }
    }
    return base.SaveChanges();
}


text:
Q: importlib.metadata.PackageNotFoundError: No package metadata was found for pyproj I wrote a code using the pyproj library and converted this code to an exe file for use on another computer. I added the pyproj to the requirements.txt file. And I installed the library with the requirements.txt file on the other computer I will use. When I run the exe file, I get the following error:
importlib.metadata.PackageNotFoundError: No package metadata was found for pyproj

I'd be glad if you can help.

A: This was caused by a change on pyproj when they updated to version 3.4.0
https://github.com/pyproj4/pyproj/issues/1155
It now requires that the dist-info of the pyproj to be present, so it can find the "version" property inside the METADATA file, so if you have an slim installation (an installation without the dist-info folder) the project will break during the first run of its pyproj/__init__.py.
Another way to fix this problem would be to manually remove that line of the code, (line 70 in the __init__.py) or to hardcode the version of the project there.
Another solution could be to install and leave the metadata with the project, another approach would be to delete everything in the dist-info folder except the METADATA file.
You could however roll back to version 3.3.1 which is prior to that breaking change.
edit: I made a change to pyproj a few days after this message, so this is fixed and no longer happens

A: Here is my solution for those who have problems like above while running the exe file:
 pyinstaller --onefile --copy-metadata pyproj "example.py"

For now this seems to have fixed the problem.


text:
Q: AD users in B2C tenant I am wondering if it is possible to let's say connect the Azure AD with the Azure B2C, in order that the Azure AD users are able to login in my custom policy. I already implemented one, including MFA.
I was reading this article, but I am not sure if it is the right way. If so, I see I have to specify the client-id. What if I have more than one application using this policy, do I have to create a policy for each one?

A: The linked approach is correct. You specify a clientId which represents AADB2C user-flow/custom-policy as an "Application" to the AAD IdP. So this relationship can be used per AAD B2C user-flow/custom-policy or shared across all your custom policies and user flows.
It can be useful to have separate registrations at AAD so that you could target them individually for conditional access.


text:
Q: Can't create Avro table in Dataproc 2.0 image I'm trying to work with Hive with 2.0-debian10 image of Google Dataproc and can't create simple table with Avro format.
It's working fine with Parquet and also works fine with 1.5 image.
CREATE TABLE `db`.`avrotable`
(
  `a` INT
)
STORED AS avro;

Getting this error:

ERROR processing query/statement. Error Code: 1, SQL state: Error while processing statement: FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. org.apache.avro.AvroRuntimeException: Unknown datum class: class org.codehaus.jackson.node.NullNode

Any ideas?

A: This failure is caused by HIVE-24436 issue and will be fixed in next release of Dataproc 2.0 image.