text:
Q: Why doesn't my AngularJS component react to attribute value changes? I've seen several questions about topics like this here on SO and on the web at large.  Specifically, I tried to follow one clear example but can't get it to work in my code.  I have a plunker which I hope shows my problem; it follows that example but doesn't work.

*

*The component displays one check box for each item in a list (specified as an attribute, should be a one-way binding as the component never changes the value to communicate to the page)

*When one and only one check box is checked, it calls a callback function to
tell the page that the Xor of the bits is true

*There is a "call in" function which clears all the check boxes.  (This works but is kind of irrelevant, it's a vestige of an earlier Plunker for a different problem)

*There is a Add Bit button on the page which adds an item to the list of bits for the component to display

*There is a $watch() in the component controller on the list of bits to display.  Right now it just logs that it was called but something closer to my end goal would be to make sure that the new checkbox is initially set rather than cleared.

The $watch() fires as the page loads (the component is created).  However, when I click the button and add a bit, the ng-repeat which creates the check boxes fires but the $watch() does not.

A: Use a watch collection. Read about it here. The solution applied to your plunkr would be this

 $scope.$watchCollection(
      "vm.myBits",
      function(newValue, oldValue) {
        console.log("a. new bit");
    });

An update version of your plunk
You can also use "deep" object checking by adding a third parameter of 'true' to the watch. However this is very "expensive" and not recommended once watchCollection was introduced in 1.2.x

 $scope.$watch(
      "vm.myBits",
      function(newValue, oldValue) {
        console.log("a. new bit");
    },true); // The TRUE is a deep checking and also works but is "expensive"


text:
Q: Given N coins, each coin can be used at most T times. Is it possible to make value W using minimum N coins? Input Format:
N T (N = number of coins, T = number of times)
C1, C2 .... CN
W
From my solution, I am getting this...
Input:
2 4
5 8
37
Output:
5 (Which is valid, because 37 = (8*4)+(5*1))
Input:
2 2
5 10
30
Output:
3 (Here the output should be 4, because I can't use coins more than 2 times).
Where is the error in my solution?
#include<bits/stdc++.h>
using namespace std;
int coins[100], N, T, mem[100][100];
int solve(int p, int w, int us[])
{
    if(p==N || w<=0){
        if(w==0) return 0;
        return 1e5;
    }
    if(mem[w][p]!=-1) return mem[w][p];
    int ans=1e5;

    if(us[p]<T){
        us[p]++;
        ans=min(1+solve(p, w-coins[p], us), ans);
        us[p]--;
    }
    ans=min(ans, solve(p+1, w, us));
    return mem[w][p]=ans;
}
int main()
{
    cin>>N>>T;
    for(int i=0;i<N;i++){
        cin>>coins[i];
    }
    int w, us[100];
    cin>>w;
    memset(mem, -1, sizeof (mem));
    memset(us, 0, sizeof (us));
    cout<<solve(0, w, us)<<endl;
    return 0;
}

A: Code Problem:
you check if(us[p]<T) but when call function u subtract w-coins[p]...
According to your logic this block:
if(us[p]<T){
        us[p]++;
        ans=min(1+solve(p, w-coins[p], us), ans);
        us[p]--;
    }

would be:
if(us[coins[p]]<T){
        us[coins[p]]++;
        ans=min(1+solve(p, w-coins[p], us), ans);
        us[coins[p]]--;
    }

Your Solution problem:
Your memorization will not work cause u pass p,w and us[] in function but you memorize only p and w.. As you memorize all state of same value p and w and different value of us[].. your solution will not works..
Solution:
You need to take new array with coin array T times...
Lets coin : 5, 10.. and t = 2
Then new array coin array will be: 5 5 10 10
Now if you want to make 30 then try to make 30 using new array:
Try with this code:
#include <bits/stdc++.h>

using namespace std;
int coins[5005], N, M, T, mem[105][5005];
int solve(int p, int w)
{
    if(p==N || w<=0){
        if(w==0) return 0;
        return 1e5;
    }
    if(mem[w][p]!=-1)
        return mem[w][p];
    return mem[w][p] = min(solve(p+1,w), 1 + solve(p+1, w-coins[p]));
}
int main()
{
    cin>>N>>T;
    M = 0;
    for(int i=0;i<N;i++){
        int a;
        cin>>a;
        for (int j = 0; j < T; j++) {
            coins[M++] = a;
        }
    }
    N = M;
    int w, us[100];
    cin>>w;
    memset(mem, -1, sizeof (mem));
    cout<<solve(0, w)<<endl;
    return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I display a thumbnail for my website? When I send my site to someone on Facebook or Messenger, the preview of a website will have the Facebook logo and the description is blank.
It doesn't show my fav icon it shows the Facebook logo. Example:

But if I enter the Twitter URL it displays what Twitter wants to show. Example:

A: You may use meta tags like this:
<meta property="og:url" content="http://www.yourwebsite.com/some_folder/some_fav_icon.png" />
<meta property="og:image" content="http://www.yourwebsite.com/some_folder/some_fav_icon.png" />
<meta property="og:title" content="Your Title" />
<meta property="og:description" content="Your Description" />

A: Pages that render nicely when shared on Facebook (or other sites) use the Open Graph Protocol. You'll find this website helpful


text:
Q: Show user's email when commenting rather than asking for input I created a blog in which users can create comments under posts. Registered users, Admins and Guests will be able to post comments.
So in the _form.html.erb I wrote this:
<%= simple_form_for([@post, @post.comments.build], html: {class: 'form-horizontal' }) do |f| %>
    <% if current_user || current_admin %>
      <% @comment.commenter = current_user.try(:email) || current_admin.try(:email) %>
    <% else %>
      <%= f.input :commenter %>
    <% end %>
    <%= f.input :body %>
    <%= f.button :submit %>
<% end %>

However I get this error: undefined local variable or method `comment'.
When I try to change @comment.commenter to @post.comments I get the error: undefined method `each' for "example@person.com":String.
Is there a way set the commenter's name if its registered. Like in the controller maybe?
The controller code is:
class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(comments_params)
    redirect_to post_path(@post)
  end

  def destroy
    @post = Post.find(params[:post_id])
    @comment = @post.comments.find(params[:id])
    @comment.destroy
    redirect_to post_path(@post)
  end

  private
  def comments_params
    params.require(:comment).permit(:commenter, :body)
  end
end

If you need any other information please let me know.
Thanks

A: <%= simple_form_for(@comment),url: [@post,@comment], html: {class: 'form-horizontal' }) do |f| %>
<%= f.input :commenter, value: comment_by_user %>
<%= f.input :body %>
<%= f.button :submit %>

Helper
def comment_by_user
current_user.try(:email) || current_admin.try(:email) if current_user || current_admin
end
Controller
class CommentsController < ApplicationController
before_filter :find_post
def new
@comment = @post.comments.build
end
def create
@comment = @post.comments.create(comments_params)
redirect_to post_path(@post)
end
def destroy
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
private
def find_post
@post = Post.find(params[:post_id])
end
end

A: Found a solution:
Controller:
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(comments_params)
    if current_admin || current_user
      @comment.commenter = current_user.try(:email) || current_admin.try(:email)
      @comment.save
    end
    redirect_to post_path(@post)
  end

View:
<%= simple_form_for([@post, @post.comments.build], html: {class: 'form-horizontal' }) do |f| %>
    <% if current_admin || current_user %>
    <%= f.input :body %>
    <% else %>
    <%= f.input :commenter %>
    <%= f.input :body %>
    <% end %>
    <%= f.button :submit %>
<% end %>

Thanks for the help.


text:
Q: passing const as this argument discards qualifiers I have the following:
first a string that is not a constant
std::string anId;

an object that is a constant
const Object * object;

This object has a method like
 const std::shared_ptr<RawData> GetRawData(const std::string &);

and there is a function like this
getData(const std::shared_ptr<RawData> raw_ptr);

So, when I do this:
getData(object->GetRawData(anId));

I get the error
error: passing 'const Object ' as 'this' argument discards qualifiers [-fpermissive]
         int stat = getData(object->GetRawData(anId));

Except the first string, I don't see how I am not passing constants...
I wonder where is the error coming from


text:
Q: Java primitive variable reassignment during expression I had a question in my test that I got confused about (code attached below). To put it shortly, I thought that the variables are reassigned and then added back as a value to the expression (making the output "8, 10") but seems like the original value somehow is not changed. What am I missing?
p.s. Sorry if a similar question exists, I couldn't find one (probably its too obvious :P).
class InitTest{
    public static void main(String[] args){
        int a = 10;
        int b = 20;
        a += (a = 4);
        b = b + (b = 5);
        System.out.println(a + ",  " + b);
    }
}

A: a += (a = 4);

The above is logically equivalent to the following:
a = a + (a = 4);

If we substitute in the existing value for a, then this simplifies to:
a = 10 + 4 = 14

We can do the same for b:
b = b + (b = 5) = 20 + 5 = 25

We see this result because of operator precedence. The addition operator, +, has a higher precedence than the assignment operator, =, as defined by the Java operator precedence table.
You can see that the addition-assignment operator, +=, shares the same precedence with the assignment operator, in which case the expression is evaluated from left to right.

If, instead, the expressions were:
a = (a = 4) + a;
b = (b = 5) + b;

Then it would result in the output that you expect (a = 8, b = 10), as the left operand is computed before the right operand (when evaluating the expression). I'll try to locate where this is specified in the Java Language Specification.

A: In Java when assigning a value to a variable, the first thing that is calculated is the left part of the = sign and then the right. Therefore, when you write a += (a = 4); which is equivalant to a = a + (a=4) which is the same as a = a + 4 , same for b.


text:
Q: Add columns in a data frame whose column headers are unique values of another column I am not sure if this particular type of question has been answered before. I did a lot of research but couldn't get exactly what I wanted. I have a data set with many columns. Two of the columns are Organic = c("Yes","Yes","No",...) and StoreBrand = c("No","Yes","No",...). I want to create columns having headers Organic_Yes, Organic_No, StoreBrand_Yes and StoreBrand_No and fill them with 0 and 1. So my expected output will be

Organic
Organic_Yes
Organic_No
StoreBrand
StoreBrand_Yes
StoreBrand_No

Yes
1
0
No
0
1

Yes
1
0
Yes
1
0

No
0
1
No
0
1

.....etc. I want to do this in R. Any help is appreciated
It would be great if the new column headers are not created by brute force. I am looking to automate the process of creating these columns. Thanks again!

A: Here's a simple tidyverse approach:
library(dplyr)

df %>%
  mutate(Organic_Yes = as.numeric(Organic == "Yes"),
         Organic_No = 1 - Organic_Yes,
         Storebrand_Yes = as.numeric(StoreBrand == "Yes"),
         Storebrand_No = 1 - Storebrand_Yes) %>%
  select(Organic, Organic_Yes, Organic_No,
         StoreBrand, Storebrand_Yes, Storebrand_No)

#>   Organic Organic_Yes Organic_No StoreBrand Storebrand_Yes Storebrand_No
#> 1     Yes           1          0         No              0             1
#> 2     Yes           1          0        Yes              1             0
#> 3      No           0          1         No              0             1

Or a more general tidyverse approach:
df %>%
  mutate(across(everything(),
                function(x) 1 * (x == "Yes"),
                .names = "{.col}_Yes")) %>%
  mutate(across(tidyselect::vars_select_helpers$where(is.character),
                function(x) 1 * (x == "No"),
                .names = "{.col}_No")) %>%
  select(order(names(.)))

#>   Organic Organic_No Organic_Yes StoreBrand StoreBrand_No StoreBrand_Yes
#> 1     Yes          0           1         No             1              0
#> 2     Yes          0           1        Yes             0              1
#> 3      No          1           0         No             1              0

Created on 2021-10-21 by the reprex package (v2.0.0)

Data
df <- data.frame(Organic    = c("Yes", "Yes", "No"),
                 StoreBrand = c("No", "Yes", "No"))

df
#>   Organic StoreBrand
#> 1     Yes         No
#> 2     Yes        Yes
#> 3      No         No

Created on 2021-10-21 by the reprex package (v2.0.0)

A: Here is another approach: Using across twice with manipulating the .names argument (learned here: Using a function in .names argument of across function)
library(dplyr)
library(stringr)
df %>%
  mutate(across(everything(), ~ifelse(. == "Yes", 1, 0), .names ="{.col}_Yes"),
         across(contains("Yes"), ~ifelse(. == 1, 0, 1), .names = "{str_replace(.col,'_Yes', '_No')}"))

output:
  Organic StoreBrand Organic_Yes StoreBrand_Yes Organic_No StoreBrand_No
1     Yes         No           1              0          0             1
2     Yes        Yes           1              1          0             0
3      No         No           0              0          1             1


text:
Q: Does the sub class inherit the private data members too in c++? But are accessed through the public methods of the super class? I'm new to c++. I used to believe that the super class private data members and member functions are not inherited by the derived class. But recently I saw a program in which the private member of the super class could be accessed through its public member function. How is it possible when the derived class doesn't have the private data member ..? please clear my concept if I am wrong .

A:
used to believe that the super class private data members and member functions are not inherited by the derived class.

Your understanding is a bit flawed.
The private members still exist in the base class. They are simply not directly accessible by the derived class.

A: Private data members of a class are not accessible from other classes when they are set as private.
But with the use of return functions, it is possible for the child classes to retrieve private data members from the parent class.
Example
class Parent{
    int age = 35;

    public int getAge(){
        return age;
    }
}

class Child : public Parent{

}

int main(){
    Child c;
    printf("%d", c.getAge());
    return 0;
}

The output will be
35


text:
Q: svelte-i18n - Svelte Rollup compiler warning: `this` has been rewritten to `undefined` Since I installed the svelte-i18n library on my Svelte application I have had the following warning when compiling Rollup.
(!) `this` has been rewritten to `undefined`

I also insert the whole error stack trace because maybe it can be useful:
https://rollupjs.org/guide/en/#error-this-is-undefined
node_modules\intl-messageformat\lib\core.js
4: See the accompanying LICENSE file for terms.
5: */
6: var __assign = (this && this.__assign) || function () {
                   ^
7:     __assign = Object.assign || function(t) {
8:         for (var s, i = 1, n = arguments.length; i < n; i++) {
...and 1 other occurrence
node_modules\intl-messageformat\lib\formatters.js
1: var __extends = (this && this.__extends) || (function () {
                    ^
2:     var extendStatics = function (d, b) {
3:         extendStatics = Object.setPrototypeOf ||
...and 3 other occurrences
node_modules\intl-format-cache\lib\index.js
4: See the accompanying LICENSE file for terms.
5: */
6: var __spreadArrays = (this && this.__spreadArrays) || function () {
                         ^
7:     for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
8:     for (var r = Array(s), k = 0, i = 0; i < il; i++)
...and 1 other occurrence

...and 3 other files
created public\build\bundle.js in 1.3s

I believe this error is very similar if not the same described here:
https://github.com/kaisermann/svelte-i18n/blob/master/docs/FAQ.md#this-keyword-is-equivalent-to-undefined
The libraries mentioned in this application have the following versions:
"svelte": 3.22.2
"svelte-i18n": 3.0.3

It seems that this warning is not a problem, however, is tremendously annoying for me.
I don't really like the solution they give in this case ("learn to live with that warning and ignore it"). Is there any way to instruct the compiler to ignore that error or someone already managed to fix it?
EDIT:
My problem was on windows (therefore back slash) and the libraries were the following:
'node_modules\\intl-messageformat\\lib\\core.js',
'node_modules\\intl-messageformat\\lib\\compiler.js',
'node_modules\\intl-messageformat\\lib\\formatters.js',
'node_modules\\intl-format-cache\\lib\\index.js',
'node_modules\\intl-messageformat-parser\\lib\\skeleton.js',
'node_modules\\intl-messageformat-parser\\lib\\normalize.js',
'node_modules\\intl-messageformat-parser\\lib\\parser.js',

A: I found a solution in an article where they linked the necessary Rollup config. Basically you need to add this to rollup.config.js:
moduleContext: (id) => {
  // In order to match native module behaviour, Rollup sets `this`
  // as `undefined` at the top level of modules. Rollup also outputs
  // a warning if a module tries to access `this` at the top level.
  // The following modules use `this` at the top level and expect it
  // to be the global `window` object, so we tell Rollup to set
  // `this = window` for these modules.
  const thisAsWindowForModules = [
    'node_modules/intl-messageformat/lib/core.js',
    'node_modules/intl-messageformat/lib/compiler.js'
  ];

  if (thisAsWindowForModules.some(id_ => id.trimRight().endsWith(id_))) {
    return 'window';
  }
}


text:
Q: UPDATE БД и переоформление вывода без перезагрузки Есть страница, на которой выводятся записи с помощью из БД с помощью такого вот запроса:
SELECT * FROM base WHERE Status < 2 ORDER BY `id` DESC

И у каждой записи есть кпопка удаления:

Удалить
(id уникальный под каждую запись)
Можно ли как-то при нажатии на этот
 получать его id и использовать для того, чтобы обновить БД таким запросом:
UPDATE base SET Status='2' WHERE id = divID

Я знаю, что это можно делать во внешнем PHP скрипте.
А можно ли делать это без перезагрузки страницы? Обновлять БД и обновлять данные на странице снова сделав запрос к БД и выведя ответ(он уже будет без этой записи).

A: Насколько я понял вам нужно что то подобное:
Для работы скрипта нужны два файла index.php и query.php
Код страницы index.php
    <!doctype html>

        <meta charset='utf-8'>

        <?php
        $link = mysqli_connect('localhost', 'root', '', 'arenda');
        if($result = mysqli_query($link, "SELECT * FROM records WHERE number > 2 ORDER BY `id` DESC")){
        while($set = mysqli_fetch_assoc($result)){
        $id = $set['id']; //поле из БД которое выводит ID
    echo '
Ваш ID='.$id.'Удалить<input id="id_rec" type="hidden" value="'.$id.'">
';
        }
        }
        ?>

Код страницы query.php
 <?php

// подключение к бд
$link = mysqli_connect('localhost', 'root', '', 'arenda');
// контейнер для ошибок
$error = false;
// получение данных

$idrec=  $_POST['id_rec'];

if(mysqli_query($link, "UPDATE records SET number='1' WHERE id = '$idrec'")){

}
else{
$error = 'Ошибка при выполнении запроса';
}
// делаем ответ для клиента
if($error){
    // если есть ошибки то отправляем ошибку и ее текст
    echo json_encode(array('result' => 'error', 'msg' => $error));
}else{
    // если нет ошибок сообщаем об успехе
    echo json_encode(array('result' => 'success'));
}
?>

Код файла query_upd.php
<?php
        $link = mysqli_connect('localhost', 'root', '', 'arenda');
        if($result = mysqli_query($link, "SELECT * FROM records WHERE number > 2 ORDER BY `id` DESC")){
        while($set = mysqli_fetch_assoc($result)){
        $id = $set['id']; //поле из БД которое выводит ID
    echo '
Ваш ID='.$id.'Удалить<input id="id_rec" type="hidden" value="'.$id.'">
';
        }
        }
        ?>

По идее должно работать.
Есть другой способ, без AJAX, но выполнение скрипта на этой же странице:
   <!doctype html>

        <meta charset='utf-8'>

        <?php
             $link = mysqli_connect('localhost', 'root', '', 'arenda');

            if(isset($_GET['id'])){
                $idd = $_GET['id'];
               mysqli_query($link, "UPDATE `records` SET number = '1' WHERE id='$idd'");
            }

            ?>
        <?php

        if($result = mysqli_query($link, "SELECT * FROM records WHERE number > 2 ORDER BY `id` DESC")){
        while($set = mysqli_fetch_assoc($result)){
        $id = $set['id']; //поле из БД которое выводит ID
    echo '
Ваш ID='.$id.'Удалить<input id="id_rec" type="hidden" value="'.$id.'">
';
        }
        }
        ?>


text:
Q: Don't print if array is not full I have an array
array('apples', 'oranges', 'grapes', 'watermelons', 'bananas');

And I don't want to print this array if there are only apples and oranges in it. How do I do that?

A: You can take a look at this example here:
$haystack = array(...);

$target = array('foo', 'bar');

if(count(array_intersect($haystack, $target)) == count($target)){
    // all of $target is in $haystack
}

A: Take out the apples and oranges and see if there is anything left.
$arr = array('apples', 'oranges', 'grapes', 'watermelons', 'bananas');
$arrDiff = array_diff($arr, array('apples', 'oranges')); //take out the apples and oranges

if(!empty($arrDiff)) //there's something other than apples and oranges in the array
    print_r($arr);

A: if (in_array('apples', $array) && in_array('oranges', $array) && count($array) == 2)
{
    // Don't print array
}

A: If you know in advance the number of elements to go into the array, then you can do:
<?php
$expectedCount = 5; //in this example, we are looking for five elements in our array
if(count($array) == $expectedCount)
{
    var_dump($array);
}

A: first specify the minimum amount of element the array must have for example in this case its 5
then use function count() whos reference can be found in http://php.net/manual/en/function.count.php
if(count(array) >= 5)

{
  //perform action

}


text:
Q: C# AES Function not returning expected results I'm using this function to Encrypt/Decrypt data using AES because it looked simple and clean (googl'ed code)
public static string Encrypt(string toEncrypt)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes("3a8114db34d5623d4fd1ee0fb0ga7a73"); // 256-AES key
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.CBC;
        rDel.Padding = PaddingMode.PKCS7; // better lang support
        ICryptoTransform cTransform = rDel.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
    public static string Decrypt(string toDecrypt)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes("3a8114db34d5623d4fd1ee0fb0ga7a73"); // AES-256 key
        byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.CBC;
        rDel.Padding = PaddingMode.PKCS7; // better lang support
        ICryptoTransform cTransform = rDel.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        return UTF8Encoding.UTF8.GetString(resultArray);
    }

I'm trying to encrypt the data "test garbage" and thats what i receive back:

YfhyS3GE/liPCaXR0cMHfQ==

However, I tried the same key/phrase on a lot of online-aes encrypt/decrypt and all of them are returning

U2FsdGVkX184u0/vPgA/B0rxofp5Iuqm7hfn4+QZAhg=

Can anyone actually tell me whats wrong?

A: First a few issues with your code. Apparently Google doesn't always return the best code on top.

*

*You are getting a key through the UTF8 encoding, which is silly. This produces a very weak key:

 // 256-AES key
 byte[] keyArray = UTF8Encoding.UTF8.GetBytes("3a8114db34d5623d4fd1ee0fb0ga7a73");

*

*You are using CBC mode but the IV is not (explicitly) set.

Then you compare to some  online-aes encrypt/decrypt services and you see a difference. That's because they probably (hopefully) work different.
The main thing here is that your 2 methods are a match and you can round-trip your data. But a good encryption would use a different way to get Key and IV.
I'm not exactly sure why you see a different (smaller) length encrypted data but that's up to a whole list of settings : Key length, Padding mode etc.

A: "3a8114db34d5623d4fd1ee0fb0ga7a73" is hex encoded 128 bit key not a utf8 encoded 256 bit key.
That said simple and clean doesn't necessarily mean correct. For example, the code your using does use a random IV, but doesn't include it in the wire format, you'll never be able to decrypt what you encrypt.
I have a cut and paste style simple code sample that I try to keep up to date and reviewed that uses authenticated encryption using AES:
Modern Examples of Symmetric Authenticated Encryption of a string. C#


text:
Q: Get duplicate users from orders table I am trying to find a way to detect the users who have duplicate accounts and ordered from a table I have on my database.  I've made some complex queries and haven't been to solve my problem.
First thought was to group by ip and count(user_id) but users can have more than one order so these wll be counted as well (eg if I use the above, the ip "192.168.1.1" will return 3 and not 2 which I want
My data is like
| order_id  |  user_id  |     ip      |
---------------------------------------
| 1001      |   2       | 192.168.1.1 |
| 1002      |   5       | 192.168.1.1 |
| 1003      |   2       | 192.168.1.1 |
| 1004      |   12      |   18.15.0.1 |
| 1005      |   9       |    10.0.0.1 |

Result needed
IP 192.168.1.1 cause it has 2 different user_id
Any help is appreciated

A: use Distinct inside your Count
SELECT COUNT(Distinct user_ID)
FROM table
GROUP BY ip

A: Try this:
SELECT t.ip, t.user_id,
   (SELECT COUNT(1)
   FROM yourtable t3 WHERE t.user_id = t3.user_id
   AND t.ip = t3.ip) as total
FROM yourtable t
WHERE EXISTS(
    SELECT 'duplicate'
    FROM yourtable t2
    WHERE t.user_id = t2.user_id
    AND t.ip = t2.ip
    AND t.order_id < t2.order_id
)

A: You are looking for IPs given to more than one user? Then group by IP and count distinct users.
select ip
from mytable
group by ip
having count(distinct user_id) > 1;

EDIT: To get the users associated with that
select user_id, ip
from mytable
where ip in
(
  select ip
  from mytable
  group by ip
  having count(distinct user_id) > 1
);

And here is the same with an EXISTS clause:
select user_id, ip
from mytable
where exists
(
  select *
  from mytable other
  where other.ip = mytable.ip
  and other.user_id <> mytable.user_id
);


text:
Q: How build array in javascript and receive it in c# mvc controller It's possible to build an array in jquery/javascript to send it to my controller c# ?
I get a list of employes from a select multiple, i can alert them like this :

        <select style="display:none" id="liste" multiple="" placeholder="Select">
            @foreach (var employe in ViewBag.Employes)
            {
            <option value="@employe.ID_Employe">@employe.Name</option>
            }
        </select>

    Suivant

My script :
        $('#check').on('click', function () {
            $("#liste").find("option:selected").each(function () { alert($(this).text()); });
        });

I send data like this :
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '/MyAjaxRoute',
            data: { arraytosend: arraybuildInJS },
            success: function (response) {
                if (response.success) {
                    alert('yes');
                }
        },

*

*Can you explain me how to make an array in js and to receive it in a c# mvc controller ?

A: I guess push is what you're looking for.
var arraybuildInJS = [];
$('#check').on('click', function () {
            $("#liste").find("option:selected").each(function () { arraybuildInJS.push($(this).text()); });
        });

Remember you should expect an Enumerable of string in your controller. As you don't code it, try matching the objects.

A: First create an Action in your Controller as:
public JsonResult SaveArrayData(List<string> myData)
{
   if(myData.Count == 0) return Json(new {success = false});

   //do something with myData
   return Json(new {success = true});
}

Then in your js code you can do the following:
var array = [];
$('#check').on('click', function () {

$("#liste").find("option:selected").each(function () {
    array.push($(this).text)
});

$.ajax({
     type: 'POST',
     dataType: 'json',
     url: '@Url.Action("SaveArrayData", "MyController")',
     data: { myData: array },
     success: function (response) {
       if (response.success) {
          array = [];//empty the array you can also use array.length = 0
          alert('yes');
       }
     }
   });
});

A: Thx your for your answers, i can succesfull send my data but i dont find the way to  parse it in my c# controller
public ActionResult GetAjaxSession(string searchequipe)
    {
        if (searchequipe != null)
        {
            var equipe_decode = HttpUtility.UrlDecode(searchequipe);

// how to parse my json variable : searchequipe ?

            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }

        return null;

    }


text:
Q: Safari flex vertical align issue I'm trying to align vertically a div inside another div using flex boxes. This code is working on Chrome, IE Edge, Opera and Firefox:
.editing-viewport {
  display: flex;
  display: -webkit-flex;
  flex-direction: column;
  -ms-flex-direction: column;
  align-items: center;
  justify-content: center;
  -webkit-justify-content: center;
  -webkit-box-align: center;
  -webkit-flex-align: center;
  -webkit-align-items: center;
  -webkit-box-sizing: border-box;
}

But on Safari, the div inside the editing-viewport div does not look completely centred on the Y axis. Looks like there are some extra pixels above the div.


text:
Q: Creating folders using loop import xml.etree.cElementTree as ET
import os
path = r'C:\Users\LME_s\Desktop\python quiz\Sessions'
for filename in os.listdir(path):
    if not filename.endswith('.xml'): continue
    fullname = os.path.join(path, filename)
    tree = ET.parse(fullname)
    root=tree.getroot()
    numbers = [e.attrib['Number'] for e in root.findall('.//ActionUnit')]
    base_path = r'C:\Users\LME_s\Desktop\python quiz\Sessions/new'
    for folder in numbers:
        os.mkdir(os.path.join(base_path, folder))

    #print(numbers)

I created a loop that reads XML data and put this data on the array dynamically. This is the output, So here is my question. In each iteration, I need to create folders named "AU45" and  "not AU45" for each array element. Here is a problem, in the first iteration I created a folder which is named "10" but in the next iteration I also have another 10 value and I get an exception because a folder named "10" also exists. How can I avoid this?

A: Keep the created folders in a set.
import xml.etree.cElementTree as ET
import os
path = r'C:\Users\LME_s\Desktop\python quiz\Sessions'
created_folders = set()
for filename in os.listdir(path):
    if not filename.endswith('.xml'): continue
    fullname = os.path.join(path, filename)
    tree = ET.parse(fullname)
    root=tree.getroot()
    numbers = [e.attrib['Number'] for e in root.findall('.//ActionUnit')]
    base_path = r'C:\Users\LME_s\Desktop\python quiz\Sessions/new'
    for folder in numbers:
        if folder not in created_folders:
            os.mkdir(os.path.join(base_path, folder))
            created_folders.add(folder)


text:
Q: Python Selenium Chrome Unable to Find Element? I'm new to Selenium, and I'm having trouble figuring out how to automate finding elements such as buttons and text fields. Here's what I have:
import os
from selenium import webdriver

os.environ["PATH"] = "chromedriver_win32"
driver = webdriver.Chrome()
driver.get("https://signup.mail.com#.7518-header-signup1-1")
driver.find_element(
    "xpath",
    '//*[@class="pos-form-element pos-text-input email-alias-input__alias-input ng-pristine ng-invalid ng-touched"]',
)

I'm confused because it's saying it cannot find the element. Is there anything obvious that I'm doing wrong? I'm not sure how to fix this.

A: You can find your element using something like element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//*[@class="pos-form-element pos-text-input email-alias-input__alias-input ng-untouched ng-pristine ng-invalid"]'))).


text:
Q: How do you describe something bad, that everyone wants? Like - trying to catch a disease on purpose.

A: From my point of view, it can only be "a masochist's dream" or "a masochist's delight".
Anyone who wishes for something bad for himself (like catching a disease) can only be a masochist, at least from everybody else's point of view.

*

*masochist (noun) someone who derives pleasure, from being humiliated or mistreated, either by another or by oneself. Someone who has a tendency to subject himself to unpleasant or trying experiences. TFD


text:
Q: Unable to install gem I am getting this error, when trying to install any gem
ERROR:  http://gems.rubyforge.org/ does not appear to be a repository
But when I do gem sources, it shows
* CURRENT SOURCES *
http://gems.rubyforge.org/

A: Perhaps you have an http proxy in your network? What do you see when you go to the page http://gems.rubyforge.org/ directly (using your browser)? Or even better: what happens if you wget the url 'http://gems.rubyforge.org/yaml'?

A: You may need to update rubygems.


text:
Q: Survival Curve from Cox Regression I want to estimate the survival curve from Cox Regression. In another question I found the following formula:
$$\hat{H}_0(t)=\int_0^t\frac{dN(\tau)}{\sum_i \exp(\beta^T x_i)Y_i(\tau)}$$
(Estimating survival curves from Cox regression results)
I guess I am getting this terribly wrong, I am self studying and don't really grasp the meaning of the formula, but I tried:
If I have a dummy dataset like (From Thereneau Modeling Survival Data). I inserted how I would (my best guess) do the calculation for the estimated $\beta=2$.

time
event
x
denominator
numerator
$\hat H_0$

1
1
1
4
6
6/4

1
0
1
2
6
6/2

6
1
1
2
4
4/2

6
1
0
0
4
?

8
0
0
0
2

9
1
0
0
1

I would appreciate any help pointing me in the right direction.

A: You started well, putting cases in order of event/censoring times, and choosing a short set of example data that illustrates the critical issues. Here's how to proceed, with my attempt at verbal descriptions of the symbols, which can be quite confusing at first.
Go time point by time point sequentially from first to last event time, stopping to do a calculation at each event time, and then adding the result to the previous results. Cumulative hazard at $t=0$ is 0.
At each event time $\tau$, the numerator $dN(\tau)$ is the number of cases having events at time $\tau$. So in your data, that's 1 at $\tau=1$, 2 at $\tau=6$, and 1 at $\tau=9$. There is no event at $\tau=8$, so $dN(8)=0$. No calculation needs to be done at that time, as only a 0 would be added.
The terminology in the denominator can be particularly confusing. The sum is over all cases $i$. $Y_i(\tau)$ is an indicator value, equal to 1 if case $i$ is at risk at time $\tau$, and 0 otherwise. What that means in practice is: just do the sum for the cases still at risk at time $\tau$, as all the others just provide values of 0. The $\exp(\beta^Tx_i)$ factor is the exponential of the linear predictor for case $i$. In your situation, for $x_i=0$ that's a value of 1; for $x_i=1$ and $\beta=2$ it's $\exp(2) \approx 7.389$. You sum those up over all cases at risk at time $\tau$ to get the denominator.
Now just go through the tedious task of putting it all together by hand. I'll do this out for all 3 event times here, as each makes a different point about the calculation.
At $\tau =1$, the numerator $dN(1)$ is 1. The denominator is the sum of exponentiated linear-predictor values for all cases at risk at $\tau =1$, or all cases. If these 6 were your only cases, then the sum in the denominator (with 3 having $x=0$ and three having $x=1$) would be 3*1 + 3*7.389, or 25.167. The ratio (1/25.167) is also the estimated cumulative baseline hazard through $t=1$.
At $\tau=6$, the numerator $dN(6)$ is 2. The denominator sum now only includes the 4 cases still at risk, 1 with $x=1$ and 3 with $x=0$. You have 3*1 + 1*7.389 in the denominator sum, or 10.389. The ratio (2/10.389) is the added contribution to cumulative hazard at $\tau=6$. You add that value to the prior value to get the cumulative hazard through $t=6$. (An integral over a discrete $dN(\tau)$ is just the sum over all the individual values.)
There is no event at $\tau=8$, so proceed to $\tau=9$. There is 1 event, so the numerator is 1. There is now only one case at risk, this case, with $x=0$ and thus a denominator of 1. That's the added contribution to cumulative hazard at $\tau=9$. Add that to the prior value of cumulative hazard and you have the cumulative hazard through the last event time, $t=9$. You have no more events, so you are done with your estimate of the baseline cumulative hazard.
This Aalen-Breslow baseline hazard estimate $\hat H_0(t)$ is for a linear-predictor value of 0, or $x=0$ in this case. For a different set of covariate values $x$, you multiply the baseline hazard by the corresponding hazard ratio to get, say, $\hat H_x(t)$. The estimated survival curves are then given by $S_0(t)=-\exp \hat H_0(t)$ and $S_x(t)=-\exp \hat H_x(t)$.


text:
Q: With WinDbg, can I modify an item in memory while a process is running? Can I, using an address found in a map file, use windbg to alter a variable in memory while the app is running?
I'm really interested in turning on/off functionality in run-time maybe with a variable.
How would you do this? Does it require breaking the app through the debugger?

A: If you have the address, you can use the any of the e* (Enter Value) commands.
You can attach to any running process if you know the process id, or you can launch the exe directly with cdb.  You do have to break the process to make any modifications.  In CDB, you can use Ctrl+C, and the it will inject a DebugBreak into the process, you can then look at the stack, threads, and memory.

A: I just did it.  Assuming you got the symbos mapped, and are in a breakpoint where you can see a variable, you just do this - assuming "myvar" is an integer:
?? myvar
   [[ this shows the current contents ]]
?? myvar=55
   [[ this will change the value of myvar to 55]]
?? myvar
   [[ this will show the updated contents of my var - which is 55 ]]
g
   [[ your program will now run, and the next read of myvar will produce 55 ]]

A: You can set a breakpoint that is only hit once and edit a value and continue execution.
Something like:
bp /1 012ABCDEF "myVar=42;g"

replace the above with your address value and your variable name.

A: I'm not sure  what exactly you trying to achieve, but debugger should be activated on some event (exception, break point or something), after it's activated, for example you can have a thread that create an exception and after get control back check the variable.
In debugger you can set a break point with command, see this guide, what will change the parameter.
I hope that this answer your question, if not please clarify the question.
In case of break point with command the application will be break and will continue execution without human intervention, i don't know any way how debugger can do something without application stops execution.
Just a thought, are you sure you need debugger for this? Can't you just use registry for that and use this to get notification about registry change.

A: You can definately do that.  Either break on a function and edit it in the locals window.  Or use e commands to edit values.  Check out the windbg help for more on it.


text:
Q: Ajax invalidating viewstate
The state information is invalid for this page and might be corrupted

This seems to be a pretty common question. But I have not yet found a post where the basic issue is addressed.
I have a heavily ajaxed application and I am running into this.
In a nutshell, the ASPX page is litle more than a series of divs that are populated w/ HTML by AJAX calls.
If anyone has comments on these basic questions I would greatly appreciate it. I will begin a sample app and see if I can answer them as well.

*

*Does the removal of runat=server controls w/ Ajax cause this.

*If i populate a DIV w/ the HTML that is generated by a runat=server control , will that trigger this.

*Is there a way to lobotomize a runat=server control before returning it as part of an ajax ctl.

( For example - a repeater is really nice to build a table. Can i use the repeater and then remove some syntax from the HTML before I send the response to the client.
I can do the looping if i have to..
)
4)  Is there something I can put in the header to make this whole thing go away.
Page Language="vb"
AutoEventWireup="false"
CodeBehind="frustration.aspx.vb"
_Inherits="Portal.frustration"
EnableViewState="false"
enableViewStateMAC="false"
EnableEventValidation="false"
ValidateRequest="false"
ViewStateEncryptionMode="Never"
MasterPageFile="~/_MasterPages/Admin.Master"

Thanks,
greg.

A: Well, I got it to work, but I'm abandoning the .NET menu anyway.
Since I was looking for some high level information, I will let the community what I was able to do...
The viewstate issue happens when I load the AJAX page then navigate using the menu. It happens because clicking the menu posts back to my AJAX page before it navigates away. If it were just a hyperlink, there would be no issue.
The AJAX page in question is essentially 3 divs.
Div_A is a navigation element consisting of a list of documents.
Div_B is a read only detail of 1 document w/ some action buttons.
Div_C is an input form.
The divs are populated by jQUery ajax calls. On success, I replace the entire innerHTML of the DIV in question.
Div_A  & Div_B  are automatically populated at page load in that order. (List and first document detail)
Breaking things down, just populating Div_A caused the problem.
Inspection showed that I had some DIVs w/ RUNAT=SERVER. I removed that. This did not resolve the problem.
There was also a FORM around the entire content. The form was tagged runat=server.
I removed the FORM completely. This allowed me to use the menu without the viewstate error. However, If i clicked a second document, causing  Div_B to reload. The problem reoccurred.
Div_B had the same FORM surrounding everything. (These must have be placed automatically by Visual Studio. There is no reason to have either form as both DIV_A and DIV_B are readonly)
The interesting thing about DIV_B is that there are DIVs with RUNAT=SERVER that I need because I set the innerText in the code behind.
Removing the FORM allowed me to navigate between documents and still be able to use the menu without VIEWSTATE errors.
So :
Having RUNAT=SERVER HTML elements added to a page DOES NOT seem to break VIEWSTATE
Having a RUNAT=SERVER FORM added to a page DOES seem to break VIEWSTATE.
So things are back to working, but why did this problem crop up suddenly? Not sure. Much has changed and I can't point to any 1 thing. (Maybe the FORMs got autogenerated when I upgraded from vs10->vs12). Who knows, who cares...
Ultimately - I can't continue to coddle this problem just for the sake of the .NET menu item. To @Brad M's point, I have decided to just use a jQuery menu and that will eliminate any wholesale page postbacks to this page.
A little searching and I uncovered arnab_bandyopadhyays' implementation of a horizontal jQuery menu which he demonstrates here: http://jsfiddle.net/yRJ9g/.
<<stackoverflow wants some code if i reference jsfiddle, so here ya go...>>
dim viewStateWorksWellWAjax as boolean =false

Thanks for the suggestions.
Greg


text:
Q: colab crashed due to unknown reasons Hi I am working in google colab and it crashing with unknown reason,
I've tried to view runtime logs and I am getting this error
ERROR:asyncio:Future exception was never retrieved
Can someone please hep me with this issue


text:
Q: Oracle UPDATE using SELECT statement that includes JOIN I'm porting an H2 UPDATE/SELECT statement to Oracle, and am running into a syntax issue that I'm having trouble diagnosing.
I have 3 tables, Users, Cars, and Trips. They look like:
SELECT * FROM USERS;
+------------+----+--------+
|  USERNAME  | ID | CAR_ID |
+------------+----+--------+
| John.Smith |  1 |     5  |
| Abby.Smith |  2 |     6  |
+------------+----+--------+

SELECT * FROM CARS;
+----+--------+-------+
| ID |  MAKE  | COLOR |
+----+--------+-------+
|  5 | Subaru | Green |
|  6 | Honda  | Red   |
+----+--------+-------+

SELECT * FROM TRIPS;
+----+------------+---------+
| ID |  USERNAME  | MILEAGE |
+----+------------+---------+
|  8 | Abby.Smith |      87 |
|  9 | John.Smith |      23 |
+----+------------+---------+

However, we have now decided to add a new column to Trips, and keep track of the car model (only) instead of the user. As an intermediate result, before dropping the USERNAME column, I'm trying to achieve:
+----+------------+---------+-----------+
| ID |  USERNAME  | MILEAGE | CAR_MODEL |
+----+------------+---------+-----------+
|  8 | Abby.Smith |      87 |     Honda |
|  9 | John.Smith |      23 |    Subaru |
+----+------------+---------+-----------+

And my (non-functional) statement looks like:
WITH USER_MODELS AS
(SELECT USERNAME, MAKE FROM USERS JOIN CARS ON (USERS.CAR_ID = CARS.ID))
UPDATE TRIPS SET CAR_MODEL =
    SELECT MAKE FROM USER_MODELS
    WHERE TRIPS.USERNAME = USER_MODELS.USERNAME

However, the syntax error I receive is:
UPDATE TRIPS SET CAR_MODEL =
*
ERROR at line 3:
ORA-00928: missing SELECT keyword

Which is throwing me for a loop. The SELECT statement is immediately following the UPDATE, which is itself preceded by a WITH clause that seems to include a properly-formatted SELECT.

A: It can be done, but you need to put the WITH clause inside the subquery:
UPDATE TRIPS SET CAR_MODEL =
( WITH USER_MODELS AS
       (SELECT USERNAME, MAKE FROM USERS JOIN CARS ON (USERS.CAR_ID = CARS.ID))
  SELECT MAKE FROM USER_MODELS
   WHERE TRIPS.USERNAME = USER_MODELS.USERNAME
);


text:
Q: Laravel set value in get route I have one route which is accepting one argument perfectly as
  Route::get('view-request/type/{type}/id/{id}', 'CustomerReqController@testing')->name('request.manage');

and also call it in blade by this
'new','id'=>'data'])}}"

and the controller is
public function testing(Request $request,$type,$id){
    dd($request->all());
}

it gives me error

Missing required parameters for [Route: request.manage] [URI: admin/view-request/type/{type}/id/{id}]. (View: /var/www/html/ehs_crm_laravel/resources/views/common/navbar.blade.php) (View: /var/www/html/ehs_crm_laravel/resources/views/common/navbar.blade.php) (View: /var/www/html/ehs_crm_laravel/resources/views/common/navbar.blade.php)

What am i doing wrong?

A: use:
 'new', 'id' => 'data']) }}">

A: you can get your route parameter by simply using this code.  hope this will work for you. for Get and Post method both.
public function testing(Request $request)
{
    $type= $request->type;
    $id= $request->id;

}

A: follow steps this code is working to me.
1 : declare route
Route::get('view-request/type/{type}/id/{id}', 'UserController@index')->name('request.manage');

2: create link
'test','id'=>6]) }}">Register

3: get data in controller
public function index($type,$id,Request $request){
        echo $type;
        echo $id;

    }


text:
Q: Html.ActionLink Fires on Load Unintentionally I have a Partial View for showing the list of products. In this view I have  ActionLinks above each column to handle sorting. There are total 4 of them and they are all identical to below one:
 <div class="col-xs-2">
    @Html.ActionLink(Html.DisplayNameFor(m => m.ProductName).ToHtmlString(), "Products", AppendQueryString.AppendQuery("sortOrder", ViewData["ProductNameSort"].ToString()))
</div>

In order to be able to append the current URL without losing any previously querystrings, I created a static class AppendQueryString and a method in it called AppendQuery. The class looks like below:
 public static RouteValueDictionary AppendQuery(string key, string value)
    {
        RouteValueDictionary routeValues = new RouteValueDictionary();
        var context = HttpContext.Current;
        var req = context.Request.QueryString;

        foreach (string qkey in req)
        {
            routeValues[qkey] = req[qkey];
        }

        if (!routeValues.ContainsKey(key))
        {
            routeValues.Add(key, value);
        }
        else
        {
            routeValues.Remove(key);
            routeValues.Add(key, value);
        }

        return routeValues;
    }

First I didn't realize what was the problem but something was trying to rewrite the same key value sent into this method so I had to use that ugly if-else there to add the key-value into the RouteValueDictionary properly and continue on with the project.
However, now the problem is obvious that for some reason, on page loading these four ActionLinks I have are being fired one after another so the AppendQuery method is being called 4 times on page load. The main View that renders this partial view is being called only once I am sure about it. Any of you have any idea why is this happening ? Thanks in advance.


text:
Q: How to get TD cell values using jquery I would like to get the text from the first and second TD which has the class user and id

  Item model number
  GL552VW-CN426T

I have tried this jQuery code but didn't work for me:
$(".item-model-number").find("td").each(function() {
  var test = $(this).text();
  alert(test);
}

I want to retrieve GL552VW-CN426T from inside the second td tag in the tr.

A: You just need to amend your selector to get the correct element:

$(".item-model-number .value").each(function() {
  var value = $(this).text();
  console.log(value);
})

    Item model number
    GL552VW-CN426T

A: If you're always getting the second td tag that contains the value, you can just use the class selector to select the DOM element using $('.item-model-number .value').
If you want to get the second td tag without using the class name on it, you can do an nth of type selector using $('.item-model-number td:nth-of-type(2)').
To get the content of the DOM element, you can call .text() on the jQuery elements returned by the selector so the whole thing would look like $('.item-model-number .value').text() or $('.item-model-number td:nth-of-type(2)').text()


text:
Q: $ fyne package -os linux ... RESULT is: bash: fyne: command not found After having coded and built my first app using the fyne toolkit, the next task is distribution. Following the instructions at https://developer.fyne.io/started/packaging
The command "fyne package -os linux -icon myapp.png" only produces "bash: fyne: command not found"
It would seem that there is a missing directory in my $PATH or $GOPATH variables or some other place that it needs to be, so that the 'fyne' cmd-tool can be found.
While my experience with the fyne toolkit has been very productive and enjoyable otherwise (been able to puzzle out every other difficulty) this issue has bested me.
Please, please, somebody help me!
Maybe I'm just blind to what I cannot see. ;)
My app is beautiful (of course it is, everyone thinks their work is beautiful), but it's all for nothing if it can't be distributed. What will it matter if nobody ever gets to use it? Ugh, to be so close, yet sooooo far.

A: My version is gov1.18 and the above answer does not solve my problem. I use go insall  instead of go get

A: You need $GOPATH/bin in your $PATH. Sometimes the Go installer does not do this, and sometimes you just need to close the terminal or log out and try it again.


text:
Q: Parse search table not returning correct results I am using parse as back-end for my app. I have found a few different methods to implement searchbar feature using a Parse tableview. This idea I found from Parse archives shows all objects on initial view and refresh, but when I search it does not return the correct results. If I type one letter "a" it returns some objects containing "a" but if I type more letters or and actual word that I know should be found it returns a blank table. It is also giving a warning when searching: A long-running Parse operation is being executed on the main thread.   I have been working and researching this for a few weeks and can't get past this point. See code for implementation file.
#import "RecipeBookViewController.h"
#import "SearchedResultCell.h"
#import "RecipeDetailViewController.h"
#import "HotelViewController.h"
#import "Recipe.h"

static NSString *const NothingFoundCellIdentifier = @"NothingFoundCell";

@interface RecipeBookViewController ()

@end

@implementation RecipeBookViewController {

}

@synthesize searchedBar;
@synthesize searchResults;
@synthesize recipesTable;

- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if (self) {
    // Custom the table

    // The className to query on
    self.parseClassName = @"Recipe";

    // The key of the PFObject to display in the label of the default cell         style
    self.textKey = @"name";

    // Whether the built-in pull-to-refresh is enabled
    self.pullToRefreshEnabled = YES;

    // Whether the built-in pagination is enabled
    self.paginationEnabled = NO;

    // The number of objects to show per page
    //self.objectsPerPage = 10;
}
return self;
}

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

#pragma mark - UIViewController

- (void)viewDidLoad
{
[super viewDidLoad];

    UINib *cellNib = [UINib nibWithNibName:NothingFoundCellIdentifier     bundle:nil];
    [self.tableView registerNib:cellNib     forCellReuseIdentifier:NothingFoundCellIdentifier];

[self.searchedBar becomeFirstResponder];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(refreshTable:)
                                             name:@"refreshTable"
                                           object:nil];
}

- (void)refreshTable:(NSNotification *) notification
{
// Reload the recipes
[self loadObjects];
}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"refreshTable"         object:nil];
}

#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchResults removeAllObjects];

[self.searchedBar resignFirstResponder];

searchResults = [NSMutableArray arrayWithCapacity:10];

//#warning Put your ClassName here
PFQuery *query = [PFQuery queryWithClassName:@"Recipe"];

//#warning put key that you want to search here
[query whereKey:@"name" containsString:searchedBar.text];

NSArray *results = [query findObjects];

[searchResults addObjectsFromArray:results];

//#warning put your key here
[query orderByAscending:@"name"];

//[self queryForTable];
[self loadObjects];

}

#pragma mark - PFQueryTableViewController

- (void)objectsWillLoad {
[super objectsWillLoad];

// This method is called before a PFQuery is fired to get more objects
}

- (void) objectsDidLoad:(NSError *)error
{
[super objectsDidLoad:error];

NSLog(@"error: %@", [error localizedDescription]);
}

#pragma mark - Query

- (PFQuery *)queryForTable
{
PFQuery *query;

if (self.searchResults == 0) {
    query = [PFQuery queryWithClassName:self.parseClassName];
} else {
    query = [PFQuery queryWithClassName:self.parseClassName];

    NSString *searchThis = [searchedBar.text lowercaseString];
    //#warning key you wanted to search here
    [query whereKeyExists:@"name"];
    [query whereKey:@"name" containsString:searchThis];
}

[query orderByAscending:@"name"];

// If Pull To Refresh is enabled, query against the network by default.
if (self.pullToRefreshEnabled) {
    query.cachePolicy = kPFCachePolicyNetworkOnly;
}

// If no objects are loaded in memory, we look to the cache first to fill the     table
// and then subsequently do a query against the network.
if (self.objects.count == 0) {
    query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}

return query;
}

/*
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:    (NSInteger)section
 {
 if (searchResults == nil) {
 return 0;
 } else if ([searchResults count] == 0) {
 return 1;
 } else {
 return [self.objects count];
 }
 }
 */

// Override to customize the look of a cell representing an object. The     default is to display
// a UITableViewCellStyleDefault style cell with the label being the first key     in the object.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:        (NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *simpleTableIdentifier = @"RecipeCell";

UITableViewCell *cell = [tableView     dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault     reuseIdentifier:simpleTableIdentifier];
    }

// Configure the cell
PFFile *thumbnail = [object objectForKey:@"imageFile"];
PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
thumbnailImageView.image = [UIImage imageNamed:@"recipeBoxImage2.jpg"];
thumbnailImageView.file = thumbnail;
[thumbnailImageView loadInBackground];

UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
nameLabel.text = [object objectForKey:@"name"];

UILabel *prepTimeLabel = (UILabel*) [cell viewWithTag:102];
prepTimeLabel.text = [object objectForKey:@"prepTime"];

static NSString *LoadMoreCellIdentifier = @"LoadMoreCell";

UITableViewCell *loadcell = [self.tableView     dequeueReusableCellWithIdentifier:LoadMoreCellIdentifier];
if (!cell) {
    loadcell = [[UITableViewCell alloc]     initWithStyle:UITableViewCellStyleDefault reuseIdentifier:LoadMoreCellIdentifier];
}

return cell;
}

- (void)configureSearchResult:(SearchedResultCell *)cell atIndexPath:    (NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *simpleTableIdentifier = @"RecipeCell";

SearchedResultCell *searchcell = [self.tableView     dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (searchcell == nil) {
    searchcell = [[SearchedResultCell alloc]     initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}

// Configure the cell
PFFile *thumbnail = [object objectForKey:@"imageFile"];
PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
thumbnailImageView.image = [UIImage imageNamed:@"recipeBoxImage2.jpg"];
thumbnailImageView.file = thumbnail;
[thumbnailImageView loadInBackground];

UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
nameLabel.text = [object objectForKey:@"name"];

UILabel *prepTimeLabel = (UILabel*) [cell viewWithTag:102];
prepTimeLabel.text = [object objectForKey:@"prepTime"];

}

// Set CellForRowAtIndexPath
- (UITableViewCell *)searchtableView:(UITableView *)searchtableView     cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
{
static NSString *CellIdentifier = @"SearchResultCell";

//Custom Cell
SearchedResultCell *cell = [searchtableView     dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[SearchedResultCell alloc]     initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

}
if ([searchResults count] == 0) {
    //cell.mainTitle.text = @"Nothing Found";
    return [self.tableView     dequeueReusableCellWithIdentifier:NothingFoundCellIdentifier];
} else {
    //#warning put your ClassName here
    PFObject *object = [PFObject objectWithClassName:@"Recipe"];
    object = [searchResults objectAtIndex:indexPath.row];
    [self configureSearchResult:cell atIndexPath:indexPath object:object];
    //[self configureSearchResult:cell atIndexPath:indexPath object:object];

    return cell;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView     cellForNextPageAtIndexPath:(NSIndexPath *)indexPath {
static NSString *LoadMoreCellIdentifier = @"LoadMoreCell";

UITableViewCell *cell = [tableView     dequeueReusableCellWithIdentifier:LoadMoreCellIdentifier];
if (!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault     reuseIdentifier:LoadMoreCellIdentifier];
}
return cell;
}

//// Set TableView Height for Load Next Page
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:    (NSIndexPath *)indexPath {
//    if([self.objects count] == indexPath.row) {
//        // Load More Cell Height
//        return 60.0;
//    } else {
//        return 80.0;
//    }
//}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

[tableView deselectRowAtIndexPath:indexPath animated:YES];

[searchedBar resignFirstResponder];

if ([self.objects count] == indexPath.row) {
    [self loadNextPage];
} else {
    PFObject *photo = [self.objects objectAtIndex:indexPath.row];
    NSLog(@"%@", photo);

    // Do something you want after selected the cell
}
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[self.searchedBar resignFirstResponder];
}

//- (void)tableView:(UITableView *)tableView commitEditingStyle:    (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath     *)indexPath
//{
//    // Remove the row from data model
//    PFObject *object = [self.objects objectAtIndex:indexPath.row];
//    [object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//        [self refreshTable:nil];
//    }];
//}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    RecipeDetailViewController *destViewController =     segue.destinationViewController;

    PFObject *object = [self.objects objectAtIndex:indexPath.row];
    Recipe *recipe = [[Recipe alloc] init];
    recipe.name = [object objectForKey:@"name"];
    recipe.imageFile = [object objectForKey:@"imageFile"];
    recipe.prepTime = [object objectForKey:@"prepTime"];
    recipe.ingredients = [object objectForKey:@"ingredients"];
    recipe.instructions = [object objectForKey:@"instructions"];
    recipe.servings = [object objectForKey:@"servings"];
    recipe.hotelSite = [object objectForKey:@"hotelSite"];
    recipe.recipeType = [object objectForKey:@"recipeType"];
    destViewController.recipe = recipe;

}
}

@end

A: found this  - hope it helps others - credit to Bizzi-Body
https://github.com/Bizzi-Body/ParseTutorial-Part-2
//
//  GourmetChefViewController.m
//
//  Created by RedMac on 3/19/15.
//

#import "RecipeBookViewController.h"

@interface RecipeBookViewController ()
{
NSMutableArray *totalStrings;
NSMutableArray *filteredStrings;

BOOL isFiltered;
}

@end

@implementation RecipeBookViewController

#pragma mark -
#pragma mark UIViewController

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
self.mySearchBar.delegate =self;
self.myTableView.delegate = self;
self.myTableView.dataSource=self;

[self retrieveFromParse];

}

- (void) retrieveFromParse {
PFQuery *retrieveRecipes = [PFQuery queryWithClassName:@"Recipe"];
[retrieveRecipes  whereKeyExists:@"name"];

[retrieveRecipes findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        NSLog(@"%@", objects);
        totalStrings = [[NSMutableArray alloc] initWithArray:objects];

    }
    [self.myTableView reloadData];
}];
}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *) searchText{
if (searchText.length ==0){
    isFiltered =NO;}
else{
    isFiltered =YES;

    filteredStrings=[[NSMutableArray alloc]init];
    for(PFObject *element in totalStrings) {
        NSString * str = [element objectForKey:@"name"];
        NSLog(@"%@", NSStringFromClass([element class])); // you thought that totalStrings
        // contained NSString objects,
        // but it contains PFObjects.
        NSRange stringRange =[str rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (stringRange.location !=NSNotFound) {
            // you need to add the PFObject back to make your cellForRowAtIndexPath: method
            // work.
            [filteredStrings addObject:element]; // used to be :str
        }
    }
}

[self.myTableView reloadData];
}

//table view datasource and delegate method.....

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section
{
if (isFiltered){
    return [filteredStrings count];
}return [totalStrings count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = @"RecipeCell";

UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (!cell){
    cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if(!isFiltered){

    PFObject *tempObject =[totalStrings objectAtIndex: indexPath.row];
    cell.textLabel.text = [tempObject objectForKey:@"name"];
}
else
{
    PFObject *tempObject2 =[filteredStrings objectAtIndex: indexPath.row];
    cell.textLabel.text =[tempObject2  objectForKey:@"name"];
}
return cell;
}

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end


text:
Q: How can one change colour of the PDF while using corner.py module? I am plotting MCMC corner plots using corner.py module in Python. I managed to change the colour of the contours, using color='red' flag but it changes the colours of the Probability Distribution Function (PDF), too. Is there any way to have a separate colour for the PDF?
Corner.py module webpage link: https://corner.readthedocs.io/en/latest/pages/custom/


text:
Q: Classes of inserted DOM node not being passed I have the following code that listens for an inserted DOM node
$('#box').on('DOMNodeInserted', function(e) {
    var news = e.target.className.split(" ");
    if (news[news.length-1].indexOf("today")){
        //do something
    }
});

When a node is inserted, the code above is supposed to check the class to see if it has the string "today". The structure of the inserted html is like this...

If it has "today", it's supposed to "do something"
The issue is that for some reason, the function above is showing that inserted nodes have a class of
""

Even though the element that was inserted is

However, elements that already exist show the correct class of
posts news today

The issue lies in this code somewhere, but I'm not sure why inserted nodes would be interpreted to not have a class while existing nodes do.
For clarification, this code
$('#box').on('DOMNodeInserted', function(e) {
    var news = e.target.className;
    console.log(news);
});

outputs the correct class name for elements that already exist on page load, but shows "" for inserted elements. As stated above, the inserted elements contain the correct class information, it just isn't being interpreted by the code above.

A: You're using jQuery anyway -- why not use it everywhere?
if ($(e.target).hasClass('today')) {
   // ...
}

http://api.jquery.com/hasClass


text:
Q: TypeError: 'str' object is not callable when making a peewee model I am currently working on my own little project which is about clicking a pointless button. I am making it in python using tkinter and peewee to be able to store saves so that the user/player can continue from where they left.
when I was making a 'save' function, but when I was creating a model in peewee it gave me an error:
TypeError: 'str' object is not callable
My Model class looks like this:
db = SqliteDatabase("scores.db")

class Score(Model):
    save = CharField()
    score = IntegerField()

    class Meta:
        database = db

and the function that saves the progress looks like this:
def save_progress():
    global score_number
    # score_number signifies the score of the game(how many times the button has been clicked)
    saves_length = int(Score.select().count())
    save = "save{}".format(saves_length+1)
    Score.create(save=save, score=score_number)

The error comes on the line:
Score.create(save=save, score=score_number)

I don't understand why it says that i'm calling a string object because I don't think I am.
Can someone please explain to me what I did wrong in my code?
Thanks!
Andrei

A: The Score class has a function called save and you changed that to a str.  Later it gets called to store the row into the DB.
class Score(Model):
    save = CharField()

See the docs.
http://docs.peewee-orm.com/en/latest/peewee/models.html

Field-naming conflicts
Model classes implement a number of class- and instance-methods, for example Model.save() or Model.create(). If you declare a field whose name coincides with a model method, it could cause problems. Consider:


text:
Q: Import Pcaml grammar to extend OCaml's printer using camlp5 I want to create a printer extension for OCaml using camlp5. My code would look like the example of this tutorial but instead of creating my own extension of the grammar, I would like to use OCaml's grammar to parse a program.
For that, I would like to use the Pcaml module to parse the given string with OCaml's grammar. Unfortunately, each time I try to use it, I get the:
Required module 'Pcaml' is unavailable
This is the part of my code where I load and open modules, as well as part of the code that uses Pcaml:
#load "pa_extprint.cmo";;
#load "q_MLast.cmo";;
#load "pa_o.cmo";;

open Pcaml;;
open Pprintf;;

let pa_ocaml = Grammar.Entry.create Pcaml.gram "pcaml_gram";;

I tried multiple command to run the program, like for example:
ocamlc -pp camlp5o -I +camlp5 gramlib.cma <my_file>.ml
What do I need to be able to use Pcaml and Pcaml.gram?

A: I recommend to use ocamlfind to build and link your programs. The only reason for newcomer against it, is that thing could become buggy when you use Windows without WSL. The compilation command without error is below
ocamlfind c -syntax camlp5o -package camlp5 -linkpkg a.ml

#load "pa_extprint.cmo";;
#load "q_MLast.cmo";;
#load "pa_o.cmo";;

open Pcaml;;
open Pprintf;;

let pa_ocaml : int Grammar.Entry.e = Grammar.Entry.create Pcaml.gram "pcaml_gram";;

FYI, your #load commands can and should be replaced by specifying right ocamlfind's packages.


text:
Q: C++ Object creation difference Sorry I know this is a really basic question but it's something that keeps tripping me up in my code. Can someone please (as simple as possible) explain to me the difference in writing:
a* objName;

versus
a* objName = new a();

I keep thinking that it's functionally the same, other than dynamic/automatic memory allocation, but it seems the way I use objName is different based on which of the above I write.
Thank you

A: You shouldn't be using either one of those constructs!  Both are much better handled by writing C++ code, not C-style code in C++.
Instead of
a* objName;

you should write
std::unique_ptr<a> objName;

Although perhaps a* objName is a typo and you actually meant to write
a objName;

If so, this creates an instance of a on the stack as opposed to allocating dynamic memory.
And instead of
a* objName = new a();

You should use std::make_unique.
auto objName = std::make_unique<a>();

Adopting such habits now will make your C++ development life much easier.

A: Consider the difference between
int x;

and
int x = 42;

They both declare a local variable, but the first leaves the value uninitialized while the latter sets it to 42.
Same thing for the code in your question: the first declares a pointer but does not assign it a value (ie a memory location of an a value), while the latter initializes it with the expression new a() which constructs an a value on the heap and returns the address.

A: Both versions declare a pointer. In the first the pointer is uninitialised so using it is likely to crash your program. In the second the pointer is made to point to a dynamically allocated object.
If at a later stage you initialise the pointer declared the first version then you would use it in exactly the same way as the second version.

A:
a* objName;

This creates an automatic - or static depending on context - object of type a*. The object is default initialised, which in case of a pointer type means that there is no initialisation. In the case the variable has static storage, it will be zero initialised, which for pointer means it will point to null. In case it is automatic, the value will be indeterminate.
If you attempt to indirect through this pointer to access the non-existing object, the behaviour of the program will be undefined.

a* objName = new a();

This also creates an automatic or static, depending on context, object of type a*. The difference is that in this case it is initialised.
Besides that, this also creates a dynamic object of type a. The pointer is initialised to point to the dynamic object. The dynamic object is value initialised.
Accessing the object through the pointer has well defined behaviour. Losing the pointer value without using delete on it will cause a memory leak.
P.S. Don't use owning bare pointers. Instead, use RAII containers such as smart pointers for dynamic allocation. Also, avoid dynamic allocation when you don't need it.


text:
Q: Why is my MacBook falling asleep with "Clamshell Sleep" but lid is not closed I have a MacBook Pro (Retina, 15", Mid 2015) running El Capitan (10.11.6).
It will often run for days with no issue. I will be using the Mac at the time, then suddenly the screen shuts down black as if its gone to sleep (nothing that I've done knowingly has triggered this). There is nothing that I can do to then turn on the Mac - Power button does nothing and pressing the touchpad also does nothing. I have to close the lid and then open it again to wake it up.
When I then open up the Mac, it will stay awake and then repeat the above over and over, only staying awake for 5 - 15 seconds at a time before sleeping again.
I have run:
    pmset -g log

.. and i get (amongst all other lines)
    Entering DarkWake state due to 'Clamshell Sleep': Using AC (Charge:100%)

From all my Googling, this seems to indicate that the lid has been shut, but the lid is still open.
Any hints on how I can stop this from happening?
ALSO: This is the 2nd MacBook Pro this has happened to, so seems to be a user profile or software thing over a hardware thing. This issue has followed me moving from one machine to another with a Time Machine backup...

A: I don't know if this might be pertinent to your situation, but I once had a very similar problem with a 2009 MBP. The weird thing was when I picked it up and moved it, it would wake up. This went on for weeks until I finally figured it out; it would sometimes fall asleep when I put it on top of a (closed) white MacBook. It turns out both the MB and MBP sense the lid is closed via a magnet in the lid and a magnetic sensor near the front of the machine. When I laid it on top of the MB the MB's magnet triggered the sensor in the MBP making it think the lid was closed. So, it might be worth noticing if you've got any strongish magnets in the area around the front of the machine when it spontaneously takes a nap.

A: My first instinct would be to reset both the NVRAM and SMC. Try the following and let us know how you go.
Reset the SMC
For your particular MacBook Pro, here's what you do:

*

*Shut down your computer

*Keep the power cable plugged in.

*Press at the same time shiftoptioncontrol (on the left side of the keyboard) and the power button

*Let go

*Turn your computer back on with the power button.

Reset your NVRAM
Older Macs had what's called Parameter RAM (PRAM), newer Macs use Non-Volatile Random-Access Memory (NVRAM). Either way, here's how to reset this:

*

*Shut down your machine. Yes, a full shut down, not just logging out.

*Press the power button and then press the commandoptionpr keys. You have to make sure you press these keys before the gray screen appears or it won't work.

*Hold those keys down until your Mac reboots again and you here the startup chime.

*Let go of the keys and let your Mac reboot normally.
Note: When you log back in you may need to readjust some of your system preferences (e.g. mouse speed, time and date/timezone, etc).

A: I had another problem that was strangely solved by @Felix answer
My MBP 13" 2019 wouldn't wake after opening lid on Catalina / Big Sur with
Sleep wake failure in EFI 0xFFFFFFFF0000001F

I tried all suggested workarounds, e.g.
sudo pmset -a standby 0
I found that the magnet from my new laptop case caused this issue as I always placed MPB on top of the case or carried MBP in it
I found it after checking pmset -g log. After failing to wake and stating that the display is off, MBP suspiciously entered sleep state again
Entering Sleep state due to 'Clamshell Sleep':TCPKeepAlive=active Using Batt (Charge:82%)

Google landed me on @Felix answer, and in the comments @Allan stated that even the smallest magnet could cause this:
https://osxdaily.com/2012/05/26/stupid-but-useful-mac-trick-turn-off-internal-macbook-pro-screen-with-a-magnet/
Thanks @Felix & @Allan, you saved me from 1000$ logic board replacement :)


text:
Q: Как вставить большую JSON строку в БД? Помогите вставить большую JSON строку в mariadb10.4. И какой лучше использовать тип данных в таблице?
{
    "content": "You can~~not~~ do `this`.```py\nAnd this.\nprint('Hi')```\n*italics* or _italics_     __*underline italics*__\n**bold**     __**underline bold**__\n***bold italics***  __***underline bold italics***__\n__underline__     ~~Strikethrough~~",
    "embed": {
        "title": "Hello ~~people~~ world :wave:",
        "description": "You can use [links](https://discord.com) or emojis :smile: \n```\nAnd also code blocks\n```",
        "color": 4321431,
        "timestamp": "2022-01-28T20:30:15.484Z",
        "url": "https://discord.com",
        "author": {
            "name": "Author name",
            "url": "https://discord.com",
            "icon_url": "https://unsplash.it/100"
        },
        "thumbnail": {
            "url": "https://unsplash.it/200"
        },
        "image": {
            "url": "https://unsplash.it/380/200"
        },
        "footer": {
            "text": "Footer text",
            "icon_url": "https://unsplash.it/100"
        },
        "fields": [
            {
                "name": "Field 1, *lorem* **ipsum**, ~~dolor~~",
                "value": "Field value"
            },
            {
                "name": "Field 2",
                "value": "You can use custom emojis <:Kekwlaugh:722088222766923847>. <:GangstaBlob:742256196295065661>",
                "inline": false
            },
            {
                "name": "Inline field",
                "value": "Fields can be inline",
                "inline": true
            },
            {
                "name": "Inline field",
                "value": "*Lorem ipsum*",
                "inline": true
            },
            {
                "name": "Inline field",
                "value": "value",
                "inline": true
            },
            {
                "name": "Another field",
                "value": "> Nope, didn't forget about this",
                "inline": false
            }
        ]
    }
}

A: Если правильно использовать параметризированные запросы - все должно отработать без проблем:
qry = """
create table test(
   id int not null auto_increment
  ,json varchar(65000) collate 'utf8mb4_unicode_ci'
  ,primary key(id)
)
"""
cursor.execute(qry)

json_str = """<your_JSON_string>"""
qry = """insert into test(json) values(%s)"""
cursor.execute(qry, [json_str])


text:
Q: mocking @value annotation of int data type @Component
public class MyHelper {
    @Value("${max.retry.count:3}")
    private int maxRetryCount;

    @Value("${max.query.count:1000}")
    private int maxQueryCount;
}

I am reading the value of a variable from a properties file using @value annotation.
When writing a junit using EasyMock, I'm getting an exception as
"nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type [java.lang.String] to required type [int];
 nested exception is java.lang.NumberFormatException: For input string: "${max.retry.count:3}".

If the data type is changed to String, then it's working fine.
Someone help me on how to mock this.

A: There are actually multiple ways to achieve that.
MyHelper managed by a Spring IoC container
In this case, you would need to add additional annotation above your test spec which create an ApplicationContext in order to inject MyHelper bean.
@RunWith(SpringJUnit4ClassRunner.class)
public class MyHelperTest { ... }

You will also need a properties file for test. If you're using Spring Boot, you can simply create an application.properties file in the scope of your test/resources folder and put the values for those properties right there and they will be picked up.
MyHelper instantiated manually
This is the easy one. You simply create a constructor or setters for maxRetryCount and maxQueryCount and set the values in that manner.
public class MyHelperTest {
    private MyHelper myHelper = new MyHelper(5, 6);
}

In this case, annotations will be simply ignored since MyHelper is not managed by a Spring IoC container.

A: Try changing the following line
@Value("${max.query.count:1000}")

to
@Value("#{new int('${max.query.count:1000}')}")


text:
Q: pull request conflict when making a change by code instead of manually
*

*OS X workstation

*Linux build machine

*GitHub Enterprise

In a Jenkins pipeline, the following works:

*

*Manually change the version number in package.json

*Commit and push

*Create a pull request from feature branch to develop branch

*Jenkins checkouts, run tests, npm publishes to a dev scope, and merges

*Create a pull request from develop branch to master branch

*Jenkins checkouts, run tests, and npm publishes to a prod scope

If I replace the manual version manipulation to be part of the pipeline by using npm version patch, and commit this version change back to the develop branch...
... then once creating the pull request from the develop branch to the master branch, the pull request cannot be created due to a conflict. The conflict appears in the version line in package.json that was changed via the npm version patch command.
I am pretty sure it is related to line endings. I do not know how to approach this problem.
Should we change a package's version number manually before deciding to publish, or increment it automatically? Obviously right now the latter will fail due to the above...

A solution would be to somehow preserve the line ending of "version": "0.0.8", exactly as it were before changing it from .7 to .8...

A: Adding a .gitattributes file with the following has seemingly solved it.
*.json text eol=lf


text:
Q: Lower bound of number of independent sets Let $G$ be a connected regular graph with even number of vertices $v$. Also let $i_{v/2}(G)$ be the number of independent sets of $G$ of size $\frac{v}{2}$. Is it possible that $i_{v/2}(G)> 2^{v/2}$?
My hunch is that the answer is no but I cannot prove it.

A: No, it's not possible. Let's show that $i_{v/2}(G)\le 2$ for all such $G$.
Let $V$ be the set of vertices of the graph $G$, $U$ be an independent subset of vertices of $G$ of size $v/2$, $W=V\setminus U$, and $d$ be a common degree of a vertex of $G$. Each vertex $u\in U$  is adjacent to $d$ vertices of $V$ and since $U$ is an independent set, all these vertices belong to $W$.  Thus there are $d|U|=dn/2$ edges between $U$ and $W$. Since $|W|=n/2$ and each vertex $w\in W$ is adjacent to $d$ vertices, the number of edges incident to vertices of $W$ is at most $dn/2$ and the equality holds iff each vertex of $W$ is adjacent only to vertices in $U$. Thus the set $W$ is independent too.
So the graph $G$ is bipartite with the partition constituted by $U$ and $W$. We claim that this is a unique partition of vertices of $G$ in two independent subsets $U'$ and $W'$.
Indeed, without loss of generality we can assume that there exists a vertex $u\in U\cap U'$. Let $v$ be any vertex of $G$. Since the graph $G$ is connected, there exists a path $P$ from $u$ to $v$. Since both $U\cup W$  and $U'\cup W'$ are partitions of $V$ into two independent sets, when we are going along $P$ from $u$ to $v$ at each step we simultaneously switch from $U$ to $W$ and from $U'$ to $W'$ and vice versa. Then we see that $v\in U$ iff $v\in U'$ and $v\in W$ iff $v\in W'$, so $U=U'$ and $W=W'$.


text:
Q: How to simulate an unhandled exception in Java I am creating some multi-threaded code, and I have created a JobDispatcher class that creates threads. I want this object to handle any unhandled exceptions in the worker threads, and so I am using
Thread.setUncaughtExceptionHandler(this);

Now, I would like to test this functionality - how can I generate an unhandled exception in the run() method of my worker object?

A: What's the problem with just throwing an exception:
throw new Exception("This should be unhandled");

Inside your run method. And of course, not catching it. It should trigger your handler.

A: You should throw some unchecked exception. An unchecked exception does not require your code to handle it, and is therefore a good candidate to make all the way down the call stack.
You can choose RuntimeException for example, or even something like AssertionError, if you want to minimize the chances that some part of the code catches the exception and handles it before it reaches your handler.

A: Just throw any exception.
E.g.:
throw new RuntimeException("Testing unhandled exception processing.");

Complete:
public class RuntimeTest
{
  public static void main(String[] a)
  {
    Thread t = new Thread()
    {
      public void run()
      {
        throw new RuntimeException("Testing unhandled exception processing.");
      }
    };
    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
    {
      public void uncaughtException(Thread t, Throwable e)
      {
        System.err.println(t + "; " + e);
      }
    });
    t.start();
  }
}

A: just add this code and you'll get unhandled exception without lint error:
int i = 1/0;


text:
Q: $k$-point after base change If $X$ is a variety over $k$, is it true that there exists a finite separable extension $k'$ of $k$ such that $X$ has a $k'$-point? What if we can assume $X$ is a smooth projective curve?
This seems silly, but I didn't know why couldn't all the residue fields at the closed points be inseparable over $k$.

A: This is true if you assume that $X/k$ is smooth. For convenience (since it's irrelevant), I'll assume that $X$ is equidimensional.
Let $x\in X$ be any point. By assumption that $X$ is smooth, there exists some neighborhood $U\subseteq X$ such that $X\to \text{Spec}(k)$ factors as
$$\begin{matrix}U & \xrightarrow{\text{etale}} & \mathbb{A}^n_k\\ & \searrow & \downarrow\\ & & \text{Spec}(k)\end{matrix}$$
where $n=\dim X$. Now, since $U\to X$ is etale, we know that its image $V$ is open. But, the $k$-points of $\mathbb{A}^n_k$ are dense. So, there exists $v\in V$ which is a $k$-point--let $u\in U$ be a point which maps to $v$. Then, by definition of etaleness, $\ell:=k(u)$ is a finite separable extension of $k(v)$. So, $u$ is an $\ell$-point with $\ell/k$ finite separable. Since $U(\text{Spec}(\ell))=U_\ell(\text{Spec}(\ell))$ we see that $U_\ell$ has an $
\ell$-point as desired.
As an exercise, try and extend the above to a much stronger statement about the separable points of $X$ (something to the tune of density).
If you don't assume that $X/k$ is smooth, then I believe the answer is no. Let $k=\overline{\mathbb{F}_p}(T)$, and let $X=\text{Spec}(k(T^{\frac{1}{p}})$. Suppose that $\ell/k$ is separable, and $X_\ell$ had an $\ell$-point. Well, $X_\ell=\text{Spec}(\ell[x]/(x^p-T)$. Then, $X_\ell$ having an $\ell$-point means that $x^p-T$ has a root in $\ell$. But, $x^p-T$ has a unique root in $\overline{k}$, and so clearly $\ell\supseteq k(T^{\frac{1}{p}})$, which implies that $\ell/k$ is not separable--contradiction.


text:
Q: Converting US date to EU date in java Without using a "dateformat" or something along those lines, I am trying to change a string of US date "mm/dd/yyyy" to an EU format "dd/mm/yyyy". I am to do this using strings and string methods. I feel like I am very close to this but cannot quite figure it out.
This is my code:
import java.util.Scanner;

public class DateChange {

    public static void main(String[] args) {
        Scanner kbd = new Scanner(System.in);
        String usDate, euDate, day, month;
        int year;
        System.out.println("Enter a date in the form month/day/year:");
        usDate = kbd.nextLine();
        month = usDate.substring(0, '/');
        day = usDate.substring('/', '/');
        year = usDate.lastIndexOf('/');
        euDate = day + "." + month + "." + year;
        System.out.println("Your date in European form is:");
        System.out.println(euDate);
    }

}

This is the error I am getting:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 47
    at java.lang.String.substring(String.java:1963)
    at DateChange.main(DateChange.java:12)

A: Why not split the input string using '/' as separator using the method String.split. It returns an array of strings. Just swap the first two elements of the array.
String usdate = "12/27/2015";
String[] arr = usdate.split("/");
String eudate = arr[1] + "/" + arr[0] + "/" + arr[2];

A: The problem is that java.String.substring takes two int values, not char values. The int value of ' / ' is 47, so substring is taking 47 as an input, not the indexOf   ' / '.
If you want to solve this without using the java library, use the following code:
import java.util.*;

public class DateChange {
    public static void main(String[] args) {
        Scanner kbd = new Scanner(System.in);
        String usDate, euDate, day = "", month = "", year = "";
        System.out.println("Enter a date in the form month/day/year:");
        usDate = kbd.nextLine();
        kbd.close();
        month = usDate.substring(0, usDate.indexOf("/"));
        day = usDate.substring(usDate.indexOf("/")+1, usDate.lastIndexOf("/"));
        year = usDate.substring(usDate.lastIndexOf("/")+1, usDate.length());
        euDate = day + "." + month + "." + year;
        System.out.println("Your date in European form is:");
        System.out.println(euDate);
    }
}

A: Scanner kbd = new Scanner(System.in);
        String usString = kbd.nextLine();
        String[] stringArray = usString.split("(\\/|\\.)");
        String month = stringArray[0];
        String day = stringArray[1];
        String year = stringArray[2];
        System.out.println("m"+month+"d"+day+"y"+year);

This code shows how to use RegEx to split the sting into a string array which can then be re assembled into EU format without the DateFormat class.