text:
Q: queria saber como faço para que o stream continue executando Olá, queria saber como faço para que o stream continue executando, mesmo se eu for pra outra tela, ou sair do aplicativo. Mais não sei como faço. Alguém me dê uma dica e exemplo. Obrigado
Estou usando classe do tipo Fragmen
Quando saiu pra outra activity já vi no log isso: W/MediaPlayer-JNI: MediaPlayer finalized without being released
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab1aovivo, container, false);

    imgStream = (ImageView) view.findViewById(R.id.imgStreamId);
    btnTocar = (ImageView)  view.findViewById(R.id.btnExecutarId);
    btnTocar.setImageResource(R.drawable.play);
    imgStream.setVisibility(imgStream.INVISIBLE);

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    progressDialog = new ProgressDialog(getActivity());

    btnTocar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(estadoInicial) {
                if(mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                }
                estadoInicial = false;
            } else {
                if(playPause) {
                    new Player().execute(stream);
                } else {
                    if(!mediaPlayer.isPlaying()) {
                        mediaPlayer.start();
                    }
                }
                estadoInicial = true;
                playPause = false;
            }
            checkIsPlaying();
        }
    });
    checkIsPlaying();
    return view;
}

private void checkIsPlaying(){
    if(!estadoInicial) {
        btnTocar.setImageResource(R.drawable.play);
        imgStream.setImageResource(R.drawable.streaming_parado);
    } else {
        btnTocar.setImageResource(R.drawable.stop);
        Glide.with(getActivity()).load(R.drawable.streaming).asGif().into(imgStream);
    }
}

class Player extends AsyncTask<String, Void, Boolean> {
    @Override
    protected Boolean doInBackground(String... strings) {
        try {
            mediaPlayer.setDataSource(strings[0]);
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    estadoInicial = false;
                    playPause = true;
                    btnTocar.setImageResource(R.drawable.play);
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                }
            });
            mediaPlayer.prepare();
            prepared = true;

        } catch (IOException e) {
            e.printStackTrace();
            prepared = false;
        }
        return prepared;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if(progressDialog.isShowing()) {
            progressDialog.cancel();
        }
        btnTocar.setImageResource(R.drawable.stop);
        mediaPlayer.start();
        imgStream.setVisibility(imgStream.VISIBLE);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Glide.with(getActivity()).load(R.drawable.carregando).asGif().into(btnTocar);
        progressDialog.setMessage("Carregando Streaming...");
        progressDialog.show();
    }
}

@Override
public void onPause() {
    super.onPause();
    Toast.makeText(getActivity(), "atc pause", Toast.LENGTH_SHORT).show();
    if(estadoInicial) {
        mediaPlayer.start();
        Toast.makeText(getActivity(), "play-pause", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onResume() {
    super.onResume();
    if(estadoInicial) {
        mediaPlayer.start();
    }
}

@Override
public void onDestroy() {
    if(prepared) {
        mediaPlayer.release();
        mediaPlayer = null;
    }
    super.onDestroy();
}


text:
Q: ModuleNotFoundError: No module named 'cassandra.cluster'; 'cassandra' is not a package I tried pip install cassandra-driver
inside pycharm terminal, conda command prompt in admin mode, I upgraded/degraded versions of cassandra-driver, restarted pycharm , created new env ,still showing error.
Here is my code .
import cassandra
from cassandra.cluster import Cluster

my error massage:
C:\Anaco3.8\envs\FlipScap\python.exe
C:/Users/Rushikesh/Downloads/FlipkratScrappingProject/cassan2.py
Traceback (most recent call last):
File "C:/Users/Rushikesh/Downloads/FlipkratScrappingProject/cassan2.py", line 1, in <module>
import cassandra
File "C:\Users\Rushikesh\Downloads\FlipkratScrappingProject\cassandra.py", line 3, in <module>
from cassandra.cluster import Cluster
ModuleNotFoundError: No module named 'cassandra.cluster'; 'cassandra' is not a package

A: The error indicatest that the Cassandra Python driver is not installed.
If you haven't already, try installing it with:
$ pip3 install cassandra-driver

Check that the installation was successful by running:
$ python -c 'import cassandra; print cassandra.__version__'

If it is installed correctly, you should get something like "3.25.0".

A: I think we can blame our dear DataStax for this, they mentioned Cluster with no camel-case and it cause this issue.
first make sure you have the package installed(pip3 install cassandra-driver), then use bellow code.
Just use it this way:
from cassandra.cluster import Cluster
cluster = Cluster(['172...', '172...','172...'])

Replace all the '172...' with your cluster IP set.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a Virtual Many-To-Many Relationship with NHibernate Let's say you have three entities - Categories, Sites and Items. The Items table has a CategoryID and a SiteID. If I want to find the sites for a given category, I can get that with a mapping in NHibernate that looks something like:
public CategoryMap()
{
  //..
  ManyToMany(x => x.Site)
    .Table("Items")
    .ParentKey("CategoryID")
    .ChildKey("SiteID");
}
This works great if I want a list of all of the categories, and the sites the category belongs to. But I also want to create a category called "Uncategorized" and list the Sites which don't belong to a Category in there. I could do it with a second query, but I was wondering if there was a way to create a "virtual" Category that would be part of the Category collection, or some other trick to this I'm missing. I'm also open to being told that this is highly wrong.

A: That would be part of your Model / Service; NHibernate can't provide it.


text:
Q: Is there a way to silently extract a self extracting multipart rar files via commandline? I have a multipart self extracting rar file;
setup.sfx.part1.exe
setup.sfx.part2.rar
setup.sfx.part3.rar

Now when I try to extract it by starting the exe via commandline I get a nice screen where to extract things to:

Now my question is here: Is there any way via commandline (as I'm trying to run things automatically via batch job) to extract that file "silently", thus without this menu popping up?

A: You could use a tool like unrar. (There's a regular RAR archive inside the self-extracting stub.)
Some versions also support the /s option for silent mode.


text:
Q: Mongoid paper clip photo is removed when parent.update_attributes!(attr) called I have 2 models
The User model embeds many pictures as follows
class User
  include Mongoid::Document

  field :user_name, type: String
  embeds_many :pictures, cascade_callbacks: true
  ...
end

The Picture model is implemented as follows
class Picture
  include Mongoid::Document
  include Mongoid::Paperclip

  field :description,   type: String

  has_mongoid_attached_file :photo,
  default_url: '',
  default_style: :thumb,
  url: "/:attachment/:id/:style.:extension",
  styles: {
    original: ['2000x1200>',  :jpg],
    thumb:    ['600x400#',    :jpg]
  },
  convert_options: {
    all: '-quality 90 -strip -background black -flatten +matte'
  }
  ...
end

The problem is in the user_controller#update
def update
   ...
   @user.update_attributes!(user_params)
   ...
end

def user_params
  params.require(:user).permit(:user_name, pictures:[:id, :description])
end

I expected this #update to update the description of the picture with the id passed... and it does.
but the uploaded picture is removed after this update ?
how do i update the description of the uploaded photo without it getting removed after using @user.update_attributes!(user_params) ?

A: Not tested!
pictures_params = params[:user].delete(:pictures)
@user.pictures.where(:id.in => pictures_params.map(&:id)).each do |pic|
  pic.set(:description, pictures_params.find{|p| p[:id] == pic.id}[:description])
end

A: I used the following code to solve the problem but i think there is a better approach for solving this issue
  # get the user hash to update both pictures and user
  user_params_hash = user_params

  # remove the picture from the hash to separate the updating of pictures from users
  picture_params_hash = user_params_hash.delete 'pictures'

  # update each picture description to avoid removing the photo
  unless picture_params_hash.nil?
    picture_params_hash.each do |picture_hash|

      picture = @user.pictures.find_or_create_by(id: picture_hash[:id])
      picture.description = picture_hash[:description]
      picture.save!
    end
  end

  # update the user attributes only without touching the embedded pictures
  @user.update_attributes!(user_params_hash)
end


text:
Q: C++ stl :: sort() через компаратор Почему не получается передавать в компаратор параметры по ссылке? Что туда вообще нужно передавать, а что не нужно? Как отсортировать двумерный массив при помощи такой функции и почему не рабоает этот код?
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxN = 100, maxM = 150;
int n, m;

bool cmp ( int* A1, int* A2 ){
    int i = 0;
    while ( ( i < m ) && ( A1[i] == A2[i] ) )
        i++;
    if ( ( i == m ) || ( A1[i] > A2[i] ) )
        return true;
    return false;
}

int main(){
    int i, j, M[maxN][maxM];
    scanf(" %d %d ", &n, &m );
    for ( i = 0; i < n; i++ )
        for ( j = 0; j < m; j++ )
            scanf( "%d", &M[i][j] );
    sort ( M, M + n, cmp );
    return 0;
}

A: Вы могли бы написать следующим образом, как, например,
#include <iostream>
#include <iterator>
#include <algorithm>
#include <array>
#include <functional>

int main()
{
    int a[][3] = { { 1, 2, 3 }, { 1, 1, 3 } };

    for ( const auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }
    std::cout << std::endl;

    std::sort( reinterpret_cast<std::array<int, 3> *>( std::begin( a ) ),
               reinterpret_cast<std::array<int, 3> *>( std::end( a ) ),
               std::less<>() );

    for ( const auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }
    std::cout << std::endl;

    std::sort( reinterpret_cast<std::array<int, 3> *>( std::begin( a ) ),
               reinterpret_cast<std::array<int, 3> *>( std::end( a ) ),
               std::greater<>() );

    for ( const auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

Вывод программы на консоль:
1 2 3
1 1 3

1 1 3
1 2 3

1 2 3
1 1 3

Как видите, сначала массив сортируется в порядке возрастания, а затем в порядке убывания, используя стандартные функциональные объекты std::less (его можно было бы вообще не использовать, так как вместо него применялся бы оператор operator <, объявленный для класса std::array) и std::greater.
Проблема в том, что интерпретация указателя на одномерный массив как указателя на объект std::array а затем обращение к элементам объекта через этот указатель, является не совсем корректной в C++, хотя программа успешно отработала.
Что касается массивов, то проблема заключается не в том, что к ним нельзя применить функцию std::swap, ее как раз можно успешно применять к массивам, а в том, что сортируемые элементы должны быть MoveConstructible и  MoveAssignable, то есть в приложении к массивам это означает, что массивы должны быть присваиваемыми или инициализируемыми с помощью других массивов. Однако для массивов отсутствует оператор перемещающего присваивания и конструктор перемещения.
В показанном мной примере с std::array этой проблемы не существует, так как этот класс имеет неявно определенные компилятором оператор перемещающего присваивания и конструктор перемещения.
Я привел этот пример для того, что вы могли бы объявить массив объектов std::array<int, maxM>. Например
#include <array>

//...

std::array<int, maxM> M[maxN];

и тогда без проблем могли бы вызывать функцию std::sort.
Поэтому если вы хотите отсортировать именно двумерный массив, то либо функцию сортировки вам придется писать самому, либо использовать стандартную C функцию qsort, объявленную в заголовочном файле <cstdlib>.
Я покажу упрощенный вариант, когда количество сравниваемых элементов в строке массива совпадает с размерностью строки массива. В вашем случае это не так, поэтому в функциях-корпоратарах вы должны учитывать число реально сравниваемых элементов. Эти числа можно включить в эти функции с помощью вызова внутри других функций, которые возвращают заданное значение числа реально сравниваемых элементов в строке массива.
#include <iostream>
#include <cstdlib>

const int maxN = 2, maxM = 3;

int cmp_ascending( const void *lhs, const void *rhs )
{
    const int ( *a )[maxM]  = reinterpret_cast<const int ( * )[maxM]>( lhs );
    const int ( *b )[maxM]  = reinterpret_cast<const int ( * )[maxM]>( rhs );

    const int *first1 = *a, *last1 = *a + maxM;
    const int *first2 = *b;

    while ( first1 != last1 && *first1 == *first2 ) ++first1, ++first2;

    return first1 == last1 ? 0 : ( *first1 > *first2 ) - ( *first1 < *first2 );
}

int cmp_descending( const void *lhs, const void *rhs )
{
    const int ( *a )[maxM]  = reinterpret_cast<const int ( * )[maxM]>( lhs );
    const int ( *b )[maxM]  = reinterpret_cast<const int ( * )[maxM]>( rhs );

    const int *first1 = *a, *last1 = *a + maxM;
    const int *first2 = *b;

    while ( first1 != last1 && *first1 == *first2 ) ++first1, ++first2;

    return first1 == last1 ? 0 : ( *first2 > *first1 ) - ( *first2 < *first1 );
}

int main()
{
    int a[][3] = { { 1, 2, 3 }, { 1, 1, 3 } };

    for ( const auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }
    std::cout << std::endl;

    std::qsort( a, maxN, sizeof( *a ), cmp_ascending );

    for ( const auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }
    std::cout << std::endl;

    std::qsort( a, maxN, sizeof( *a ), cmp_descending );

    for ( const auto &row : a )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

Вывод на консоль будет таким же, как и в предыдущей программе:
1 2 3
1 1 3

1 1 3
1 2 3

1 2 3
1 1 3

Вы могли бы обойти эти трудности, если бы динамически выделили массив указателей на одномерные массивы.
В противном случае, если вы не хотите возиться с массивами, то лучше использовать стандартный класс std::vector<std::vector<int>>
Итак, у вас есть следующие четыре возможности.
Первая - это объявить массив объектов класса std::array
std::array<int, maxM> M[maxN];

В этом случае никаких проблем с сортировкой не будет.
Вторая - это объявить массив указателей, а затем каждый указатель массива инициализировать адресом динамически выделенного одномерного массива. Например
int * M[mxN];

for ( int i = 0; i < maxN; i++ ) M[i] = new int[maxM];

В этом случае также никаких проблем с вызовом std::sort не будет.
Третья - оставить объявление массива таким, какое оно есть в вашей программе, и использовать стандартную C функцию qsort, объявленную в заголовке <cstdlib>
Четвертая - использовать стандартный контейнер std::vector, включив следующее объявление в программу
std::vector<std::vector<int>> M( maxN, std::vector<int>( maxM ) );

A: Дело не в компараторе, а в том, что std::sort не может сортировать массив массивов, т.к. она не может присвоить элементам массива новые значения (нельзя присвоить массив массиву).
Используйте vector<vector<int>>.


text:
Q: Scraping tables from Multiple URLs Hi I've been able to scrape tables and export them from a specific website but would like to add more websites to scrape from. It only returns the second URL I put in. Apologies in advance since I'm very new to Python. Thank you.
import requests
from bs4 import BeautifulSoup
import csv
import pandas as pd

urls = ['http://a810-bisweb.nyc.gov/bisweb/BScanItemsRequiredServlet?requestid=7&defaultdisplay=y&passjobnumber=123821098&passdocnumber=01&allbin=1015650', 'http://a810-bisweb.nyc.gov/bisweb/BScanItemsRequiredServlet?requestid=6&defaultdisplay=y&passjobnumber=121054170&passdocnumber=01&allbin=1015650']

for url in urls:
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36', "Upgrade-Insecure-Requests": "1","DNT": "1","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language": "en-US,en;q=0.5","Accept-Encoding": "gzip, deflate"}
    page = requests.get(url,headers=headers)
    soup = BeautifulSoup(page.content, 'html.parser')
    table = soup.find_all('table')[3]
    df = pd.read_html(str(table))[0]

print(df)

A: Well, The issue here that you are looping over the tables without appending. and then you are printing out.
Example:
for item in range(1, 4):
    pass

print(item)

Now the output is:
3

Because it's the last returned element from the loop.
But, if we append like the following:
result = []
for item in range(1, 4):
    result.append(item)

print(result)

So we will get the following:
[1, 2, 3]

Now, let's move to the next point, you already can read the table directly using pandas.read_html because urllib3 is already within the background of pandas , as the following:
import pandas as pd

df = pd.read_html(
    "http://a810-bisweb.nyc.gov/bisweb/BScanItemsRequiredServlet?requestid=7&defaultdisplay=y&passjobnumber=123821098&passdocnumber=01&allbin=1015650")[3]

print(df)

But since the website TCP layer is configured to Connection: close ref.

HTTP/1.1 defines the "close" connection option for the sender to signal that the connection will be closed after completion of the response. For example,

   Connection: close

So we will run that under requests library with maintaining the Session object to not getting blocked by the server firewall using requests.Session() and appending the table for each url and then concatenated it in one table using pd.concat function and then convert to csv using pd.to_csv():
import pandas as pd
import requests

urls = ['http://a810-bisweb.nyc.gov/bisweb/BScanItemsRequiredServlet?requestid=7&defaultdisplay=y&passjobnumber=123821098&passdocnumber=01&allbin=1015650',
        'http://a810-bisweb.nyc.gov/bisweb/BScanItemsRequiredServlet?requestid=6&defaultdisplay=y&passjobnumber=121054170&passdocnumber=01&allbin=1015650']

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0'
}

def main(urls):
    goal = []
    with requests.Session() as req:
        for url in urls:
            r = req.get(url, headers=headers)
            df = pd.read_html(r.content)[3]
            goal.append(df)
    goal = pd.concat(goal)
    goal.to_csv("data.csv", index=False)

main(urls)

Output: View Online

Code updated as per User Request:
import pandas as pd
import requests

urls = ['http://a810-bisweb.nyc.gov/bisweb/BScanItemsRequiredServlet?requestid=7&defaultdisplay=y&passjobnumber=123821098&passdocnumber=01&allbin=1015650',
        'http://a810-bisweb.nyc.gov/bisweb/BScanItemsRequiredServlet?requestid=6&defaultdisplay=y&passjobnumber=121054170&passdocnumber=01&allbin=1015650']

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0'
}

def main(urls):
    goal = []
    with requests.Session() as req:
        for url in urls:
            r = req.get(url, headers=headers)
            df = pd.read_html(r.content)[2:4]
            for table in df:
                goal.append(table)
    goal = pd.concat(goal)
    goal.to_csv("data.csv", index=False)

main(urls)

Output: view-online


text:
Q: Use data frame that should return both numeric and character columns I have a built in data set in R called "mpg". When I type
df(,c[1,2,"year"])

the result( it should print respective tables) should be
**manufactures**  **model**  **year**
1) audi        a4.    1999
2) audi.       a4.    1999
    .           .      .
    .           .      .
    .           .      .
224)

A: If you want to mix the ways with which you subset the columns of a dataframe, you can use dplyr.
Sample dataset:
mtcars

                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2

Code
library(dplyr)

mtcars %>% select(1, 2, "drat")

Output
                     mpg cyl drat
Mazda RX4           21.0   6 3.90
Mazda RX4 Wag       21.0   6 3.90
Datsun 710          22.8   4 3.85
Hornet 4 Drive      21.4   6 3.08
Hornet Sportabout   18.7   8 3.15

A: mpg[,c(1,2,4)]
Is what you're looking for.
or
mpg[, c("manufacturer", "model", "year")]


text:
Q: Comma delimited numeric value fails validation in asp.net MVC 4 I have this model class:
using System;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication1.Models
{
    public class PropertyModel
    {
        public int Id { get; set; }
        public String BuildingStyle { get; set; }
        public int BuiltYear { get; set; }
        [Range(1, 100000000, ErrorMessage = "Price must be between 1 and 100,000,000.")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0,0}")]
        [Display(Name = "Price")]
        public int Price { get; set; }
        public string AgentName { get; set; }
    }
}

And this controller:
using System.Web.Mvc;
using MvcApplication1.Models;`

namespace MvcApplication1.Controllers
{
    public class PropertyController : Controller
    {
        public ActionResult Edit()
        {
            PropertyModel model = new PropertyModel
            {
                AgentName = "John Doe",
                BuildingStyle = "Colonial",
                BuiltYear = 1978,
                Price = 650000,
                Id = 1
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(PropertyModel model)
        {
            if (ModelState.IsValid)
            {
                //Save property info.
            }

            return View(model);
        }
    }
}

And this view:
@model MvcApplication1.Models.PropertyModel
@{
    ViewBag.Title = "Edit";
}

Edit

@using (@Html.BeginForm())
{
    <text>Built Year: </text>@Html.TextBoxFor(m => m.BuiltYear)

    <text>Building Style: </text>@Html.TextBoxFor(m => m.BuildingStyle)

    <text>Agent Name: </text>@Html.TextBoxFor(m => m.AgentName)

    <text>Price: </text>@Html.TextBoxFor(m => m.Price)

    <input type="submit" value="Save" />
}

If I enter the price without any commas, ModelState.IsValid is true. But if I enter the price as a comma delimited value, ModelState.IsValid is false (see the screenshot). What do I need to do in order to be able to enter numeric values with commas and pass the model validation?  I know implementing my own custom model binder is an option, but I want to make that the last option.  Thank you. Please share your thoughts.

A: This is the problem:
public int Price { get; set; }

The reason is your Price is set into int. It would definetley cause an error if you place a comma. If you want a comma, just change your int into a string then if your going to use it for computations, just use the split[','] to split the comma and convert it to int by using the Convert.ToInt32() method.

A: Which version of MVC you are using ?
As you are displaying comma for price text, I suggest you should use custom ModelBinder to get its values.

A: You would need to change the data type of your Price to a string so that it would pass the validation.  By doing that though, you would have to do some additional checking to see that the string passed in is truly a valid int.  A little extra work, but not too bad.

A: Success Code Here
http://blog.rebuildall.net/2011/03/02/jQuery_validate_and_the_comma_decimal_separator
in Model->  [Range(1, 100000000, ErrorMessage = "Price must be between 1 and 100,000,000.")]
in View (javascript) ->
 $.validator.methods.range = function (value, element, param) {
    var globalizedValue = value.replaceAll(",", "");
    return this.optional(element) || (globalizedValue >= param[0] &&
    globalizedValue <= param[1]);
 }


text:
Q: распараллеливание кода с генерацией перестановок в си, openmp Доброго времени суток. Необходимо ускорить работу программы при больших значениях входных данных. Собственно сама задача: необходимо для каждой сгенерированной перестановки считать определённые значения, которые записываются в массив (обозначим его uniq_arr). Далее проверятся, есть ли в линейном списке (Node_t) узел, содержащий данный массив. Если есть, то игнорируем данный uniq_arr и, следовательно, саму перестановку; иначе создаём новый узел с таким значением и записываем в самое начало списка (FIFO). Собственно, вот основной код.
    #define SIZE_RING 10

    const int ring[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    typedef struct SpectrNode {
        int spectVector[SIZE_RING];
        struct SpectrNode *next;
    }SpectrNode_t;
    void push (SpectrNode_t **head, int spectr[SIZE_RING])
    {
        SpectrNode_t *newNode;
        int i = 0;
        newNode = (SpectrNode_t*)malloc(sizeof(SpectrNode_t));

        memset(newNode->spectVector, 0, SIZE_RING * sizeof(int));
        for(i = 0; i < SIZE_RING; i++)
            (newNode->spectVector)[i] = spectr[i];
        newNode->next = *head;
        *head = newNode;
    }
    void find (SpectrNode_t **head, int newSpectr[SIZE_RING])
    {
        SpectrNode_t *cur = *head;
        int res = 0;
        while (cur != NULL) {
            if (CompareIntArrays(cur->spectVector, newSpectr) == 0)
                res = 1; // такой элемент уже есть в списке
            cur = cur->next;
        }
        cur = *head;
        if (res == 0) {
            // элемент уникален
            push(head, newSpectr);
        }
    }
void countSpectVector(SpectrNode_t **head, int perm[SIZE_RING])
{
    int intSpectr[SIZE_RING];
    int i = 0, k = 0;
    int diffTmp = 0, betta = 0;

    memset(intSpectr, 0, SIZE_RING * sizeof(int));

    for (i = 0; i < SIZE_RING; i++){
        betta = ring[i];
        diffTmp = perm[( 1 + betta ) % SIZE_RING] - perm[betta];
        if (diffTmp < 0)
            diffTmp += SIZE_RING;
        intSpectr[diffTmp]++;
    }
    find(head, intSpectr);
}

    void generatePerms(int arr[SIZE_RING],  SpectrNode_t **head)
     {
        int c[SIZE_RING];
        int i;

        i = 0;
        memset(c, 0, SIZE_RING * sizeof(int));

        while (i < SIZE_RING) {
            if (c[i] < i) {
                if (i % 2 == 0)
                    swap(&arr[0], &arr[i]);
                else{
                    swap(&arr[c[i]], &arr[i]);

                }
                countSpectVector(head, arr);
                c[i] += 1;
                i = 0;
            }
            else {
                c[i] = 0;
                i += 1;
            }
        }
    }
    int main()
    {
        int *perm;
        int i = 0;
        SpectrNode_t *head;

        perm = (int*)malloc(SIZE_RING * sizeof(int));
        for (i = 0; i < SIZE_RING; i++)
            perm[i] = i;
        head = (SpectrNode_t*)malloc(sizeof(SpectrNode_t));

        if (head == NULL)
            return 1;
        memset(head->spectVector, 0, SIZE_RING * sizeof(int));
        head->next = NULL;

        generatePerms(perm, &head);

        return 0;
    }

Собственно, теперь мои соображения. Я не случайно установил в define значение 10, потому что уже на этом значении программа вычисляется довольно долго (генерируется 10! перестановок, и для каждой проводится порядка 10 итераций + проход по списку). Нужно распараллелить генерацию перестановок. Но они генерируются в цикле while, поэтому простыми средствами OpenMP, к примеру, этого не сделать. Также необходимо сделать место добавление узла в список и вообще работы со списком - критической секцией (скорее всего, просто добавление, но я не уверен). Так же в уме пока что использование CUDA, но пока не уверен, как её сюда припаять.
В общем, подскажите, пожалуйста, советом. Может, где код исправить, чтобы быстрее работало или поменять где-то саму концепцию.
p.s. для генерации перестановок использовался алгоритм Хипа.

A: Тормозит не генерация перестановок, а поиск по списку.
Для начала стоит заменить список на хеш или дерево. Сложность сразу упадёт с O(N!log(N!)) до ~O(N!)(в случае удачного хеша) или ~O(N!loglog(N)) в случае дерева. На практике время  должно сократиться по меньшей мере в 10-20 раз уже для N=8.

Пример реализации хеша.
Пара Замечаний:

*

*Код As-is. Претензий на оптимальность нет.

*Хеш функции честно одолжены, разница в качестве для таблицы минимальная.

*Хеши написаны для little-ending архитектуры.

*Размеры таблицы вполне можно сделать круглыми, простыми сделал их на первых парах...

*Заодно можно будет избавится от деления по модулю при хешировании.

Код:
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <assert.h>

//#define HEAP_PROFILE //turn on collission counting

#define LOG2l(X) ((unsigned) ( 8*sizeof (long) - __builtin_clzl((X)) - 1))
#define COUNT_OF(arr) (sizeof(arr)/sizeof(arr[0]))

#define SWAP(a, b) do { \
    typeof (a) _a = (a); \
    a = b;\
    b=_a;} while (0)

#define SIZE_RING 10

typedef int16_t permutInt_t;
typedef permutInt_t permut_t[SIZE_RING];

static const permut_t ring = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
//static const permut_t ring = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

static size_t hashPrimes[]={ 61l, 127l, 251l, 509l, 1021l, 2039l, 4093l, 8191l,
    16381l, 32749l, 65521l, 131071l, 262139l, 524287l, 1048573l, 2097143l,
    4194301l, 8388593l, 16777213l, 33554393l, 67108859l, 134217689l }; // primes number for hash size

typedef struct spectrNode_t {
    permut_t spectVector;
    struct spectrNode_t *next;
} spectrNode_t;

typedef struct spectrHash_t {
    size_t sz;
    spectrNode_t **tbl;
    size_t num;
    uint8_t size_cnt;
    uint32_t seed;
#ifdef HEAP_PROFILE
    size_t collisions;
#endif // HEAP_PROFILE
} spectrHash_t;

int spectrHash_rehash (spectrHash_t *hash);

inline uint32_t murmur3_32(const uint8_t* key, size_t len, uint32_t seed) {
    uint32_t h = seed;
    if (len > 3) {
        const uint32_t* key_x4 = (const uint32_t*) key;
        size_t i = len >> 2;
        do {
            uint32_t k = *key_x4++;
            k *= 0xcc9e2d51;
            k = (k << 15) | (k >> 17);
            k *= 0x1b873593;
            h ^= k;
            h = (h << 13) | (h >> 19);
            h = (h * 5) + 0xe6546b64;
        } while (--i);
        key = (const uint8_t*) key_x4;
    }
    if (len & 3) {
        size_t i = len & 3;
        uint32_t k = 0;
        key = &key[i - 1];
        do {
            k <<= 8;
            k |= *key--;
        } while (--i);
        k *= 0xcc9e2d51;
        k = (k << 15) | (k >> 17);
        k *= 0x1b873593;
        h ^= k;
    }
    h ^= len;
    h ^= h >> 16;
    h *= 0x85ebca6b;
    h ^= h >> 13;
    h *= 0xc2b2ae35;
    h ^= h >> 16;
    return h;
}

inline uint32_t hashFNV (const void *arr, size_t sz) { // FNV-1a hash
    uint32_t rv = 0x811c9dc5;
    while(sz--) {
        rv = (rv*16777619) ^ *(uint8_t*)arr++;
    }
    return rv;
}

inline uint32_t spectrHash_hashVal (const void *val, spectrHash_t* hash) {
    return  murmur3_32 (val, sizeof(permutInt_t)*SIZE_RING, hash->seed) % hash->sz;
    //return  hashFNV (val, sizeof(permutInt_t)*SIZE_RING) % hash->sz;
}

int spectrHash_init (spectrHash_t* hash) {
    hash->size_cnt = 0;
    hash->sz = hashPrimes[hash->size_cnt];
    hash->num = 0;
#ifdef HEAP_PROFILE
    hash->collisions = 0;
#endif // HEAP_PROFILE
    hash->seed = hash->sz-2; //< should actually be random
    hash->tbl = malloc ( hash->sz*sizeof(hash->tbl[0]) );

    if (hash->tbl) {
        memset (hash->tbl, 0, hash->sz*sizeof(hash->tbl[0]));
        return 0;
    } else {
        return 1;
    }
}

/**
 * Tries to find a node with given value in the table. If the value is not in the table
 * insert it.
 * @returns a pointer to either the found or inserted value.
 */
spectrNode_t *spectrHash_findOrInsert (spectrHash_t *hash, permut_t val) {
    uint32_t valHash = spectrHash_hashVal (val, hash);

    spectrNode_t *node = hash->tbl [valHash], *last;
    if (node) {
        do {
            if (memcmp (val, node->spectVector, sizeof(*val)*SIZE_RING) == 0) {
                // we found the node; return ir
                return node;
            }
            last = node;
            node = node->next;
        } while (node);
        // we haven't found the node; insert to the last node
        last->next = malloc (sizeof(spectrNode_t));
        node = last->next;
#ifdef HEAP_PROFILE
        hash->collisions++;
#endif // HEAP_PROFILE
    } else {
        // hash key is empty; insert directly to the table
        hash->tbl [valHash] = malloc (sizeof(spectrNode_t));
        node = hash->tbl [valHash];
    }
    assert (node);
    memcpy (node->spectVector, val, sizeof(*val)*SIZE_RING);
    node->next = 0;
    if (4*++hash->num > 3*hash->sz) {
        spectrHash_rehash (hash);
    }
    return node;
}

int spectrHash_rehash (spectrHash_t *hash) {
    hash->size_cnt++;
    size_t old_sz = hash->sz;

    if (hash->size_cnt < COUNT_OF(hashPrimes)-1) {
        hash->sz = hashPrimes[hash->size_cnt];
    } else {
        hash->sz = old_sz<<1;
    }
    spectrNode_t **new_tbl = malloc (hash->sz*sizeof(new_tbl[0]));
    assert (new_tbl);
    memset (new_tbl, 0, hash->sz*sizeof(new_tbl[0]));
#ifdef HEAP_PROFILE
    hash->collisions = 0;
#endif // HEAP_PROFILE
    hash->seed = hash->sz-2; //< should be random

    for (size_t i=0; i<old_sz; i++) {
        for (spectrNode_t *node = hash->tbl[i], *next; node; node=next) {
            next = node->next;
            node->next = 0;
            uint32_t valHash = spectrHash_hashVal (node->spectVector, hash);

            if (!new_tbl[valHash]) {
                new_tbl[valHash] = node;
            } else {
#ifdef HEAP_PROFILE
                hash->collisions++;
#endif // HEAP_PROFILE
                spectrNode_t *tail;
                for (tail = new_tbl[valHash]; tail->next; tail=tail->next) {}
                tail->next = node;
            }
        }
    }

    free ( hash->tbl );
    hash->tbl = new_tbl;

    return 0;
}

void countSpectVector(spectrHash_t *hash, permut_t perm)
{
    permut_t intSpectr;
    int i = 0;
    permutInt_t diffTmp = 0, betta = 0;

    memset(intSpectr, 0, SIZE_RING * sizeof(intSpectr[0]));

    for (i = 0; i < SIZE_RING; i++){
        betta = ring[i];
        diffTmp = perm[( 1 + betta ) % SIZE_RING] - perm[betta];
        if (diffTmp < 0)
            diffTmp += SIZE_RING;
        intSpectr[diffTmp]++;
    }
    spectrHash_findOrInsert(hash, intSpectr);
}

void generatePerms(permut_t arr, spectrHash_t *hash)
 {
     permut_t c;
    int i;

    i = 0;
    memset(c, 0, SIZE_RING * sizeof(c[0]));

    while (i < SIZE_RING) {
        if (c[i] < i) {
            if (i % 2 == 0)
                SWAP(arr[0], arr[i]);
            else{
                SWAP(arr[c[i]], arr[i]);
            }
            countSpectVector(hash, arr);
            c[i] += 1;
            i = 0;
        }
        else {
            c[i] = 0;
            i += 1;
        }
    }
}

int main()
{
    permut_t perm;
    spectrHash_t hash;

    spectrHash_init (&hash);

    for (size_t i = 0; i < SIZE_RING; i++)
        perm[i] = i;

    generatePerms(perm, &hash);

#ifdef HEAP_PROFILE
    int collisionCounters[36];
    memset (collisionCounters, 0, sizeof(collisionCounters));

    for (size_t i=0; i<hash.sz; i++) {
        if(hash.tbl[i]) {
            size_t col = 0;
            for (spectrNode_t *head = hash.tbl[i]; head->next; head=head->next) {
                col++;
            }
            if(col) {
                switch(col) {
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        collisionCounters[col-1]++;
                        break;
                    default:
                        collisionCounters[LOG2l(col)+2]++;
                        // smart-ass for sort array to the buckets there each bucket contains element <2^N
                        break;
                }
            }
        }
    }
    printf("size = %zd, num =  %zd collision = %zd\n",
            hash.sz, hash.num, hash.collisions);
    long i;
    bool is_print_started = false;
    for(i=COUNT_OF (collisionCounters)-1; i > 4; i--) {
        if (is_print_started || collisionCounters[i]) {
            printf ("%4d collisions with depth <%lu\n", collisionCounters[i], 1l<<(i-2));
            is_print_started = 1;
        }
    }
    for(; i>=0; i--) {
        if (is_print_started || collisionCounters[i]) {
            printf ("%4d collisions with depth %ld\n", collisionCounters[i], i+1);
            is_print_started = 1;
        }
    }
#endif // HEAP_PROFILE

    return 0;
}

extern inline uint32_t hashFNV (const void *arr, size_t sz);
extern inline uint32_t murmur3_32(const uint8_t* key, size_t len, uint32_t seed);
extern inline uint32_t spectrHash_hashVal (const void *val, spectrHash_t* hash);


text:
Q: Creation a custom JSON converter I'm using json.net for experimentation and I'm trying to create a custom converter with that json :
{
    "daily" :
    {
        "1388361600000": 2081,
        "1388448000000": 2171,
        "1388534400000": 2244,
        "1388620800000": 2271
    },
    "average":
    {
        "1388361600000": 1923,
        "1388448000000": 1942,
        "1388534400000": 1963,
        "1388620800000": 1984
    }
}

the keys are timestamp (they are random)
I am trying to convert to a rootobject auto-created with a Daily class and an Averange Class. I see the ReadJSON and WriteJSON things, but I don't know how to use them for my conversion. I don't want to use the dynamic keyword, I want to make a proper object. So, there's a way to convert that?
Class :
public class Rootobject
{
    public Daily daily { get; set; }
    public Average average { get; set; }
}

public class Daily
{
    public Dictionary<string, string> dic;
}

public class Average
{
    public Dictionary<string, string> dic;
}

A: You don't need a converter if you define your RootObject class like this:
public class RootObject
{
    public Dictionary<string, int> daily { get; set; }
    public Dictionary<string, int> average { get; set; }
}

Would that work for you?


text:
Q: HTML CSS Menu with Sub Menus I am trying to create a custom navigation bar with sub menus with very simple coding to keep it light but its not working properly. Please have a look at this code and fiddle link. Fiddle https://jsfiddle.net/tjmkf9sb/
As you can see that I want to create a hoverable sub menu but the sub menus are not obeying display: none property right now. Please help.
CSS
.menu {
    border: 1px solid aliceblue;
    margin-top: 55px;
    margin-left: auto;
}
.menu li {
    list-style: none;
    padding: 15px;
    border-radius: 5px;
    color: #fff;
    background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #1fc8db, #2cb5e8); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #1fc8db, #2cb5e8); /* Standard syntax */
    display: inline;
}
.menu li:hover {
    background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #26cfe3, #1aade4); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #26cfe3, #1aade4); /* Standard syntax */
}
.menu a:hover {
    text-decoration: none;
}
.menu li ul {
    display: block;
}
.submenu ul {
  display: none;
  position: absolute;
}

HTML

Dashboard

        Licence Orders

Paid Orders

Unpaid Orders

Dashboard

Logout

Please help me. I have been stuck on this for quite some time now.

A: Add:
.menu li ul {
    display: none;
}

.menu li:hover ul {
    display: block;
}

.menu {
 border: 1px solid aliceblue;
 margin-top: 55px;
 margin-left: auto;
}
.menu li {
 list-style: none;
 padding: 15px;
 border-radius: 5px;
 color: #fff;
 background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #1fc8db, #2cb5e8); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #1fc8db, #2cb5e8); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #1fc8db, #2cb5e8); /* Standard syntax */
 display: inline;
}
.menu li:hover {
 background: red; /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(left top, #26cfe3, #1aade4); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(bottom right, #26cfe3, #1aade4); /* For Firefox 3.6 to 15 */
  background: linear-gradient(to bottom right, #26cfe3, #1aade4); /* Standard syntax */
}
.menu a:hover {
 text-decoration: none;
}
.menu li ul {
 display: none;
}

.menu li:hover ul {
  display: block;
}
.submenu ul {
  display: none;
  position: absolute;
}

Dashboard

      Licence Orders

Paid Orders

Unpaid Orders

Dashboard

Logout

Style with your rules.
Edit: Only li can be descendent from ul


text:
Q: How to clear specific image from cache in Flutter? How can I remove specific image-url from cache? I've read This question, but the accepted answer is clearing all the cache, also I've checked this one that is using a library (that I don't want to use). Does flutter have any ability to clear specific image that is already cached by:
precacheImage(NetworkImage(imageAddress), context);

The reason is that I have a page full of cached-images, I want to clear them all (to free memory) when the user passes it and goes to another page (after all, do I need do this?).


text:
Q: MongoDB > Can I upsertMany using instance data in the query I'm currently attempting to synchronise data from an external source, into a Mongo database. The data comes in, as an array, and I'd like to BULK insert or update ("upsert") the data, depending on whether a record with a matching customid already exists.
var data = [{
    customid: '123',
    name: 'Bob',
    occupation: 'Builder'
}]

db.foobar.insertMany(data)

Insert is fine, but now (on subsequent synchronisations), I would like to insert/update the following (sample) data, not knowing if the customid exists... is there any way to do this as a bulk operation? e.g.
var newdata = [{
    customid: '123',
    name: 'Bob',
    occupation: 'Nightclub Bouncer'
}]

db.foobar.updateMany({ customid: $instance.customid }, newdata, { upsert: true })

... or is the only way, to manually iterate over the records and run an update(..)?

A: I've found a compromise, using bulkWrite and multiple updateOne statements. If anyone has a better solution, please don't hesitate to post it.
https://stackoverflow.com/a/47832754/782034


text:
Q: How to determine which package to install? On the Mac, since I used node to run NodeJS, so I assume I would do the same on Ubuntu (just like gcc for the GNU C Compiler).
So I typed node, and it says
The program 'node' can be found in the following packages:
 * node
 * nodejs-legacy
Try: sudo apt-get install <selected package>

So it seemed like it would be node.
But then if I use apt-cache search ^node$ to search for its description, it showed nothing.  If I use apt-cache search ^nodejs$, then it would show nodejs - evented I/O for V8 javascript.
And so it seemed like it would be nodejs.
(Also, apt-cache show node didn't show anything, while apt-cache show nodejs showed a lot of info, so there seemed to be higher chance that it is nodejs.  However, what about the fact when I typed node, it said "The program 'node' can be found in the following packages: node, nodejs-legacy"?)
In this situation, how can you tell which one is the correct one?  I am less interested in knowing just which one is the correct one, but more interested to learn how to find out from the given information so far.
--
Update:
as per @muru's request, this is the output from
$ sudo apt-get update

Hit http://us.archive.ubuntu.com wily InRelease
Hit http://us.archive.ubuntu.com wily-updates InRelease
Hit http://security.ubuntu.com wily-security InRelease
Hit http://us.archive.ubuntu.com wily-backports InRelease
Hit http://us.archive.ubuntu.com wily/main Sources
Hit http://security.ubuntu.com wily-security/main Sources
Hit http://us.archive.ubuntu.com wily/restricted Sources
Hit http://security.ubuntu.com wily-security/restricted Sources
Hit http://us.archive.ubuntu.com wily/universe Sources
Hit http://us.archive.ubuntu.com wily/multiverse Sources
Hit http://security.ubuntu.com wily-security/universe Sources
Hit http://us.archive.ubuntu.com wily/main amd64 Packages
Hit http://us.archive.ubuntu.com wily/restricted amd64 Packages
Hit http://security.ubuntu.com wily-security/multiverse Sources
Hit http://us.archive.ubuntu.com wily/universe amd64 Packages
Hit http://security.ubuntu.com wily-security/main amd64 Packages
Hit http://us.archive.ubuntu.com wily/multiverse amd64 Packages
Hit http://us.archive.ubuntu.com wily/main i386 Packages
Hit http://security.ubuntu.com wily-security/restricted amd64 Packages
Hit http://us.archive.ubuntu.com wily/restricted i386 Packages
Hit http://us.archive.ubuntu.com wily/universe i386 Packages
Hit http://security.ubuntu.com wily-security/universe amd64 Packages
Hit http://us.archive.ubuntu.com wily/multiverse i386 Packages
Hit http://us.archive.ubuntu.com wily/main Translation-en
Hit http://security.ubuntu.com wily-security/multiverse amd64 Packages
Hit http://us.archive.ubuntu.com wily/multiverse Translation-en
Hit http://security.ubuntu.com wily-security/main i386 Packages
Hit http://us.archive.ubuntu.com wily/restricted Translation-en
Hit http://security.ubuntu.com wily-security/restricted i386 Packages
Hit http://us.archive.ubuntu.com wily/universe Translation-en
Hit http://security.ubuntu.com wily-security/universe i386 Packages
Hit http://us.archive.ubuntu.com wily-updates/main Sources
Hit http://us.archive.ubuntu.com wily-updates/restricted Sources
Hit http://security.ubuntu.com wily-security/multiverse i386 Packages
Hit http://us.archive.ubuntu.com wily-updates/universe Sources
Hit http://us.archive.ubuntu.com wily-updates/multiverse Sources
Hit http://security.ubuntu.com wily-security/main Translation-en
Hit http://us.archive.ubuntu.com wily-updates/main amd64 Packages
Hit http://security.ubuntu.com wily-security/multiverse Translation-en
Hit http://us.archive.ubuntu.com wily-updates/restricted amd64 Packages
Hit http://us.archive.ubuntu.com wily-updates/universe amd64 Packages
Hit http://security.ubuntu.com wily-security/restricted Translation-en
Hit http://us.archive.ubuntu.com wily-updates/multiverse amd64 Packages
Hit http://us.archive.ubuntu.com wily-updates/main i386 Packages
Hit http://security.ubuntu.com wily-security/universe Translation-en
Hit http://us.archive.ubuntu.com wily-updates/restricted i386 Packages
Hit http://us.archive.ubuntu.com wily-updates/universe i386 Packages
Hit http://us.archive.ubuntu.com wily-updates/multiverse i386 Packages
Hit http://us.archive.ubuntu.com wily-updates/main Translation-en
Hit http://us.archive.ubuntu.com wily-updates/multiverse Translation-en
Hit http://us.archive.ubuntu.com wily-updates/restricted Translation-en
Hit http://us.archive.ubuntu.com wily-updates/universe Translation-en
Hit http://us.archive.ubuntu.com wily-backports/main Sources
Hit http://us.archive.ubuntu.com wily-backports/restricted Sources
Hit http://us.archive.ubuntu.com wily-backports/universe Sources
Hit http://us.archive.ubuntu.com wily-backports/multiverse Sources
Hit http://us.archive.ubuntu.com wily-backports/main amd64 Packages
Hit http://us.archive.ubuntu.com wily-backports/restricted amd64 Packages
Hit http://us.archive.ubuntu.com wily-backports/universe amd64 Packages
Hit http://us.archive.ubuntu.com wily-backports/multiverse amd64 Packages
Hit http://us.archive.ubuntu.com wily-backports/main i386 Packages
Hit http://us.archive.ubuntu.com wily-backports/restricted i386 Packages
Hit http://us.archive.ubuntu.com wily-backports/universe i386 Packages
Hit http://us.archive.ubuntu.com wily-backports/multiverse i386 Packages
Hit http://us.archive.ubuntu.com wily-backports/main Translation-en
Hit http://us.archive.ubuntu.com wily-backports/multiverse Translation-en
Hit http://us.archive.ubuntu.com wily-backports/restricted Translation-en
Hit http://us.archive.ubuntu.com wily-backports/universe Translation-en
Reading package lists... Done

$ apt-cache show node | grep -i Desc
$                           # <-- nothing is showing up as result

$ apt-cache show node
N: Can't select versions from package 'node' as it is purely virtual
N: No packages found

A: From Digital Ocean:
To install node on Ubuntu, do the following:

*

*Update your current packages:
sudo apt-get update

*To add source (for more recent versions, also, node recommends to download it from here):
wget -c https://deb.nodesource.com/setup | sudo bash -

*To install node.js:
sudo apt-get install nodejs

*You might also need build-essential for more features (required by npm):
sudo apt-get install build-essential

A: Running apt-cache show should show their descriptions:
$ apt-cache show node | grep -i Desc
Description: Amateur Packet Radio Node program (transitional package)
Description-md5: 1278ed271672fd829c99361f93f468da
$ apt-cache show nodejs | grep -i Desc
Description: evented I/O for V8 javascript
Description-md5: e507fb472d7cdaceffc5b285a62d5c1b

If it doesn't, you can still visit the Package Index. Just go to http://packages.ubuntu.com/<package-name>:

*

*node

*nodejs
As you can see, in both pages, the packages have descriptions next to their names.


text:
Q: Solving the following recurrence $T(1) = 2$
$T(n) = T(n-1) + n/2$
My guess is this would be equivalent to $T(n) = 2 + \sum\limits_{i=2}^n \frac{n}{2^{i-1}}$. However, I don't know how to advance from here.

A: HINT
Note that
$$
\begin{split}
T(n) &= T(n-1) + \frac{n}{2} \\
     &= T(n-2) + \frac{n-1}{2} + \frac{n}{2} \\
     &= \ldots \\
     &= T(n-n) + \sum_{k=1}^n \frac{k}{2} \\
     &= T(0) + \frac{1}{2} \sum_{k=1}^n k
\end{split}
$$


text:
Q: Firebase Hosting - OAuth Redirect Is it possible to use a Firebase Hosted site with OAuth 2.0 for a third party API? I would like to use the Quizlet API. This requires an OAuth 2.0 redirection flow and a custom state parameter.

State: A random string generated by you. You send us this, and we'll send it back to you, and you verify that we send back the same thing you sent.
  You must send and verify this value in order to prevent CSRF attacks.

So for example:
https://quizlet.com/authorize?response_type=code&client_id=MY_CLIENT_ID&scope=read&state=RANDOM_STRING
This would take the user away from my Firebase Hosted page and then they would authenticate. Upon authentication, Quizlet would send me back to:
REDIRECT_URL/?code=GENERATED_CODE&state=YOUR_STATE&expires_in=60
Can I somehow catch these URL query parameters in my Firebase Hosted site or its Angular code?
Thanks!


text:
Q: Node js soap: unable to create client :Error: unable to verify the first certificate I am trying to connect the SOAP web service using soap package
Here is my code
var options = {
    wsdl_options: {
      forever: true,
      rejectUnauthorized: false,
      strictSSL: false,
      pfx: fs.readFileSync(__dirname + '/certs/test_cert.pfx'),
      passphrase: '123123'
    }
  };

  soap.createClient(process.env.SOAP_ENDPOINT, options, function (err, client) {
    console.log(err);
    console.log(client);
  });

While executing this I m getting the following error
Error: unable to verify the first certificate
    at TLSSocket.onConnectSecure (node:_tls_wrap:1531:34)
    at TLSSocket.emit (node:events:378:20)
    at TLSSocket._finishInit (node:_tls_wrap:945:8)
    at TLSWrap.ssl.onhandshakedone (node:_tls_wrap:719:12) {
  code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
  config: {
    url: '<URL>?WSDL',
    method: 'get',

Not sure why I am getting this however I am successfully able to connect through the soap UI in that I am using a p12 file.


text:
Q: Can't launch applications after uninstalling theme I am using Ubuntu 18.04 with GNOME environment. I'm not very experienced in Linux. I was just customizing my desktop by installing themes, icon packs, etc. using gnome tweaks tool.
I was using a material theme alongside with Communitheme (Yaru) icons but on Ubuntu session (not on communitheme session). Then after uninstalling communitheme and logging out and in, my icons are gone and I can't launch most of the applications including terminal, file manager, gnome tweak tool.
I tried to remove gnome tweak tool from Alt+F2 command line but that didn't work. Is there a way to disable themes temporarily so I can pick another theme from tweak tool?
Here is a screenshot:

A: I reset icon theme by pressing Alt+F2 and entering this code: gsettings reset org.gnome.desktop.interface icon-theme. then all the icons came back. Now I can start the apps.


text:
Q: User disconnects often First, I literally learned nodejs today.
I have a nodejs application that uses express. I have proxied it through apache. The application works fine (the server streams data in real time to the user presented on a browser), but for some reason, after some random amount of time, the user disconnects. My server.js looks like this
var express = require('express'),
    app = express(),
    path = require('path'),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    feed = require('./feed');

app.use(express.static(path.join(__dirname, './www')));

    io.on('connection', function (socket) {
        console.log('User connected. Socket id %s', socket.id);

        socket.on('join', function (rooms) {
            console.log('Socket %s subscribed to %s', socket.id, rooms);
            if (Array.isArray(rooms)) {
                rooms.forEach(function(room) {
                    socket.join(room);
                });
            } else {
                socket.join(rooms);
        }
    });

    io.on('configure', function() {
        io.set('close timeout', 60*60*24); // 24h time out
    });

    socket.on('leave', function (rooms) {
        console.log('Socket %s unsubscribed from %s', socket.id, rooms);
        if (Array.isArray(rooms)) {
            rooms.forEach(function(room) {
                socket.leave(room);
            });
        } else {
            socket.leave(rooms);
        }
    });

    socket.on('disconnect', function () {
        console.log('User disconnected. %s. Socket id %s', socket.id);
    });

    socket.on('close', function() {
         console.log('Close. Socket id %s', socket.id);
    });

    socket.on('end', function() {
        console.log('end. Socket id %s', socket.id);
    });
});

feed.start(function(room, type, message) {
    io.to(room).emit(type, message);
});

http.listen(8080, function () {
    console.log('listening on: 8080');
});

After searching the web, I thought maybe there is some kind of timeout/heartbeat that is not working, so I tried
io.on('configure', function() {
            io.set('close timeout', 60*60*24); // 24h time out
        });

But it doesn't work. I am not sure how to debug these applications. Is there anything that I should try? It seems hard to believe that it is a browser issue, but I am not sure. Perhaps also something extra has to be configured in the apache proxy.
If I refresh the browser, I can see the server print that the user has connected and it starts to display data again on the browser (although sometimes for some reason it takes a couple of refresh), and then randomly stops working some time thereafter.


text:
Q: writing to pipe signals synchronization Here's what I'd like to do:
(It is a part of the bigger assignment)
And I'm stuck at the start of it.
I've created the main process which forks p1,p2 processes and used execlp(separate programs). They're are supposed to read one word per line from p1.txt (process p1) and p2.txt (process p2) and write it to the pipe. Then in the main process, proc_pr is forked (I don't have the source code for it) , which should send SIGUSR 1 to them whenever it wishes to read a word from pipe and then writes it to the second pipe.
I've tried to come up with simple code in p1, but it does not work most of the time, only in some cases. I could tell from the output of proc_pr that it sent the signal to p1 and then nothing happens.
I've seen the solution using the open(),read() and lseek() but I used fopen() and fgets().
Any help is appreciated.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>

#define MAXLENGTH 150               //definujme si maximalnu dlzku retazca

int fd; int data_processed;         //file deskriptor a premenna na pocitanie precitanych dat
char buff[150];                 //buffer
FILE *f;                    //smernik na prud suboru

/* odchytenie signalu, subor je uz otvoreny a fd nacitany */
void odchytenie(int sig)
{
    /* read a line */
    if ( fgets ( buff, sizeof buff, f ) != NULL )
       {
             /* write the line */
            fputs ( buff, stdout );

            /* store the word into pipe */
           write(fd,buff,strlen(buff));
       }
       else
        {
            //do something to stop the process and close the file
        }

}

int main(int argc, char *args[])
{

 /* prevedieme retazec z parametra na cislo deskriptora pipe na zapis */
 fd = atoi(args[1]);

 /* otvorime subor p1 */
 f=fopen("p1.txt","r");

/* zabezpeci odchytenie signalu */
(void) signal(SIGUSR1,odchytenie);

/* pocka na signal, proces sa neukonci, ani sa nezavrie subor */
while(1)
 {
    sleep(1);
 }

 /* close the file */
 fclose(f);

 /* exit with value 0 */
 exit(0);

}

A: Hm, I've figured it out. The problem was in the main process. And I should probably use async-safe functions in handler.


text:
Q: I'm looking for the word that means opposition towards a specific nation or country Essentially, I'm looking for a word that means the opposite of nationalism. Whereas nationalism means support for a nation's interests, the word I'm looking for means opposition to a certain nation's interests.
Does such a word exist?
I found anti-nationalism, but that means opposition to nationalism as a concept, and also xenophobia, but that means opposition to any nation other than your own. What I'm looking for is opposition to a single specific nation; essentially a hypernym for conc

A: I don't believe there is a specific word, but you can prefix a country's name with "anti" to indicate opposition to the country in general. For example:

He is anti-Russia or anti-Russian

indicates that he is opposed to the country, its government, its ideals, its actions, etc.


text:
Q: Select some rows of a html table and sent the values of one column of selected rows to another php page when clicking a link I have a requirement to select some rows of a html table and sent the values of one column of selected rows to another php page when clicking a link. How it can be done?
With a form i can store values in an form element array and can send to a php array vairable when clicking submit button. but in this case it has to pass through a link.
<?php
$query2="select * from products";
$result2=mysqli_query($connection, $query2);
?>

        <input type="checkbox" id="0" />
        Item
        Date
        Type
        Price
        SKU
        Description

<?php
$i=1;
while($row2=mysqli_fetch_array($result2))
{
?>

            <input type="checkbox" id="<?php $i; ?>" name="check['<?php echo $i; ?>']" value="<?php echo $row2['id']; ?>"/>
            $row2['item']
            $row2['date']/td>
            $row2['type']
            $row2['price']
            $row2['sku']
            $row2['description']

<?php
$i++;
}
?>

Review Selected Items

I want to store "Item" column values of the selected rows in a variable and need to pass it to another php file where i want to fetch aall related details of the selected items from database like amount, tax etc and display it in a html table.

A: set the products id in the id attribute and on the click of review button send those ids in the GET method to the next page and there user $_GET to retrieve those ids and from those ids execute the sql query to get particular products
it will redirect something like this:
http://localhost/yourpage?id=1,2,3
and get this ids and explode them.


text:
Q: I Need a way to execute a particular function when i press the forward key or the back key in javascript I need a way to execute a particular function when I press the forward key or the back key in javascript.  So that it may work when the forward button is pressed it may execute the function but it should work without taking the input in any type of text box.
I mean it should work on the whole page no matter where I am on the page but if I press the forward button the function should be executed.
I know how to do it by taking an input in a text box by matching the key codes but don't know how to make it work in someway else.

A: If by forward and back keys you mean the arrow keys, this is how you can do it!
document.onkeydown = function(e) {
e = e || window.event;
switch(e.which || e.keyCode) {
    case 37: // left
    break;

    case 38: // up
    break;

    case 39: // right
    break;

    case 40: // down
    break;

    default: return; // exit this handler for other keys
}
   e.preventDefault(); // prevent the default action
});

A: I feel pretty confident with my assumption that you are referring to the arrow keys on the keyboard. And as you say you already have working code for when a textbox is focused, I also assume you are using onkeydown (or one of the similar ones) already. So the solution is to add the event listener to the document instead.
Like this for example:
document.onkeydown = function(e){
    // Your existing code goes here.
}

You need to use onkeydown if you want to detect arrow keys.
Here is a working example

A: Use onkeydown as this should work for all browsers. I don't think onkeypress will work with google chrome for the arrow key events.

*

*38 = Up Arrow

*40 = Down Arrow

To find more you can use console.log(event.keyCode); in your onkeydown function to log the key codes to your browsers console.

function MyFunc() {
  alert("Key up or down!");
}
document.onkeydown = function() {
  if (event.keyCode == 38 || event.keyCode == 40) {
    MyFunc();
  }
}

If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!


text:
Q: create object key and property of object dynamically I want to create a new object dynamically and insert into the inside of columns object
dynamicCreate = [
    {
        columns: {
            title: {
                title: "Title"
            }
        }
    }
]

Create dynamically like
name: {
    title: "Name"
},

and insert next of
title: {
    title: "Title"
},

A: You can try using the dot notation

var obj={};
obj.title={};
obj.title.title="name";
console.log(obj)

A: Javascript is a dynamic language. so you can assign any props dynamically to the object.

var obj={
  name:'foo'
};
obj.extraInfo={
  bar:'baz'
}

console.log(obj);


text:
Q: I want to appeal this problem from an exam in Linear Algebra I, do you think its appealable? I have the follow question :
Let $U_1, U_2, W$ are linear spans of linear space $V$ while V is finite.
Proof:
If $$U_2 \cap W \neq \{0\}$$
$$U_1\cap W\neq \{0\}$$
$$U_1 \cap U_2=\{0\}$$
Then $dimW \geq 2$
My proof :
Since $U_1 \cap W \neq \{0\}$ there is a least one $v$ that $v \in Sp\{U_1 \cap W\}$ impiles $v \in Sp\{U_1\}$ and $v \in Sp\{W\}$
In a similar way since $U_2 \cap W \neq \{0\}$ there is a least one $u$ that $u \in Sp\{U_2 \cap W\}$ impiles $u \in Sp\{U_2\}$ and $u \in Sp\{W\}$
Let $u_1,u_2$ be any vectors so that $u_1 \in Sp\{U_1 \cap W\}$ and $u_2 \in Sp\{U_2 \cap W\}$.
If the group $\{u_1,u_2\}$ is linear dependent then we get a contradiction to $U_1 \cap U_2=\{0\}$
Therefore we proof that for all $u_1 \in Sp\{U_1 \cap W\}$ and to all $u_2 \in Sp\{U_2 \cap W\}$ Therefore $\{u_1,u_2\}$ is linear independent therefore we proved the existence of $u \in Sp\{W\}$ and $v \in Sp\{W\}$, and from the proof above we know that $\{u,v\}$ is linear dependant, therefore we get $dimW \geq 2$
For some reason the examiner, has marked this line
If the group $\{u_1,u_2\}$ is linear dependent then we get a contradiction to $U_1 \cap U_2=\{0\}$
And wrote why? This claim requires a proof. and I got 7/12 point for this question.
I think this is trivial and also from the proof above it's clear that I understand why this statement is true.
I'd be very happy to hear from examiners of linear algebra exams, do you think this is appealable? or do you think that this is justified?
Since the grade can go down or up then I appeal I'd like to consult about this matter first.
I really appreciate any help, Thank you!

A: Well first complete the proof.
$ \{ u_1, u_2 \} $ linearly dependent implies $\alpha u_1 = u_2 $ so then $u_2 \in U_1 \cap U_2$ hence contradiction.
I think the marker was harsh as you don't really need much of an argument to prove the statement. Everything else seems fine so there is no worry that your mark will go down.
However do try and see the markers point of view, it is an easy question where not much work is required and being worth so many marks it may be expected that every step is necessary.


text:
Q: How do I structure my Parse data in the new Firebase? I am probably like many others, who has recently been learning to code in Swift, and was learning to also use Parse as a backend database.
I have recently decided that before launching my app, I want to explore Firebase, and I feel that this may be the better option for my app. Also, as Parse is shutting down it's services, I think this makes most sense.
From what I understand, Parse is a Relational Database, and Firebase is non-relational. And right now, I'm struggling to see how I can build what I already have in Parse, into Firebase.
To breifly explain my Parse set up:

*

*I have several classes, 2 of which are called Reviews, and Votes_Up

*The reviews class simply holds info about films that I have manually added. It also keeps a count against how many people have voted up or down for that particular film.

*Votes_Up class is more relational. It records which logged in user is voting up for which film.
As Firebase doesn't seem to have this Table structure but instead uses JSON trees, I'm struggling to work out how I will create my database in Firebase, and still create the same features I currently have. (In where I can show individual users which films they have voted for etc)
Can anyone help and give an example using my current Parse database classes, and how I would structure this in the new Firebase?

A: To complete the others answers   I suggest this structure:
• Film
    o  CRxIO5xmJ8
            DateReleased: "2015-12-29T09:15:50.165Z"
            filmName: "Money Monster"
            usersVoteFor
                    cXcofgX0x6gNFOLMLnuq5BnkxV73: true
                    xxxxxotherUIDfromAuthentication: true

    o  w5PvtvNT1X
            DateReleased: "2015-12-29T09:15:50.165Z"
            filmName: "Captain America"

•   User
       o cXcofgX0x6gNFOLMLnuq5BnkxV73
             filmsVotedFor
                   CRxIO5xmJ8: true
                   w5PvtvNT1X: true
             username: zozo

       o xxxxxotherUIDfromAuthentication
             username: zaza

A: You probably should consider something like:
users
films
  user voted for
reviewers
  film voted for

A: As you know the two PaaS platforms are totally different.

*

*With Parse you create the tables/Classes on the web dashboard and then use the SDK in your mobile app to read/write.

Firebase uses a data structure implementation (JSON blobs).

*

*Parse does not have a Web Socket framework which means you need to build it. With Parse you use the client/app to check the Parse tables to see if there's new data. This means with Parse there is a delay.

With Firebase they use Web Socket framework to tell you when data has changed. This means Firebase will notify all mobile apps/clients using the private specific key in their JSON that there is new data. Firebase is known to be more "real-time".

*

*In addition they use completely different user authentication.

What you need is Firebase's Structuring Data Guide
Have you considered using Parse Server?


text:
Q: Avoid Repeated Function call in WHERE Clause I know this is bad, I just don't know how to re-write it... any help appreciated!
DECLARE @i   INT,
    @var VARCHAR(max)

SET @i = 0

WHILE 1 = 1
BEGIN
  INSERT INTO mrs.dbo.nav_worldcheck_results
              ("counter",
               "entity no",
               "entity first name",
               "entity last name",
               "entity full name",
               "worldcheck uid",
               "worldcheck first name",
               "worldcheck last name",
               "worldcheck full name",
               "percentage match")
  SELECT TOP(1) [Counter] = @i,
                EN.[entity no_],
                EN.[name 2],
                EN.[name],
                EN.[name 2] + ' ' + EN.[name]          AS EntityName,
                SM.uid                                 AS WorldCheckID,
                SM.[first name],
                SM.[last name],
                SM.[first name] + ' ' + SM.[last name] AS WorldCheckName,
                dbo.Fn_calculatejarowinkler(EN.[name 2] + ' ' + EN.[name],
                SM.[first name] + ' ' + SM.[last name])
  FROM   [NAV_LIVE].dbo.[entitytable$entity] AS EN
         CROSS JOIN [NAV_LIVE].dbo.[worldcheck master] AS SM
  WHERE  ( EN.inactive = 0 )
         AND dbo.Fn_calculatejarowinkler(EN.[name 2] + ' ' + EN.[name],
                 SM.[first name] + ' ' + SM.[last name]) >= .75
         AND NOT EXISTS(SELECT *
                        FROM   mrs.dbo.nav_worldcheck_results AS WCR
                        WHERE  EN.[entity no_] = WCR.[entity no]
                               AND WCR.[worldcheck uid] = SM.uid)

  SET @i = @i + 1
END

I want to avoid the repeated function call in the where statement and I've tried assigning all as variables and then processing but I fall into the trap of you can't mix sets with data retrieval and my poor little brain is in Friday mode! :o/

A: It doesn't look like you can optimize out your function call. Potentially you could consider pre computing this value if the query needs to be run regularly and the data doesn't change.
I recommend that you read a little more about joins and determine if a cross cartesian is really necessary in your case(most of the time you actually want an inner join). http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
You should really also consult with your DBAs to ensure you are operating on Indexed columns or see if they can add indexes to speed things up.
I would also look into learning about your databases(I assume MSSQL) query tuning capabilities. Notably the explain plan can tell you in more depth what your query is actually doing and where you could optimize.
Although its impossible to know how the query is being optimized beforehand, in general NOT EXISTS and EXISTS filters can be horribly inefficient.  Especially if the filter on the not exists query returns more than one row or if it operates on non indexed columns.  Either way I recommend select 1 instead of select * since reducing the number of columsn selected is an easy optimization.

A: In this case SqlServer query processor (looks like you use SqlServer?) does not necessarily call dbo.Fn_calculatejarowinkler function twice for every returned row (first time in select part and second time in the where clause) as you may think. If function is deterministic, likely it does not doing it.
You may rewrite your statement:
SELECT
    ...
    dbo.Fn_calculatejarowinkler(EN.[name 2] + ' ' + EN.[name],
            SM.[first name] + ' ' + SM.[last name])
    ...
FROM ... AS EN
    CROSS JOIN ... AS SM
WHERE
    ...
    AND dbo.Fn_calculatejarowinkler(EN.[name 2] + ' ' + EN.[name],
                 SM.[first name] + ' ' + SM.[last name]) >= .75
    ...

in the following way:
SELECT
    ...
    F.Value,
    ...
FROM ... AS EN
    CROSS JOIN ... AS SM
    CROSS APPLY (
        select dbo.Fn_calculatejarowinkler(EN.[name 2] + ' ' + EN.[name],
            SM.[first name] + ' ' + SM.[last name])
    ) F(Value)
WHERE
    ...
    AND F.Value >= .75
    ...

but unlikely you will gain in performance.

A: Thanks all for looking and taking the time to reply.
I've actually done as Deadron suggested and used a mix of inner join using soundex as the relationship rather than the cross join.
I've also added in the use of "difference" into the where clause rather than my Jaro function and performance has improved dramatically and it's returning hits that would be close enough to worry about.
Thanks again!


text:
Q: How can I through the OnModelCreating method create foreign keys dynamically On my EF6 model I have created certain base classes that contain properties/columns that I want to be inherited across several entities.
Here is a simple example of the concept:
public class Replaceable
{
    [Column("REPLACING")]
    public int Replacing { get; set; }
}

[Table("PARTS")]
public class Part : Replaceable
{
    [Column("ID"), Key]
    public int Id { get; set; }

    [Column("PART_NUMBER")]
    public string PartNumber { get; set; }
}

So the REPLACING property & column will be inherited to Part-class/PARTS-table.
The REPLACING column is supposed to point towards an ID in the same table. For example if you replace a part you want to keep track of what replaced what.
What I want to do (if possible) through OnModelCreating is:

*

*Get all entities that inherit from Replaceable.

*Mark the column REPLACING as a foreign key and point it to the entity's Primary Key (PART_ID, COMPONENT_ID etc).

The trick here is how to get the name of the ID column of each entity's table since all of them are not called ID but PART_ID, COMPONENT_ID etc.
Is this even possible? An alternative practice is also welcome.

A: You can use a base configuration class:
public abstract class ReplaceableConfiguration<T> : EntityTypeConfiguration<T>
    where T : Replaceable
{
    public ReplaceableConfiguration()
    {
        this.Property(r => r.Replacing).HasColumnName(typeof(T).Name + "_ID");
    }
}

And derive as many concrete classes as you want.
public class PartConfiguration : ReplaceableConfiguration<Part>
{ }

public class ComponentConfiguration : ReplaceableConfiguration<Component>
{ }

I tried this with just two classes:
modelBuilder.Configurations.Add(new PartConfiguration());
modelBuilder.Configurations.Add(new ComponentConfiguration());

Which gave me this DDL:
CREATE TABLE [dbo].[PARTS] (
    [ID] [int] NOT NULL IDENTITY,
    [PART_NUMBER] [nvarchar](max),
    [Part_ID] [int] NOT NULL,
    CONSTRAINT [PK_dbo.PARTS] PRIMARY KEY ([ID])
)

CREATE TABLE [dbo].[COMPONENTS] (
    [ID] [int] NOT NULL IDENTITY,
    [COMPONENT_NUMBER] [nvarchar](max),
    [Component_ID] [int] NOT NULL,
    CONSTRAINT [PK_dbo.COMPONENTS] PRIMARY KEY ([ID])
)


text:
Q: numbering cells in a column google app script All I am trying to do is set a range and then number the cells in that range, i.e. B2:B11 as 1, 2, 3,etc...
function numberMe() {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];
var counter = 1;
  var cell = sheet.getRange("G2:G11");
  while(counter <= 10){
 cell.setValues(counter);
  }

this just gives a single number like "1" in every cell rather than 1, 2, 3, etc... documentation mentions setValues() but that seems to set the values along the row rather than down the column

A: First, you're not incrementing counter, second, the documentation states that setValues() must be used with an array, all initialized, as a double array and with the exact same size as the range.
As so, your while should be
var cell = sheet.getRange("G2:G11");
var toPaste = [];
while(toPaste.length < cell.getNumRows()){
  toPaste.push([counter++]);
}
cell.setValues(toPaste);


text:
Q: How to remove gaps between bars in Matplotlib bar chart I'm making a bar chart in Matplotlib with a call like this:
xs.bar(bar_lefts, bar_heights, facecolor='black', edgecolor='black')

I get a barchart that looks like this:

What I'd like is one with no white gap between consecutive bars, e.g. more like this:

Is there a way to achieve this in Matplotlib using the bar() function?

A: It has been 8 years since this question was asked, and the matplotlib API now has built-in ways to produce filled, gapless bars: pyplot.step() and pyplot.stairs() with the argument fill=True.
See the docs for a fuller comparison, but the primary difference is that step() defines the step positions with N x and N y values just like plot() would, while stairs() defines the step positions with N heights and N+1 edges, like what hist() returns. It is a subtle difference, and I think both tools can create the same outputs.

A: Add width=1.0 as a keyword argument to bar().  E.g.
xs.bar(bar_lefts, bar_heights, width=1.0, facecolor='black', edgecolor='black').
This will fill the bars gaps vertically.

A: Just set the width 1 over the number of bars, so:
width = 1 / len(bar_lefts)
xs.bar(bar_lefts, bar_heights, width=width, color='black')

A: You can set the width equal to the distance between two bars:
width = bar_lefts[-1] - bar_lefts[-2]
xs.bar(bar_lefts, bar_heights, width=width)


text:
Q: Length of INT in C++ Is there a way for me to limit the number of characters of int in C++? I'm kind of new to this language. Hope I could get some answers from you, guys! Thank you!

A: If you talking about number of bits, you can use, short, char instead of int. You can see int8_t, etc in c++ reference

A: If you want to limit how many characters a user can input as an int, you can use a control-structure checking if the entered value is between 2 limits.
ex: if you want to limit a user to entering 2 char's, you can limit the input between -10 & 100
Limiting the size of the number (in bits) can be done by using a smaller type (smaller range).
byte < sbyte < ushort < short < uint < int < ...

A: char[4] defines an array of chars. You're not limiting the size of a char itself, but declaring an automatic-storage fixed-length array.
And sure, you can create int arrays in the same fashion: int[4].

A: if we use while loop like this code , We will make counter (n) is Increasing unless X=0 because of that condition will became (false),So will printed (n)
   #include <iostream>

using namespace std;

int main(){
    int x(1), n(0);
    while(x){
    //cout << x << endl;
    n++;
    x/=10;
    }
    cout << n;

}


text:
Q: ASP.NET Stored Procedure method not working I have this method that is calling a stored procedure:
public List<BarcodeClass> CheckTagId(int tagId)
{
    barcodes = new List<BarcodeClass>();
    try
    {
        using (SqlCommand command = new SqlCommand("uspCheckTagId", connection))
        {
            command.CommandType = CommandType.StoredProcedure;
            SqlParameter parameter = new SqlParameter("@TG", SqlDbType.Int)
            {
                Direction = ParameterDirection.Input,
                Value = tagId
            };
            command.Parameters.Add(parameter);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
            }
        }
    }
    finally
    {
        connection.Close();
    }

    return barcodes;
}

My problem is this does not work. I just get this message: An error has occurred. I know its not the connection to the database because if I change the stored procedures name to another stored procedure it doesnt return that error message. I have a feeling it has something to do with this part:

SqlParameter parameter = new SqlParameter("@TG", SqlDbType.Int)
{
    Direction = ParameterDirection.Input,
    Value = tagId
};

because I am passing in an int, if I use another stored procedure with a NVarChar and pass in a string this works! this there something wrong with the way I am passing in the int as parameter?
Here is the stored procedure:
    declare @TG int

    declare @L1R nchar(10) -- Label1 Return Variable
    declare @L2R nchar(10) -- Label2 Return Variable
    declare @L3R nchar(10) -- Label3 Return Variable
    declare @L4R nchar(10) -- Label4 Return Variable
    declare @LD1R nchar(15) -- LData1 Return Variable
    declare @LD2R nchar(15) -- LData2 Return Variable
    declare @LD3R nchar(15) -- LData3 Return Variable
    declare @LD4R nchar(15) -- LData4 Return Variable
    set @TG = 10001
    exec uspCheckTagId @TG, @L1 = @L1R output, @L2 = @L2R output, @L3 = @L3R output, @L4 = @L4R output,  @LD1 = @LD1R output, @LD2 = @LD2R output, @LD3 = @LD3R output, @LD4 = @LD4R output
    print @L1R
    print @L2R
    print @L3R
    print @L4r
    print @LD1R
    print @LD2R
    print @LD3R
    print @LD4r

Please help! I can't debug this because the database only works on the server I am pushing to and I dont have access to this server.

A: The syntax of creating a SP in sql server is:
CREATE PROCEDURE [schema].[procName]
    @param1 int,
    @param2 bit
AS
BEGIN
    -- SP Logic
    declare @someVar int, -- note this is a variable, not a parameter.
            @anotherVar varchar(10)

    -- select, updates, deletes, etc
END

What you've posted as your proc definition (which was incomplete) does not have a parameter name @TG, but rather a variable.  If you correct your proc to follow the above example, using parameters rather than variables, that should solve your immediate problem.
Additionally, based on your code comments, it looks like you're attempting to use output parameters.  those need to be set up in the SP declaration (just as normal parameters) but with the out or output modifier.
It seems you want something like this:
create procedure mySpName
    @TG int, -- input parameter
    @L1R nchar(10) out, -- output parameter -- Label1 Return Variable
    @L2R nchar(10) out, -- Label2 Return Variable
    @L3R nchar(10) out, -- Label3 Return Variable
    @L4R nchar(10) out, -- Label4 Return Variable
    @LD1R nchar(15) out, -- LData1 Return Variable
    @LD2R nchar(15) out, -- LData2 Return Variable
    @LD3R nchar(15) out, -- LData3 Return Variable
    @LD4R nchar(15) out -- LData4 Return Variable
AS
BEGIN
    -- SP body
END

To use the parameters in your c# code you could use the example:
Add the parameter:
SqlParameter output = new SqlParameter("@L1R", SqlDbType.NVarChar);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);

Read the parameter:
string L1R = cmd.Parameters["@L1R"].Value.ToString();


text:
Q: ubuntu 13.04 and Kubuntu and windows 8 boot problem i was installing windows 8
then i installed ubuntu 13.04 and Burg for boot loader
and everything was going great
then i installed Kubuntu and it changed the boot but still works
and last thing which caused the problem,i used Easy BCD on windows 7 to change
the boot loader to the windows 8`s boot loader
but it messed up everything,
only windows 8 shows and i tried to add entries " Ubuntu and Kubuntu " but it does not work when i select on start up
 i tried many things using live cd of ubuntu and kubuntu but nothing work.
so Please help.

A: Do you really want EasyBCD. I do not know that, but some do use it. It has to compromise grub2's boot loader to work. You have to force grub2 to install into a partition's boot sector (PBR) which means it uses blocklists or hard coded addresses to find the rest of grub in the install. If any of those files are updated then the address may be wrong & you have to reinstall grub.
But you have to install Ubuntu's grub2 boot loader to the PBR of Ubuntu and Kubuntu's to the PBR of Kubuntu. (actually only one required as either grub will offer to boot everything.)
If you really want EasyBCD:
http://neosmart.net/wiki/display/EBCD/Ubuntu
Whichever install you install last is the boot loader that goes into the MBR of the hard drive and will be the one used to boot. Any other boot loader must be chain loaded to another boot loader or grub can find kernels and boot those also.
How to restore the Ubuntu/XP/Vista/7 bootloader
https://help.ubuntu.com/community/RestoreUbuntu/XP/Vista/7Bootloader
Reinstall grub2 - Short version & full chroot version
https://help.ubuntu.com/community/Grub2#Reinstalling GRUB2
I am not sure that burg has been maintained for a while, so it may not work with newer systems.


text:
Q: Execute MySql query from asp.net Why wont this command execute properly:
    using (MySqlCommand myCommand = new MySqlCommand("Update jobs SET poster_email = '@1', url = '@2' WHERE company = '@3'; ", myConn))
    {
        myCommand.Parameters.AddWithValue("@1", email);
        myCommand.Parameters.AddWithValue("@2", url);
        myCommand.Parameters.AddWithValue("@3", company);
        myConn.Open();
        myCommand.ExecuteNonQuery();
    }

But when I substitute @3 with an actual value it works:
using (MySqlCommand myCommand = new MySqlCommand("Update jobs SET poster_email = '@1', url = '@2' WHERE company = 'MyCompany'; ", myConn))
{
    myCommand.Parameters.AddWithValue("@1", email);
    myCommand.Parameters.AddWithValue("@2", url);

    myConn.Open();
    myCommand.ExecuteNonQuery();
}

The value being passed in for the company variable is identical to the value that is hardcoded in the second example. I've stepped through with the debugger to make sure the company variable is being added as a parameter and that it's the value that I'm expecting. ie. with no spaces and trim()
Any idea what I'm doing wrong?
Update:
This also works, but then I have to worry about Sql Injection...
    string myQuery = string.Format("Update jobs SET poster_email = '{0}', url = '{1}' WHERE company = '{2}'; ", email, url, company);

    using (MySqlCommand myCommand = new MySqlCommand(myQuery, myConn))
    {
        myConn.Open();
        myCommand.ExecuteNonQuery();
    }

A: I believe for MySQL commands you want to use a "?" instead of a "@" :
using (MySqlCommand myCommand = new MySqlCommand("Update jobs SET poster_email = '?1', url = '?2' WHERE company = '?3'; ", myConn))
{
    myCommand.Parameters.AddWithValue("?1", email);
    myCommand.Parameters.AddWithValue("?2", url);
    myCommand.Parameters.AddWithValue("?3", company);
    myConn.Open();
    myCommand.ExecuteNonQuery();
}

http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html#connector-net-examples-mysqlcommand-parameters


text:
Q: Soldering capacitor pins When soldering capacitors, is the order on which you solder them important?
I am about to solder a project but I don't know this information
For example, I can solder each pin however I like, or one pin is goes somewhere, the other elsewhere?
Noob question, but first time soldering capacitors.

A: It sounds like you are talking about component orientation, not literally the order of soldering the wires.  In this case, yes for some capacitors it is important which way around they go.  The negative lead is identified with a "-" or  a stripe down the side.  The positive lead may be longer.
This is a typical electrolytic capacitor, showing the stripe and the line of "-" signs that identify the negative lead.

For ceramic capacitors (usually orange discs) it doesn't matter which way around they go.

A: Nope, no power should be applied to a board you are soldering to so pin order does not matter. If they are polarized capacitors just make sure you don't solder the leads in backwards.


text:
Q: Моргают страницы в браузере У меня есть маленькое приложение на Django. Оно работает. Но на доли секунды появляется белый фон при нажатии на ссылки. В браузере Firefox такого нет а в Chromium and Opera такое проявляется но только в данном приложении. Я так понимаю что это связанно с кэшированием. Есть какое-нибудь решение чтоб это сиправить?
Здесь моё приложение.


text:
Q: Unhashable type: 'list' error when trying to add m2m relationships dynamically using post_save in Django My Content model has a many-to-many relationship to the Tag model. When I save a Content object, I want to add the relationships dynamically. Im doing this the following way.
def tag_content(obj):
    obj.tags.add([1,2,3])
    obj.is_tagged = True
    obj.save()
    return obj

class Tag(models.Model):
    name = models.CharField(max_length=255)

class Content(models.Model):
    title = models.CharField(max_length=255)
    is_tagged = models.BooleanField(default=False)
    tags = models.ManyToManyField(Tag, blank=True)

    def save(self, *args, **kwargs):
        super(Content, self).save(*args, **kwargs)

@receiver(post_save, sender = Content)
def update_m2m_relationships_on_save(sender, **kwargs):
    if not kwargs['instance'].is_tagged:
        tag_content(kwargs['instance'])

Basically, when a Content object is saved, the receiver is used to call a post_save method which in turn calls the tag_content method to add the m2m relationships. However, I get this error:
TypeError
unhashable type: 'list'

It specifically references the .add() function. Any idea why I am getting this error? Any help is appreciated. Also, do note that I have Tag objects with ids = 1, 2, and 3 in database.
EDIT
Alright, I changed my tag_content to something like this:
def tag_content(obj):
    for tag in Tag.objects.all():
        print tag
        obj.tags.add(tag)

This is because the add() method takes in object instances, not ids. However, it still doesn't work :/ I get no error, but the relationships are simply not established.
This is especially weird since the print tag command works and prints out the tags. In other words, the function is being called. Any help please? Btw, I am running Django 1.9.8.

A: You cannot pass a list to add(), which is why you get the error. You either need to add one item at a time or expand the list into a series of arguments, e.g:
obj.tags.add(*[1,2,3]) # The * expands the list into the function arguments

This will still cause an error because you cannot pass IDs to add() - you have to pass Tag objects to it. So something like this would work:
# Get a list of Tag objects
tags_to_add = [Tag.objects.get(id=j) for j in [1, 2, 3]]
# Now pass this to the add() function:
obj.tags.add(*tags_to_add)

A: According to the add docs you need actual models to be passed as args.
If you really want a list of models you need to unpack it, but you might as well pass the objs as arguments directly in this case.


text:
Q: Percentage calculation from another column sql / presto I have this table
month_year  shopid  payment_method   count
Jul-19      3lokpn99    CC           115
Jul-19      3lokpn99    PAYPALL      1
Jul-19      6jyhikmm    CC           180
Jul-19      6jyhikmm    PAYPALL      7
Aug-19      3lokpn99    CC           108
Aug-19      3lokpn99    PAYPALL      4
Aug-19      6jyhikmm    CC           114
Aug-19      6jyhikmm    PAYPALL      3

what im looking for is to calculate percentage for each payment method on that month.
desired result is like this
month_year  shopid  payment_method   count   %
Jul-19      3lokpn99    CC           115    99.14
Jul-19      3lokpn99    PAYPALL      1      0.86
Jul-19      6jyhikmm    CC           180    96.26
Jul-19      6jyhikmm    PAYPALL      7      3.74
Aug-19      3lokpn99    CC           108    96.43
Aug-19      3lokpn99    PAYPALL      4      3.57
Aug-19      6jyhikmm    CC           114    97.4
Aug-19      6jyhikmm    PAYPALL      3      2.56

A: There are different approaches possible

*

*using Window Functions

*self-JOIN with aggregation (as presented in Wojciech's answer)

Window Functions approach has additional advantage that source data is read only once.
SELECT month_year, shopid, payment_method, count,
    100e0 * count / sum(count) OVER (
        PARTITION BY month_year, shopid
        RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
        AS "%"
FROM ...

(Tested on Presto 318)
See Presto Window Function documentation
https://trino.io/docs/current/functions/window.html

A: You could achieve this result by query:
SELECT s.*, ROUND(s.count / ss.count_summed * 100,2) AS `%`
FROM stack s
JOIN (SELECT s.month_year, s.shopid, SUM(s.count) AS count_summed FROM stack s GROUP BY s.month_year, s.shopid) ss ON ss.month_year = s.month_year AND ss.shopid = s.shopid;


text:
Q: Question on positive integer solutions of $x^4-y^4=z^2$ Suppose the equation $x^4-y^4=z^2$ has solution(s) in positive integers. Then show that the least $x$ value of these solutions is odd.

Here is my attempt using contradiction
let $x=2k$ $$(2k)^4-y^4 = z^2$$
Any hint/help on how one should go about finding a contradiction ? Thanks!

A: For the least positive solution $(x,y)=1$
So both of $x,y$ can not be even
If $x$ is even and $y$ is odd
$x^4\equiv0\pmod4, y^4\equiv1\pmod4\implies x^4-y^4\equiv-1\pmod4$
But $z^2\equiv0,1\pmod4\not\equiv-1$


text:
Q: TortiseSVN - commit Item failed error I use tortise svn in VS2010.  When I go to commit my changes at the end of the day, I get the following error.
Commit item 'folder / filename' has copy flag but an invalid revision.
What does that mean and how do I resolve it?  I Googled for it but really only saw a transcript of a rather esoteric discussion for a Java-related issue.
EDIT - 10/25/2010
Nothing?  Really?

A: I agree with Pekka's comment.  Right click on the project folder -> TortoiseSVN -> Check for modifications.  Take note of the files you changed.
Create a new folder - and checkout the repository to the new folder.  Move the files that changed back into the new folder, replacing any existing ones.  Try your commit again.
You may try doing this with Windows Explorer instead of Visual Studio.

A: *

*have you renamed that folder[say, folder1]?

*If not then, "export" the content of that folder to somewhere else[say, folder2].

*go back to parent of folder1 and delete then update folder1.

*replace all the files[*not folder*s] in folder1 with the equivalent files from folder1

*now commit folder1 independently after stealing any lock if exists.

A: What happens if you try to get the latest revision (update before committing, but after you back up your code ;)?
It sounds like there is potentially something that is in conflict in a bad way - you may need to back up your files, update or check out a new working copy, and then replace checked out files with your old ones.

A: check out a clean copy. put in the changes you previously made. commit.
do that, and try to forget your problems. it should work.