text:
Q: The member with identity 'FaseProjeto_Fase_Target' does not exist in the metadata collection Estou com um erro muito estranho... não faço a minima do que seja.
Esta é minha classe:
 public class FaseProjeto
{
    public int IdProjeto { get; set; }
    public int IdFase { get; set; }
    public virtual Projeto Projeto { get; set; }
    public virtual FaseModelo Fase { get; set; }
    public DateTime DataInicio { get; set; }
    public DateTime DataFim { get; set; }
    public StatusProjetoFase Situacao { get; set; }
    public string Observacao { get; set; }

}

Esse é o mapeamento dela:
public FaseProjetoMap()
    {

        // Define nome da Tabela
        ToTable("FaseProjeto");

        // Chave primária composta
        HasKey(po => new { po.IdProjeto, po.IdFase });

        // Properties
        Property(t => t.IdProjeto)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        Property(t => t.IdFase)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

        Property(t => t.IdProjeto).HasColumnName("Projeto_Id");
        Property(t => t.IdFase).HasColumnName("Fase_Id");

        HasRequired(fp => fp.Projeto)
            .WithMany(p => p.Fases)
            .HasForeignKey(f=>f.IdProjeto);

        HasRequired(fp => fp.Fase)
            .WithMany()
        .HasForeignKey(f=>f.IdFase);

    }

Aí eu tenho essa classe que herda de fase projeto:
 public class FaseProjetoPlanejamento : FaseProjeto
{

    public virtual OrgaoPublico Orgao { get; set; }

    public virtual ObjetoLicitacao Objeto { get; set; }

    public virtual LocalizacaoObra Localizacao { get; set; }

    public virtual IEnumerable<Documento> Documentos
    {
        get
        {
            return this.Projeto.GetDocumentos();
        }
    }

    public virtual NCode.Orcamento.Model.Ent.Orcamento Orcamento
    {
        get
        {
            return this.Projeto.GetOrcamento();
        }
    }

    public override FaseModelo Fase
    {
        get { return ModeloProjetoObraSetorPublico.FasePlanejamento; }
        set { }
    }

}

Quando eu vou salvar essa classe com EF me retorna o seguinte erro:

The member with identity 'FaseProjeto_Fase_Target' does not exist in
  the metadata collection. Nome do parâmetro: identity

A: Poderia debugar e falar qual linha exatamente da o erro rs, acredito que algo está com o nome incorreto no seu mapeamento ou não está preenchendo corretamente a entidade, verifique novamente nesta parte do seu código:
    HasRequired(fp => fp.Projeto)
        .WithMany(p => p.Fases)
        .HasForeignKey(f=>f.IdProjeto);

    HasRequired(fp => fp.Fase)
        .WithMany()
    .HasForeignKey(f=>f.IdFase);


text:
Q: Limitar data fim de acordo com data inicial no bootstrap-datepicker Gostaria de saber como faço para limitar a data final do formulário utilizando datepicker, preciso que quando seja selecionado no calendário a data inicial, a final automaticamente limite para até 90 dias. Já pesquisei e não encontrei nada do tipo. Segue abaixo os meus campos html:

        <input type="date" class="form-control inputIni">

        <input type="date" class="form-control inputFim">

Os calendários funcionam corretamente, o formato tem que ser dd/mm/yyyy.

A:
$('inputIni').datetimepicker({
  locale: 'pt-br',
  format: 'DD/MM/YYYY'
});

$('.inputFim').datetimepicker({
  locale: 'pt-br',
  format: 'DD/MM/YYYY',
  useCurrent: false
});

$(".inputIni").on("dp.change", function (e) {
   $('.inputFim').data("DateTimePicker").maxDate(e.date.add(90,'days'));
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to only log queries without executing for Postgres Server? Is there any way I can make postgres server only log incoming statements without  executing them ?

A: No, any semi-sane program would go crazy after a couple of queries that return no sensible data and have no impact on future queries.
What is the problem you're trying to solve this way?


text: Q: TexStudio paragraphs and hard returns Following a hard return, TexStudio sometimes gives me (A) a new line on which I can write and edit a full paragraph (e.g., lines 316 and 318 in the accompanying image), and sometimes given me (B) a series of lines that ought to register as a single line/paragraph (e.g., lines 301--310 in the accompanying image). Oddly, TexStudio treat lines 301--310 as a single line/paragraph when I first type it, but converts it to ten numbered lines after I save the file. This happens throughout my documents, with what should be single lines turning into multiple lines after saving. Any idea what's up?


text:
Q: combine rows and expand different columns in r I have a dataframe:
df1<-data.frame(ID=c(1,2,2,3,3,3,4),
                V1=c(1,2,3,4,5,6,7),
                V2=c(8,9,10,11,12,13,14),
                V3=c(15,16,17,18,19,20,21))
> df1
  ID V1 V2 V3
1  1  1  8 15
2  2  2  9 16
3  2  3 10 17
4  3  4 11 18
5  3  5 12 19
6  3  6 13 20
7  4  7 14 21

I would like to combine rows when the rows have the same ID, but expand new columns because the rows with same ID have differnet values in each of the variable. I would like the final table to be like:
> df1
  ID V1.1 V1.2 V1.3 V2.1 V2.2 V2.3 V3.1 V3.2 V3.3
1  1    1   NA   NA    8   NA   NA   15   NA   NA
2  2    2    3   NA    9   10   NA   16   17   NA
3  3    4    5    6   11   12   13   18   19   20
4  4    7   NA   NA   14   NA   NA   21   NA   NA

Is there any way to do that in r?

A: We can use pivot_wider
library(dplyr)
library(tidyr)
library(data.table)
df1 %>%
   mutate(nm1 = rowid(ID)) %>%
   pivot_wider(names_from = nm1, values_from = c(V1, V2, V3), names_sep=".")

-output
# A tibble: 4 x 10
#     ID  V1.1  V1.2  V1.3  V2.1  V2.2  V2.3  V3.1  V3.2  V3.3
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1     1     1    NA    NA     8    NA    NA    15    NA    NA
#2     2     2     3    NA     9    10    NA    16    17    NA
#3     3     4     5     6    11    12    13    18    19    20
#4     4     7    NA    NA    14    NA    NA    21    NA    NA


text:
Q: How would you store CSV data in some sort of data structure without a concrete : number of columns, column types, etc in C++ Alright so basically I need to read data from a CSV file and store it in some sort of data structure. The CSV data would kind of look like this:
year,position,MVP,entity
INT,STRING,BOOL,STRING
2020,FORWARD,TRUE,Lionel Messi
2020,MIDFIELDER,FALSE,Jordan Henderson
2020,GOALKEEPER,FALSE,David De Gea
2020,DEFENDER,FALSE,Virgil van Dijk

The first two rows would tell you the name of the attributes, and their types.
I know how to read data from a CSV file, but the problem is that I don't really know what is the best data structure to store said data when the number of columns, attribute types (bool, int, etc), can vary.
Originally I thought a table represented by a vector of Row objects would work, but that only works when I know exactly how many attributes there are, what their types are, what their names are, and etc.
I'm thinking I can somehow store it based off the metadata of the data, like # of attributes, attribute types, location of row, etc, but I don't really know how to expand on this idea yet.
Any help would be appreciated!
edit:
so basically my program has to work with CSV files that are similar to the structure that I posted above, but each CSV file could have a different number of columns, different attribute types, and etc.
One csv file can look like the example above, and another can look like this:
startYear,job,entity
INT,STRING,STRING
2001,SALES ASSOCIATE,Jackie Cruz
1992,GENERAL MANAGER,Jorge Almandra
2004,CUSTODIAN,Jeffrey Howie
2018,ELECTRICIAN,Katie Moody

I still need to be able to store the data into some sort of data structure even though the number of columns and their types differ.

A: Here is one possible solution
And I hate it.  I would never do something like that. Becuase the design idea or the rquirement is already nonesense.
Either, we use types and we know the which column has what type, or we simply use a fits-to-all-type for the required context. In this case, simply a std::string.
But doing this dynamically will result in really ugly and not maintanable code.
The solution here is std::any. But maybe a class hierachie would be even better. I will try later.
Please see this ugly code:
#include <iostream>
#include <sstream>
#include <vector>
#include <regex>
#include <string>
#include <iterator>
#include <algorithm>
#include <utility>
#include <any>
#include <map>
#include <tuple>

// the delimiter for the csv
const std::regex re(",");

// One DataRow from the csv file
struct DataRow {
    std::vector<std::string> columns{};

    friend std::istream& operator >> (std::istream& is, DataRow& dr) {

        // Read one complete line
        if (std::string line{}; std::getline(is, line)) {

            // Split the string, containing the complete line into parts
            dr.columns.clear();
            std::copy(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {}, std::back_inserter(dr.columns));
        }
        return is;
    }
};

struct CSV {

protected:
    // Conversion functions
    std::any stringToAnySTRING(const std::string& s) { return s; }
    std::any stringToAnyBOOL(const std::string& s) { bool result{ false }; if (s == "TRUE") result = true; return result; }
    std::any stringToAnyINT(const std::string& s) { int result = std::stoi(s); return result; }
    std::any stringToAnyLONG(const std::string& s) { long result = std::stol(s); return result; }

    // Making Reading easier
    using ConvertToAny = std::any(CSV::*)(const std::string&);

    // Map conversion functions to type strings
    std::map<std::string, ConvertToAny> converter{
        {"STRING", &CSV::stringToAnySTRING},
        {"BOOL", &CSV::stringToAnyBOOL},
        {"INT", &CSV::stringToAnyINT},
        {"LONG", &CSV::stringToAnyLONG}
    };

public:
    // Header, Types and data as std::any
    std::vector<std::string> header{};
    std::vector<std::string> types{};
    std::vector<std::vector<std::any>> data{};

    // Extractor operator
    friend std::istream& operator >> (std::istream& is, CSV& c) {
        // Read header line
        if (std::string line{}; std::getline(is, line)) {

            // Split header line into sub strings
            c.header.clear();
            std::copy(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {}, std::back_inserter(c.header));

            // Read types line
            if (std::getline(is, line)) {

                // Spit types into sub strings
                c.types.clear();
                std::copy(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {}, std::back_inserter(c.types));

                // Read all data, so all lines, split them and convert them to the desired data type
                c.data.clear();

                // This will read all lines and split them into columns
                std::vector<DataRow> drs(std::istream_iterator<DataRow>(is), {});

                // Make at least one plausibility check, that all rows have the same number of columns
                size_t minDataLength = std::min_element(drs.begin(), drs.end(), [](const DataRow& dr1, const DataRow& dr2)
                    {return dr1.columns.size() < dr2.columns.size(); })->columns.size();
                if (c.header.size() == c.types.size() && c.types.size() == minDataLength) {

                    // Now convert all columns into the type denoted by the read type array and store them as any data
                    // Double transform because of 2 dimensional array
                    std::transform(drs.begin(), drs.end(), std::back_inserter(c.data), [&c](const DataRow& dr) {

                        std::vector<std::any> va{};
                        // This is the conversion into a type defined by the types array
                        // Anybody who understands this transfrom will get the Nobel price for Obfuscation
                        std::transform(dr.columns.begin(), dr.columns.end(), std::back_inserter(va),
                            [&c, i = 0U](const std::string& s) mutable {return (c.*(c.converter[c.types[i++]]))(s); });
                        return va; });
                }
            }
        }
        return is;
    }

    // Inserter operator
    friend std::ostream& operator << (std::ostream& os, const CSV& c) {

        // Write header
        os << "Header: ";
        std::copy(c.header.begin(), c.header.end(), std::ostream_iterator<std::string>(os, "  "));

        // And the type names
        os << "\nTypes:  ";
        std::copy(c.types.begin(), c.types.end(), std::ostream_iterator<std::string>(os, "  "));
        os << "\n\nData:\n";

        // And the types. Arrgh. How ugly
        std::for_each(c.data.begin(), c.data.end(), [&c,&os](const std::vector<std::any>& va) {
            for (size_t i = 0U; i < va.size(); ++i) {
                if (c.types[i] == "INT") { int v = std::any_cast<int>(va[i]); os << v << " "; }
                else if (c.types[i] == "LONG") { long v = std::any_cast<long>(va[i]); os << v << " "; }
                else if (c.types[i] == "STRING") { std::string v = std::any_cast<std::string>(va[i]); os << v << " "; }
                else if (c.types[i] == "BOOL") { bool v = std::any_cast<bool>(va[i]); os << v << " "; }
            }
            os << "\n";
        });
        return os;
    }
};

// The data. Does not matter if file or stringstream. Is the same
std::istringstream csvFile{ R"(year,category,winner,entity
INT,STRING,BOOL,STRING
2015,CHEF OF THE YEAR,FALSE,John Doe
2015,CHEF OF THE YEAR,FALSE,Bob Brown
2015,CHEF OF THE YEAR,TRUE,William Thorton
2015,CHEF OF THE YEAR,FALSE,Jacob Smith)" };

int main() {

    // Define varaiable of type csv
    CSV csv{};

    // Read from somewhere
    csvFile >> csv;

    // Show some debug output
    std::cout << csv;

    return 0;
}


text:
Q: Stop table going off page I'm aware that my table is too wide as it keeps going off the page on the right.
Is there a way to fix this?
I'm using lyx as I am a learner.

A: You can fix the width of the table to fit the width of your general text.
To fix the width of the table in LyX 2.0, right-click in a cell in the column, move to More... and choose Settings.... In the Table Settings tab, you can set the value near the bottom, under Table-wide settings.
This, however, will set the width of your table, but not the content of the table. If, e.g., you have a cell with a lot of text that extends beyond the margin, then also pick a width for that (those) column(s) under Column settings in the same tab. This will also allow line breaks in the text.

A: \noindent\resizebox{\textwidth}{!}{%
... your tabular ...
}

In LyX insert the two lines in ERT (Evil Red Text) mode (Ctrl-L) just before and after your tabular. In the documents preamble add \usepackage{graphicx} if not already present.
This is how you add a new package: Use custom latex package in LyX


text:
Q: How do I change the hard-coded database password of a Delphi program that I can't recompile? I have a Delphi application that I cannot recompile.
In the process of moving the database to a new SQL Server version, I want to change the database password so it's no longer blank. The problem is that the application has the database credentials embedded in the .exe.
Is there any way that I can change the password?
Server name and database name are configurable.

A: Below is a screenshot of part of a D7 .Exe of mine showing the relevant part of its Ado ConnectionString.
I used an antique file viewer (from the example apps accompanying an old TurboPower library) to take the screenshot.  I just loaded the file into it, entered "persist" as the search string and skipped a couple of TPersistent instances to locate it.
Of course, you could use any old hex file-editor to do similar and change it, provided the .Exe isn't compressed or protected against tampering by checksums, etc.
You'll probably need to experiment a bit, & compare with another app which has a non-blank password so that you can come up with some new credentials that'll fit into the space available in the .Exe's disk image.

A: If the connection string was saved in the TADOConnection component in design mode, Your best choice is to use Resource editor such as Resource Hacker.
The forms or data modules DFM are found in the RCData section. just change the connection string and use "Compile script".
This will save your changes back to the EXE file without the worry of corrupting the EXE.
I assume your EXE is not packed (PE packer) or digitally signed.


text:
Q: How to dispatch value onChange I'm building a search component and I've set up my actions and reducers and so on... but I can't figure out how to dispatch an event in my component. What should be inside the onChangeValue attribute?
Here's the code:
import React from "react";
import { connect } from "react-redux";
import { getListOfUsers, clearDetails } from "../../actions/actions";
import SearchBar from "../../components/search/search";

const SearchBarContainer = onChangeValue => {
  return <SearchBar onChangeValue={onChangeValue} id="search" icon="search" />;
};

const mapStateToProps = state => {
  return {};
};

const mapDispatchToProps = dispatch => {
  return {
    onChangeValue: e => {
      dispatch(getListOfUsers(e.target.value));
      dispatch(clearDetails());
    }
  };
};

const connected = connect(
  mapStateToProps,
  mapDispatchToProps
)(SearchBarContainer);

export default connected;

A: SearchBarContainer is a functional component and hence it won't have state or this variable. You need to get them from the props. Also dispatch function onChangeValue is available as a prop to the container.
const SearchBarContainer = ({ onChangeValue, value }) => {
  return (
    <SearchBar
      onChangeValue={onChangeValue}
      value={value}
      id="search"
      icon="search"
    />
  );
};

A: change
<SearchBar
      onChangeValue={onChangeValue}
      value={this.state.value}
      id="search"
      icon="search"
    />

to
<SearchBar
          onChangeValue={this.props.onChangeValue}
          value={this.state.value}
          id="search"
          icon="search"
        />


text:
Q: Android parse sdk push notification Android parse sdk push notification is working on the emulator but when i run it on the phone using usb debugging, the push notification is triggered in the back-end and can be seen in my parse.com account but the phone doesn't receive the push notification.
public class Profile_InviteActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile__invite);

        Bundle extras = getIntent().getExtras();
        ParseQuery<ParseObject> query = ParseQuery.getQuery("UserProfile");
        Log.d("id",""+extras.getInt("fid"));

        query.whereEqualTo("fid", ""+extras.getInt("fid"));
        query.findInBackground(new FindCallback<ParseObject>() {
            public void done(final List<ParseObject> scoreList, ParseException e) {
                if (e == null) {

                    TextView name = (TextView) findViewById(R.id.profile_name);
                    TextView location = (TextView) findViewById(R.id.profile_location);

                    name.setText(scoreList.get(0).getString("name"));
                    location.setText(scoreList.get(0).getString("location"));

                    ParseFile img1 = (ParseFile)scoreList.get(0).get("profileimage");

                   img1.getDataInBackground(new GetDataCallback() {

                        public void done(byte[] data,
                                ParseException e) {
                            if (e == null) {
                                Log.d("test",
                                        "We've got data in data.");
                                // Decode the Byte[] into
                                // Bitmap
                                ImageView image = (ImageView) findViewById(R.id.profimg);

                                image.setImageBitmap(BitmapFactory
                                        .decodeByteArray(
                                                data, 0,
                                                data.length));
                            } else {
                                Log.d("test",
                                        "There was a problem downloading the data.");
                            }
                        }
                    });

                } else {
                    Log.d("score", "Error: " + e.getMessage());
                }
            }
        });

    }

    public void inviteToTrain(View v)
    {
        Log.d("inviting","now");

        Bundle extras = getIntent().getExtras();

        //ParseInstallation installation = ParseInstallation.getCurrentInstallation();

        //installation.put("fids",true);
        //installation.saveInBackground();

        ParseQuery pushQuery = ParseInstallation.getQuery();
        //pushQuery.whereEqualTo("fid", extras.getInt("fid"));
        pushQuery.whereEqualTo("fids", true);
        // Send push notification to query
        ParsePush push = new ParsePush();
        push.setQuery(pushQuery); // Set our Installation query
        push.setMessage("Someone would like to join you at your event ");
        push.sendInBackground();
        Log.d("invited","now");
    }

}
Kindly help me with this.
Thanks

A: In order to get push notifications,
You have to write broadcast receivers to handle that.
sample code :
After initializing Parse details,Add this
PushService.setDefaultPushCallback(this, SampleClass.class);

Then in ur Manifest file ,add this
<receiver android:name="com.parse.ParseBroadcastReceiver" >
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.USER_PRESENT" />
    </intent-filter>
</receiver>

Then Go to parse dashboard, and send push manually inorder to check whether push is getting into ur phone. Use Json format like this,
{ "alert": "Notification", "title": "Push", "objectId": "objectId",
 "objectType": "type", "action": "Your Action Name" }

More Details ,Refer
How to trigger an event using Parse for Android via push notification?


text:
Q: How to deal with long lines of code and commands in Python I've tried searching, but I couldn't find any situations similar to mine. I am writing a program and so far I've stuck to the no more than 79 characters in a line rule. However I'm not sure where to break lines in a few situations.
Here are the problem areas:
        self.proc.stdin.write('(SayText "%s")\n' % text.replace('\\', '\\\\').replace('"', '\\"'))

For this situation when I break first line after the '(SayText "%s")\n', the second line ends up being 80 characters long. Should I then break the second line somewhere in the brackets like this?
        self.proc.stdin.write('(SayText "%s")\n'
                              % text.replace('\\',
                                             '\\\\').replace('"', '\\"'))

Or would it be better to bring the entire third line to the beginning of the first brackets like this:
        self.proc.stdin.write('(SayText "%s")\n'
                              % text.replace('\\',
                              '\\\\').replace('"', '\\"'))

Another example of this is here:
        filename = tkFileDialog.askopenfilename(filetypes = (("Word list", "*.tldr"), ("All files", "*.*")))

Should I do this?
        filename = tkFileDialog.askopenfilename(filetypes = (("Word list",
                                                              "*.tldr"),
                                                             ("All files",
                                                              "*.*")))

Or this?
        filename = tkFileDialog.askopenfilename(filetypes = (("Word list",
                                                "*.tldr"),("All files", "*.*")))

What would be a good convention to follow?
Thanks.

A: In my opinion, one of the reasons to prefer shorter lines is that it makes the programmer more likely to break up code into individual shorter lines which are easier to understand and to spot errors or better ways to do things in.
from __future__ import print_function

FMT_SAY_TEXT = '(SayText "%s")'

text_escaped = text.replace('\\', r'\\')
text_escaped = text_escaped.replace('"', r'\"')
text_out = FMT_SAY_TEXT % text_escaped
print(text_out, file=self.proc.stdin)

For your second example:
FILE_DIALOG_FILETYPES = (("Word list", "*.tldr"), ("All files", "*.*"))

filename = tkFileDialog.askopenfilename(filetypes = FILE_DIALOG_FILETYPES)

A: As a general rule, I try to break at the first point in the "dominant" syntactic connective, and use a single indent for the continuation line for a normal statement, or a double indent if the broken line is followed by a colon. However, if the syntactic connective is "." then I prefer to use temporary variables, as this is usually more clear.
For your examples:
self.proc.stdin.write('(SayText "%s")\n' % text.replace('\\', '\\\\').replace('"', '\\"'))

I would write:
self.proc.stdin.write(
    '(SayText "%s")\n' % text.replace('\\', '\\\\').replace('"', '\\"'))

For
filename = tkFileDialog.askopenfilename(filetypes = (("Word list", "*.tldr"), ("All files", "*.*")))

I would write:
filename = tkFileDialog.askopenfilename(
    filetypes = (("Word list", "*.tldr"), ("All files", "*.*")))

For function calls with many arguments, I sometimes find it most clear to put one on a line, even
if more could fit. E.g.
filename = some_function_call_with_long_args( the_first_argument = some_rather_long_expression, another_argument = some_other_expression )

Would become:
filename = some_function_call_with_long_args(
    the_first_argument = some_rather_long_expression,
    another_argument = some_other_expression )

or even:
filename = some_function_call_with_long_args(
    the_first_argument = some_rather_long_expression,
    another_argument = some_other_expression
    )

The variation on this for ":" terminated statements is illustrated:
for foo in this_is_a_long_function_generating_an_iterable( here_are_some = arguments, and_they = are_long_too ):
    print foo

becomes:
for foo in this_is_a_long_function_generating_an_iterable(
        here_are_some = arguments, and_they = are_long_too
        ):
    print foo

but usually clearer would be
foo_iter = this_is_a_long_function_generating_an_iterable(
    here_are_some = arguments, and_they = are_long_too )
for foo in foo_iter:
    print foo

or
foo_iter = this_is_a_long_function_generating_an_iterable(
    here_are_some = arguments, and_they = are_long_too
    )
for foo in foo_iter:
    print foo

A final note: some people consider these rules obsolete, as you can usually use a larger window. I find these rules quite useful, still, because:

*

*with consistently short lines I can see code in more open windows (or more editing panes)

*the method above exhibits the logical structure of the program

*when it isn't easy to break lines, it is often a sign that the structure
would be better exhibited with temporary variables (etc.)

A: Whatever works for you or the conventions of the code base you are working on.  PEP 8, the style guide for code included in the Python standard library, suggests that the most important consideration for continuation lines is to ensure that they are easily distinguished from indented lines (those starting a new block).
Continuation lines should align wrapped elements either vertically using
Python's implicit line joining inside parentheses, brackets and braces, or
using a hanging indent.  When using a hanging indent the following
considerations should be applied; there should be no arguments on the
first line and further indentation should be used to clearly distinguish
itself as a continuation line.

See the examples given there.

A: A convention I sometimes follow when the usual indentation style leads to too much horror, is the following:
filename = tkFileDialog.askopenfilename(
    filetypes = (("Word list", "*.tldr"),("All files", "*.*"))
)

It looks very weird at first. But it clearly lays out the "head" of the multi-line structure separately on the first line where it is prominent, and clearly shows where the multi-line structure stops. Only indenting one level, instead of to the level of the opening brace, gives you a lot more room to write the nested lines. And it has the happy side effect of causing diffs to clearly show when you only change the arguments of such a call, which is occasionally helpful.
In some ways I think this formatting convention is actually a better fit for modern high level OO languages than the usual styles, which tend to date back to C; C doesn't have chained calls and tended to have much shorter callable names due to not having objects. But since no one else uses this style I save it as a fallback for when the normal style makes readability worse.

A: The best place to look for general Python code formatting guidelines is pep8. There are "rules" there for how/when to break up longer lines of code.
For your particular examples however, I usually assign the arguments to variables in a previous line:
msg = '(Say Text "%s")\n' % text.replace('\\', '\\\\').replace('"', '\\"')
self.proc.stdin.write(msg)

files_types = (("Word list", "*.tldr"), ("All files", "*.*"))
filename = tkFileDialog.askopenfilename(filetypes=file_types)

A: I don't think many people still use a VT100, so you can safely bump it up to 100/120 characters.
For something like your first example, it much easier to read when you break apart the 4  operations into 2 lines of 2:
myStr = '(SayText "%s")\n' % text.replace('\\', '\\\\')
self.proc.stdin.write(myStr.replace('"', '\\"'))

Example 2:
ftypes = (("Word list", "*.tldr"), ("All files", "*.*"))
filename = tkFileDialog.askopenfilename(filetypes = ftypes)

A: It's your preference.
When I code, I prefer to break it by argument, if I have to. Of course, you can do something differently. It's all what you think.


text:
Q: GUI Dropdown Full Width According to Screen Resolution I have been trying to build GUI programatically according to JSON Object and stacking each dropdown on top of each other. This is what I am trying to achieve.
And this is the my current code.
btnRect = newDropdown.GetComponent<RectTransform> ();
btnRect.sizeDelta = new Vector2(Screen.width, 54);

But what really happen is, the my dropdown width is larger than the canvas width. What I can do to fix it?
Edited
My Current View


text:
Q: How to save common \addplot options in a variable. [Software Engineering] In the following figure, the are three points each of them has common options \addplot like fill=blue, mark=*, thick, only marks, mark size=4pt, point meta=explicit symbolic, and have some options that distinguish each point like color=blue. When I try to edit some common options I have to repeat the edit for every point because of the code duplication.
Is there a way which enables me to store the common options in a variable so that the  duplication is eliminated.
Something like that \addplot [unique1=value1, \commonFeaturesVariable] { ...
I found that I can make a global default settings but I don't want that because it will corrupt the figures in the same document that depend on the original default options.

\documentclass{IEEEtran}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
    axis x line = bottom,
    axis y line = left,
    scaled y ticks = false,
    enlarge x limits=0.1,
    nodes near coords,
]
    \addplot[color=blue, fill=blue, mark=*, thick, only marks, mark size=4pt, point meta=explicit symbolic]
        coordinates {
        (1, 4)
        };

    \addplot[color=red, fill=red, mark=*, thick, only marks, mark size=4pt, point meta=explicit symbolic]
        coordinates {
            (2, 9)
            };

    \addplot[color=brown, fill=brown, mark=*, thick, only marks, mark size=4pt, point meta=explicit symbolic]
        coordinates {
            (3, 7)
            };
\end{axis}
\end{tikzpicture}
\end{document}

A: When you use PGF/TikZ/pgfplots you have already loaded the pgfkeys package. You can use it to define a style:
\documentclass{IEEEtran}
\usepackage{tikz}
\usepackage{pgfplots}

\pgfplotsset{%
  myaddplot/.style = {%
    mark=*,
    only marks,
    mark size=4pt,
    point meta=explicit symbolic,
  }
}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
    axis x line = bottom,
    axis y line = left,
    scaled y ticks = false,
    enlarge x limits=0.1,
    nodes near coords,
]
    \addplot[color=blue, fill=blue, myaddplot]
        coordinates {
        (1, 4)
        };

    \addplot[color=red, fill=red, myaddplot]
        coordinates {
            (2, 9)
            };

    \addplot[color=brown, fill=brown, myaddplot]
        coordinates {
            (3, 7)
            };
\end{axis}
\end{tikzpicture}
\end{document}

The above will define a global style myaddplot which can be used after it was defined.
As Mr. marmot said in the comments, you can omit fill=<color> here if you will always want the draw and fill color the same because you specify the mark = *. Also, if you will use the same fill and color, then thick will also have no effect because you are plotting only marks.
If you want different colors, though, you can make your style take arguments:
\pgfplotsset{%
  myaddplot/.style args = {#1/#2}{%
    mark=*,
    only marks,
    mark size=4pt,
    point meta=explicit symbolic,
    color=#1,
    fill=#2,
  }
}

then use as:
\addplot[myaddplot=blue/blue]
    coordinates {
    (1, 4)
    };


text:
Q: Checkbox text not being retrieved I have a ListView with some CheckBoxes.  When I click on each row of the ListView I want to save the CheckBox's text in a String.
I set the ListView row to not focusable so that the user can click on the CheckBox itself.  The CheckBox cannot be checked or unchecked by the user himself, but instead, when the user clicks on it, he is lead to another activity where he needs to input data.  I am checking whether the user is inputing data or not by returning a boolean value.
If the value is true, I need to set the checkbox to checked.  In order to do so I need to compare the text of the CheckBox to another String value before actually checking it.
In other words the checked state of each CheckBox is determined by whether or not the user entered data in the previous activity.
What I cannot do is get the CheckBox text from the clicked/ touched/ selected CheckBox
Why are the below code snippets not working? clickedError is empty after running this code.
@Override
    public void onClick(final View v)
    {
        CheckBox cb = (CheckBox) v.findViewById(R.id.chkSelected);
        clickedError = cb.getText().toString() ;

AND
@Override
public void onClick(final View v)
{
    CheckBox cb = (CheckBox) v;
    clickedError = cb.getText().toString() ;
}

Have already been tried
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
        ......
        holder.chk.setOnClickListener(new MyClickListener(holder.chk));
        ......
}

private class MyClickListener implements OnClickListener
{
    CheckBox checkbox = null;

    public MyClickListener(CheckBox cb)
    {
        checkbox = cb;
    }
    @Override
    public void onClick(final View v)
    {
//          CheckBox cb = new CheckBox(mContext);
//          cb = (CheckBox) v;
//          clickedError = cb.getText().toString() ;

        CheckBox cb = (CheckBox) v.findViewById(R.id.chkSelected);
        clickedError = cb.getText().toString() ;

Thanks.

A: Use
ListView.onListItemClick(ListView parent, View row, int position, long id);

to get the reference for CheckBox in the list.

A: @Override
    public void onClick(final View v)
    {
        CheckBox cb = (CheckBox) v;
        clickedError = cb.getText().toString() ;
    }

try this.
Edit :
in your new code what are you trying to do with this
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
        ......
        holder.chk.setOnClickListener(new MyClickListener(holder.chk));
        ......
}

cant you do it like this for eg:
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
        ......
        holder.chk.setOnClickListener(new OnClickListener(){
         public void onClick(View v){
            CheckBox cb = (CheckBox) v;
            clickedError = cb.getText().toString() ;
         }
        });
        ......
}


text:
Q: Hibernate java.lang.ClassCastException: org.hibernate.action.EntityIdentityInsertAction cannot be cast to org.hibernate.action.EntityInsertAction I'm using Hibernate with an EntityManager. When I use
    Session session = (Session)entityManager.getDelegate();
    session.flush();
    session.clear();

I get
java.lang.ClassCastException: org.hibernate.action.EntityIdentityInsertAction cannot be cast to org.hibernate.action.EntityInsertAction
at org.hibernate.engine.ActionQueue$InsertActionSorter.sort(ActionQueue.java:636)
at org.hibernate.engine.ActionQueue.sortInsertActions(ActionQueue.java:369)
at org.hibernate.engine.ActionQueue.sortActions(ActionQueue.java:355)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:224)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)

Since it doesn't say which entity causes the problem, I'm stuck here. Does anyone have an idea what can cause this?

A: It's a bug in Hibernate. Exception is thrown when following conditions are met:

*

*id generation strategy is identity

*entity is saved outside of transaction

*hibernate.order_inserts is true
It happens because EntityIdentityInsertAction can be added to the ActionQueue.insertions list, whereas ActionQueue$InsertActionSorter expects that it contains only EntityInsertActions.
It looks like this bug was not reported yet, so feel free to report it.
Perhaps you can change the value of hibernate.order_inserts as a workaround.

A: I got this error just because I forget to add @Transactional annotation on the method that calls em.persist(myNewEntity) as I thought all the callers will be on Transaction,
the error is not popping directly but when I tried to delete all rows from a table
really the error is misleading but its the same as the second case in @axtavt answer
so

make sure that save operation is done within an active transaction


text:
Q: Sequence based on month number instead of month name alphabet How to sort the value based on month number instead of month name?
Create a bar chart which require to show the previous month's full data plus current month's month-to-date data. However, when select the Feb and 04/02/2022, the bar chart should display the Jan's full set data plus the Feb's month-to-date data (04/02/2022) instead of only Feb data.
The reason is due to the system is sort based on the month name instead of month number.

Code:
month_labels = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug',9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'}

df['month'] = pd.to_datetime(df['Date'], format = '%d/%m/%Y', errors='coerce').dt.month

x= df['month'].apply(lambda x: month_labels[x])

month_cat = list(x.unique())

app.layout = dbc.Container([

dbc.Row([
    dbc.Col([
        html.H3('Month'),
        html.Br(),

        dcc.Dropdown(id='month_dd', value= x.max(),
                      options = [{'label':x, 'value':x}
                                for x in month_cat],

                      ),

        html.Br(),

        html.H3('Date'),
        html.Br(),

         dcc.Dropdown(id='date_dd', value='',)

            ])
        ]),

dbc.Row([
    dbc.Col([
        html.P("Bar Chart:",
                style={"textDecoration":"underline"}),

        dcc.Graph(id='bar-fig', figure={})

            ])
        ])

@app.callback(
    Output('date_dd','options'),
    Input('month_dd', 'value')
    )

def update_dd (month_dd):

    month_date= df.drop_duplicates(['Date'], inplace= False)

    relevant_date= month_date[month_date['Month']== month_dd]['Date'].values.tolist()
    date_option= [dict(label=x,value=x)for x in relevant_date]

    return date_option

@app.callback(
    Output('date_dd','value'),
    Input('date_dd', 'options')
    )

    def default_value(latest_date):
       value = latest_date[-1]['value']

       return value

@app.callback(
    Output('bar-fig', 'figure'),
    Input('date_dd', 'value'),
    Input('month_dd', 'value')

    )

def update_graph(dd_selection,mth_selection):
    if len (dd_selection) and len (mth_selection) ==0:
        return dash.no_update

else:
    dff1= df[df['Date'] == dd_selection]
    dff= df[df['Month'] == mth_selection]

    bar_groupby1 = df[df['Month'] < mth_selection ].groupby(['Date','Month'])['MTD'].agg(['sum']).reset_index().rename(columns={'sum':'Total_Tx_Amount'})

    bar_groupby2 = dff1.groupby(['Date','Month'])['MTD'].agg(['sum']).reset_index().rename(columns={'sum':'Total_Tx_Amount'})

    combine = pd.concat([bar_groupby1,bar_groupby2])

    fig = px.bar(combine, x='Month', y='Total_Tx_Amount', title='Bar_chart', color='Month')

    return fig

Input data from .csv:
Date    Month   Minor   Major   MTD
01/01/2022  Jan     Clutlery    Kitchen     100
01/01/2022  Jan     Tops    Clothes     200
08/01/2022  Jan     Shoes   Clothes     300
01/02/2022  Feb     Turf    Garden  1000
02/02/2022  Feb     Hoses   Garden  500
03/02/2022  Feb     Clutlery    Kitchen     2000
04/02/2022  Feb     Tops    Clothes     200
01/03/2022  Mar     Clutlery    Kitchen     1300
01/03/2022  Mar     Tops    Clothes     500
02/03/2022  Mar     Shoes   Clothes     400
02/04/2022  Apr     Turf    Garden  2
02/04/2022  Apr     Hoses   Garden  4
12/05/2022  May     Rakes   Garden  6
20/05/2022  May     Cooking     Kitchen     8
25/05/2022  May     Clutlery    Kitchen     200
Expected output:
 When select Feband 04/02/2022, expect it will display Jan chart for whole month and Febchart for data until 04/02/2022.


text:
Q: Сложность в работе запроса mysql Обработчик принимает textarea и сохраняет её содержимое в базу данных.
Вот фрагмет формы:
<textarea name="massage" id="teamMember" cols="30" rows="10">
    Игрок 1:
    ФИО: ФИО
    Позывной:
    ----
    Игрок 2:
    ФИО: ФИО
    Позывной:
</textarea>

А обработчик этого кода вот (остальные данные тоже заполнены):
$teamMember = htmlspecialchars($_POST['teamMember']);
$q = $mysqli->query("INSERT INTO tournament_team (`name`,`capitanName`, `capitanNick`, `capitanPhone`, `member`)
        VALUES ($teamName, $capitanName, $capitanNick,$capitanPhone, ,$teamMember)");

И после запроса MySQL выдает такую ошибку:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'Игрок 1: ФИО: Иванов Петр Васильевичadgasdgasdg По' at line 2

Не могу понять, в чем сложность данного фрагмента кода?

A: У вас вклинилась лишняя запятая перед $teamMember. Попробуйте ее убрать и выполнить запрос еще раз.

A: $q = $mysqli->prepare("INSERT INTO tournament_team (name,capitanName,capitanNick,capitanPhone,member)
        VALUES (:teamName, :capitanName, :capitanNick,:capitanPhone, ,:teamMember)");
$q->bindParam(':teamName',$_POST['teamName']);
$q->bindParam(':capitanName',$_POST['capitanName']);
$q->bindParam(':capitanNick',$_POST['capitanNick']);
$q->bindParam(':capitanPhone',$_POST['capitanPhone']);
$q->bindParam(':teamMember',$_POST['teamMembar']);
$q->execute();


text:
Q: Auth0 and AWS Policy My web app is using Auth0 and AWS(Delegation token) to access to some resources in S3.
I have the following directory structure in a bucket named testinfo
-Directory1
    - Subdirectory11
    - Subdirectory11
-Directory2
    - Subdirectory21
-Directory3
I have the following Policy for S3 Buckets.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1423804993000",
      "Effect": "Allow",
      "Action": [
        "s3:"
      ],
      "Resource": [
        "arn:aws:s3:::testinfo/Directory1",
        "arn:aws:s3:::testinfo/Directory1/"
      ]
    }
  ]
}
And I have the following javascript code to show the contents of the bucket
var getTokenPromise = auth.getToken({api: 'aws', role: "xyz", principal: "xyz"});
getTokenPromise.then(function (value) {
    console.log('delegation: ' + value);
    bucket = new AWS.S3({params: {Bucket: 'testinfo'}});
    bucket.config.credentials =new AWS.Credentials('x','y','z');
    bucket.listObjects({}, function (err, data) {
        if (err)
            alert(err);
        var files = [];
        for (var i in data.Contents) {
            //show files
        }
    });
}, function (reason) {
    console.log('failed: ' + reason);

});
According to the policy, only the contents of Directory1 show be shown. Unfortunately I got an Access Denied Exception.
May someone give a hand to solve this problem?
Cheers

A: Could you try adding a wildcard to the directory, like this:
"arn:aws:s3:::testinfo/Directory1/*"


text:
Q: Checking an XElement for Existence of One of Several Possible XElements Is there a way to determine if an XElement contains one of any specified elements? For example, I have XElements that I'll want to check:
Dim xe1 = <color><blue/></color>
Dim xe2 = <color><red/></color>
Dim xe3 = <color><powderBlue/></color>
Dim xe4 = <color><aqua/></color>
Dim xe5 = <color><green/></color>

I'd like to be able to query any of the xelements to see if they containt the elements <red/>, <green/> or <blue/> below them and return true if so, false if not.
I was hoping that it would be simplier, but the best I could come up with was:
Dim primaryColor = From e In xe1.Elements Where e.Name = "blue" Or e.Name = "red" Or e.Name = "green"
Dim primaryColorTrue = primaryColor.SingleorDefault
If primaryColorTrue IsNot Nothing Then
'Blah
End If

Does anyone have a better way to do this, such as putting those xelements of red/green/blue into an array and using something like Elements.Contains(list of elements)?

A: If I understand correctly - perhaps (using C#, sorry - but no real C# specific logic here):
var colors = new[] {"red", "green","blue"};
bool any = el.Descendants().Any(child => colors.Contains(child.Name.LocalName));

Even if the VB fights you, I'm sure you can use .Any instead of .SingleOrDefault and a null check.
For info, using elements here to me sounds like an odd idea; I'd just have the color name as the text if possible:
<somexml><color>blue</color></somexml>

or even as an attribute:
<somexml color="blue"/>


text:
Q: Getting Thunderbird's email editor object from a restartless (bootstrapped) addon I'm creating a restartless (bootstrapped) addon for Thunderbird to replicate the functionality of an overlay-based addon I made years ago. The desire is to manipulate some of the text in the new email's body. In the old overlay version, it was pretty straightforward: I could just use the gMsgCompose object. How do I get the gMsgCompose object for a compose window in a restartless addon?
Here's my code right now. For a while I thought that edElem was nearly what I wanted, which is why I'm test-dumping edElem.editortype (which should be either "textmail" or "htmlmail" when I really do have the right object).
    'use strict';

    const Cc = Components.classes;
    const Ci = Components.interfaces;
    const Cu = Components.utils;

    Cu.import("resource://gre/modules/Services.jsm");

    function startup(data, reason)
    {
        Services.wm.addListener(MyAddon.windowListener);
    }

    function shutdown(data, reason)
    {
        Services.wm.removeListener(MyAddon.windowListener);
    }

    function install(aData, aReason) { }
    function uninstall(aData, aReason) { }

    if(!MyAddon) var MyAddon = {};
    MyAddon.windowListener = {
        onOpenWindow: function(aXULWindow) {
            let aDOMWindow = aXULWindow
                .QueryInterface(Ci.nsIInterfaceRequestor)
                .getInterface(Ci.nsIDOMWindow);
            if (!aDOMWindow) return;

            aDOMWindow.addEventListener("load", function _cl_load(event){
                aDOMWindow.removeEventListener("load", _cl_load, false);
                MyAddon.handleOpenWindow(aDOMWindow, event.target);
            }, false);
        }
    }; // MyAddon.windowListener

    MyAddon.handleOpenWindow = function(aDOMWindow, DOMdocument) {
        if(DOMdocument.documentURI != "chrome://messenger/content/messengercompose/messengercompose.xul")
            return;
        let edWindow = DOMdocument.documentElement;
        // Just to be sure
        if(edWindow.id != 'msgcomposeWindow')
            return;

        let edElem = DOMdocument.getElementById("content-frame");

        /* I thought edElem was the element I want, but the following
         * returns an empty result, which I take to mean the element isn't
         * fully loaded yet.
         */
        dump("XXX handleOpenWindow: edElem.editortype="+edElem.editortype+"\n");

        /* Adding a listener to this element doesn't get the behaviour
         * I want either. I've tried hooking several events
         * in the following fashion, and the event handler code doesn't
         * execute for any of them, so maybe edElem isn't what I want.
         */
        [ "load",
          "unload",
          "compose-window-init",
          "compose-window-close",
          "compose-fields-ready",
          "compose-send-message",
        ].forEach(function(eventName) {
            edElem.addEventListener(eventName, function _eE_FIXME(event){
                dump("XXX "+eventName+": edElem.editortype="+edElem.editortype+"\n");
            }, false);
        });

        /* So, how do I get control of the editor,
         * so I can read and play with its content?
         */

    }; // MyAddon.handleOpenWindow

The only question I found on stackoverflow that's close to what I want is Get sender and recipients in Thunderbird extension upon sending message. I've tried what they do there, but all it seems to do is give me an alternate way of getting the compose window as a whole, which I can already get.

A: I've made an ugly stub with a timer in the onOpenWindow:
domWindow.setTimeout( function() { uploadHook( domWindow ); }, 500 );

So then (in uploadHook) I can get editor with:
var editorNode = domWindow.document.getElementById("content-frame");
// GetCurrentEditor() equivalent:
nsIEditor = editorNode.getEditor(editorNode.contentWindow)

But looking for a better solution.


text:
Q: Using Regex in :contains jQuery Selector I am trying to use regex in a :contains jQuery selector and I am having issues finding documentation that supports being able to do so. I have the DOM of a webpage loaded in the domContent variable and trying to find all lines that contain a webURL and log it to the console. I just want to output all instances of an email address listed in the DOM.
function doStuffWithDOM(domContent) {
      console.log($(domContent).filter(":contains('@')").text())
}

I want to replace the @ with a regex that outputs an email address based on the following regex \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b

A: You cannot use a regular expression using the :contains() selector.
According to the documentation, nowhere does it say a regex can be used, and the parameter text is just a plain string text:

text: A string of text to look for. It's case sensitive.

What you're looking for is using the filter's function parameter:

This allows you to write custom code in the function (which can include a regular expression), and return true for elements that match the expression.
For more information, see "Using a Filter Function" section in the linked documentation.


text:
Q: Serializar y deserializar objetos y propiedades en Java Tengo un problema con la serialización y deserialización de objetos en Java, y creo que es porque realmente no entiendo como funciona. Mi programa consiste en unas hojas de calculo como en Excel, pero por consola. Tengo una clase "Book" y una clase "Page":
En Book, tengo declarado un HashMap de Page y en Page tengo un Hashmap de String (para simular las celdas). Ahora quiero que ese libro sea persistente y para ello lo que hago es serializar el objeto libro (instancia de Book)
try {
    FileOutputStream fileOut =
    new FileOutputStream("H:\\Users\\thero\\Desktop\\bin\\libro.bin");
    ObjectOutputStream out = new ObjectOutputStream(fileOut);
    out.writeObject(libro);
    out.close();
    fileOut.close();
    System.out.printf("Se ha guardado el libro correctamente");
}catch (IOException i) {
     i.printStackTrace();
}

Este codigo esta metido dentro de un metodo de una clase llamada "Salvar" que llamo desde el main.
Paralelamente tengo una clase "Cargar" con el metodo contrario:
try {
     FileInputStream fileIn = new FileInputStream("H:\\Users\\thero\\Desktop\\bin\\libro.bin");
     ObjectInputStream in = new ObjectInputStream(fileIn);
     libro = (Book) in.readObject();
     in.close();
     fileIn.close();
} catch (IOException i) {
     i.printStackTrace();
} catch (ClassNotFoundException ex) {
     Logger.getLogger(Cargar.class.getName()).log(Level.SEVERE, null, ex);
}

Este metodo tambien lo llamo desde el main, y al ejecutarlo, no salta ninguna excepción. Sin embargo parece ser que solo carga la instancia de Book, pero no carga la propiedad Hashmap, y por tanto no cargan las hojas creadas ni las celdas ni nada. Donde puede estar el problema? Gracias

A: Primero que todo, la serializacion consiste en convertir un objeto o conjunto de estos en bits para tratarlos en diferentes usos informaticos, sea para almacenarlos en archivos, o enviarlos mediante sockets (De groso modo, por la red). Puedes serializar cualquier objeto, siempre y cuando sea heredado de la interfaz Serializable.
La ventaja de HashMap es que ya tiene como interface implementada Serializable, por lo que nosotros podemos serializar todo el HashMap de una vez, con todos sus datos y atributos internos, por lo que al abrir el programa, solo es abrir el flujo, leer y asignar, cerrar los flujos y el buffer y listo.
Un ejemplo en codigo Java es el siguiente:
private HashMap<Integer, Persona> personas = new HashMap<Integer, Persona>();

Tenemos un HashMap, el cual la llave primaria sera de la clase Integer o entero, y el contenido sera de la clase Persona. Para guardar puedes utilizar lo siguiente:
public boolean add(int edad, String nombre){
        Persona p = new Persona(edad, nombre);
        return personas.put(personas.size()+1, p) != null;
}

Hasta aquí solo guarda en memoria, para guardar en el archivo haz lo siguiente:
    public void guardar(){
        try {
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(this.personas);
            oos.close();
            fos.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Gestion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Gestion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

El método add y guardar los puedes fusionar si quieres. Toda la clase donde esta toda la serializacion esta de la siguiente forma:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Carlos
 */
public class Gestion {
    private HashMap<Integer, Persona> personas = new HashMap<Integer, Persona>();
    private File file;
    private FileInputStream fis;
    private FileOutputStream fos;
    private ObjectInputStream ois;
    private ObjectOutputStream oos;

    public Gestion(String ruta) {
        this.file = new File(ruta);
        this.crearArchivo();
    }
    public boolean add(int edad, String nombre){
        Persona p = new Persona(edad, nombre);
        return personas.put(personas.size()+1, p) != null;
    }

    public HashMap<Integer, Persona> obtenerTodo() {
        try {
            HashMap<Integer, Persona> personasTemp = new HashMap<>();
            boolean buffer = false;
            fis = new FileInputStream(file);
            while (fis.available() > 0) {
                ois = new ObjectInputStream(fis);
                Persona p = (Persona) ois.readObject();
                if (p != null) {
                    personasTemp.put(personasTemp.size() + 1, p);
                }
                buffer = true;
            }
            if (buffer) {
                ois.close();
            }
            fis.close();
            return personasTemp;
        } catch (IOException | ClassNotFoundException e) {
            System.out.println(e);
            return null;
        }

    }

    public void obtener(){
        try {
            fis = new FileInputStream(file);
            boolean buffer = false;
            while(fis.available() > 0){
                ois = new ObjectInputStream(fis);
                HashMap<Integer, Persona> personasTemp = (HashMap<Integer, Persona>) ois.readObject();
                if (personasTemp != null){
                    this.personas = personasTemp;
                }
                buffer = true;
            }
            if (buffer){
                ois.close();
            }
            fis.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Gestion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(Gestion.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void guardar(){
        try {
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(this.personas);
            oos.close();
            fos.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Gestion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Gestion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void crearArchivo() {
        if(!this.file.exists()){
            try {
                file.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(Gestion.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void imprimirTodo(){
        if(this.personas.isEmpty()){
            System.out.println("No hay nada...");
            return;
        }
        for(int i = 0 ; i < this.personas.size(); i++){
            System.out.println(personas.get(i+1));
        }
    }
}

La clase personas es la siguiente:
import java.io.Serializable;
import java.util.Objects;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Carlos
 */
public class Persona implements Serializable{

    private static final long serialVersionUID = 1L;
    private int edad;
    private String nombre;

    public Persona(int edad, String nombre) {
        this.edad = edad;
        this.nombre = nombre;
    }

    public int getEdad() {
        return edad;
    }

    public void setEdad(int edad) {
        this.edad = edad;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 59 * hash + this.edad;
        hash = 59 * hash + Objects.hashCode(this.nombre);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Persona other = (Persona) obj;
        if (this.edad != other.edad) {
            return false;
        }
        if (!Objects.equals(this.nombre, other.nombre)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Persona{" + "edad=" + edad + ", nombre=" + nombre + '}';
    }

}

Y finalmente la clase Main o principal, que es donde esta el Main, es la siguiente:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Carlos
 */
public class Main {
    private final Gestion gestion;
    public Main() {
        this.gestion = new Gestion("ejemplo.bin");
        /*this.gestion.add(25, "Carlos");
        this.gestion.add(20, "Juan");
        this.gestion.add(19, "Pepe");
        this.gestion.guardar();*/
        this.gestion.imprimirTodo();
        this.gestion.obtener();
        this.gestion.imprimirTodo();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Main m = new Main();
    }

}


text:
Q: Read/write binary data on SD using Arduino I'm working on a project with an Arduino, and I'd like to be able to save some data persistently. I'm already using an Ethernet shield, which has a MicroSD reader.
The data I'm saving will be incredibly small. At the moment, I'll just be saving 3 bytes at a time. What I'd really like is a way to open the SD card for writing starting at byte x and then write y bytes of data. When I want to read it back, I just read y bytes starting at byte x.
However, all the code I've seen involves working with a filesystem, which seems like an unneeded overhead. I don't need this data to be readable on any other system, storage space isn't an issue, and there's no other data on the card to worry about. Is there a way to just write binary data directly to an SD card?

A: It is possible to write raw binary data to an SD card. Most people do this using the 4-pin SPI interface supported by the SD card. Unfortunately, data isn't byte-addressed, but block-addressed (block size usually 512 bytes).
This means if you wanted to write 4 bytes at byte 516, you'd have to read in block 0x00000001 (the second block), and then calculate an offset, write your data, then write the entire block back. (I can't say that this limitation applies to the SD interface using more pins, I have no experience with it)
This complication is why a lot of people opt for using libraries that include "unneeded overhead".
With that said, I've had to do this in the past, because I needed a way of logging data that was robust in the face of power failures. I found the following resource very helpful:
http://elm-chan.org/docs/mmc/mmc_e.html
You'll probably find it easier to make your smaller writes to a memory buffer, and dump them to the SD card when you have a large enough amount of data to make it worthwhile.
If you look around, you'll find plenty of open-source code dealing with the SD SPI interface to make use of directly, or as reference to implement your own system.


text:
Q: Phonegap 3 and Eclipse - Why use together? I understand that phonegap 3 no longer requires Eclipse to compile the code and that this is now done directly via just the command line.
Apart from using Eclipse to right code in, is there any other advantages to using it, instead of just using sublime 2 ?
Would an advantage be that Eclipse has a built in android emulator?

A: It is really going to come down to personal preference. My choice is to use Aptana Studio (built on Eclipse) for development.
Eclipse does not have a built in android emulator. You need to install the Android SDK, build an AVD and install the Eclipse plugin. This will allow you to run your code inside of the Android emulator but it is not built in to Eclipse. The same could be done with Aptana Studio.

A: As long as you build the .apk with PhoneGap build or the CLI you only really need the Android SDK and specifically adb to debug effectively on a physical device or on the emulator.
I usually build and test most things in Chrome, then test specifics using an Android device running
adb logcat

There is no real use for Eclipse unless you actually want to use it (and for JavaScript, why would you?)


text:
Q: IdentityServer4 redirect validator - implementing IRedirectUri interface I implemented a custom redirect validator (implemented interface IRedirectUriValidator) and injected it into IdentityServer4 (I'm aware of the risk that needs to be mitigated with covert redirect attacks) with the following, on the IdSrv4 host in Startup.cs, ConfigureServices():
services.AddIdentityServer()
    .AddRedirectUriValidator<MyCustomValidator>()

Even though I can get it to trigger following playing with client redirectUris / server side client config quite a bit, unless the redirectUri asked for by the client is in the server side client config's "RedirectUris" list, my redirectUri validator never gets triggered because the client will be rejected first.
Seems to defeat the point of a redirect Uri validator.  Is there a way to completely override this behavior besides just implementing this interface / injecting it into the authentication flow?

A: Did you implement the interface from scratch or did you, like I did, inherited from the StrictRedirectUriValidator?
I ask as I had the same problem just this week using IdentityServer 3.1.2 until I realised I hadn't added the "override" modifier to the IRedirectUriValidator method signatures that I overrode.
public **override** async Task<bool> IsRedirectUriValidAsync(string requestedUri, Client client)
{
   ...
}

It worked after that. Such a silly error but they do happen. Hope this helps someone.


text:
Q: Error VSP1737: File could not be opened due to sharing violation I am getting below error in the Visual Studio 2013 Ultimate when running performance and diagnostics session with Team Foundation Server (TFS). Below are the steps to reproduce:

*

*Get latest from Team Foundation Server.

*Create new Performance Session of "CPU Sampling" method.

*Launch the newly created Performance Session.

*After exiting the session by closing internet explorer or clicking
on "Stop Profiling".

Then I would get below error in the Output Window.
Preparing web server for profiling.
Profiling started.
Launching web server with profiling.
Launching profilable project.
Profiling process ID 9460 (iisexpress).
Profiling process ID 7008 (iexplore).
Process ID 7008 has exited.
Process ID 9460 has exited.
Error VSP1737: File could not be opened due to sharing violation: C:\Users\%hiddenuserprofile%\Documents\Projects\%HiddenPathWithFilename%.vsp
PRF0025: No data was collected.
Profiling complete.

In order to get rid of this error, I would have to clear the read-only attribute of my solution folder which TFS has set. If I clear the read-only attribute then the TFS cannot detect changes in my local workspace with the TFS server. Then I would have to manually check for changes with compare option in TFS and then merge.
Why does this error shows up? Am I doing it the right way?

A: This error occurs because you have added files to source control that should not be in there. Therefore it is downloaded from TFS and marked as read only.
You should use a .tfignore file. You will have to manually remove all of the files that have already been added. You should not have any /bin/* or /obj/* files for a start...
Then check for *.dll and other binaries, including *.vsp files and remove them from source control.
There are two types of binaries:

*

*References - these should be done using Nuget and never included in source control or added manually.

*output/generated - No generated files should be added to source control.


text:
Q: Change value of variable from component to other (non related components) Is there a way to change the value of the variable called variable1 in the component 2 from component 1 making click in the function of this component ?
Component 1 ts
@Component({
  selector:    'app-component1',
  templateUrl: './component1.html',
})
export class Component1 implements OnInit {
  changeVariable(){

  }
}

component1.html

Component 2 ts
@Component({
  selector:    'app-component2',
  templateUrl: './component2.html',
})
export class Component2 implements OnInit {
  variable1: boolean = false
}

A: You have 2 options:

*

*Pass the component2 context/reference into component1.

*Use service to store the variable1, and it can be then share between component1 and component2.

Option 1
If non-related means sibling components which is used side by side in a parent component like below:

  <app-component-1>   </app-component-1>
  <app-component-2>   </app-component-2>

Then you can pass the context of the component-2 into component-1.
component1.ts
import { Component, Input } from '@angular/core';
import { Component2Component } from '../component-2/component-2.component';

@Component({
  selector: 'app-component-1',
  templateUrl: './component-1.component.html',
  styleUrls: ['./component-1.component.css']
})
export class Component1Component {

  // This will allow you to pass in component2 context/reference.
  @Input()
  public component2Context!: Component2Component;

  constructor() { }

  public changeVariable() {
    // After passing component2 context, you can call all its public functions/properties.
    this.component2Context.variable1 = true;
  }

}

component1.html
<button (click)="changeVariable()">Change Variable 1</button>

component2.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-component-2',
  templateUrl: './component-2.component.html',
  styleUrls: ['./component-2.component.css'],
})
export class Component2Component {
  public variable1 = false;

  constructor() {}
}

component2.html

Component2.variable1 = {{ variable1 }}

Then in the Parent, you need to pass the reference from component2 into the component1 like below:
parent.html

  <app-component-1 [component2Context]="comp2Context"></app-component-1>
  <app-component-2 #comp2Context></app-component-2>

Option 2
You can use a service to store the variable1. Then any components can have access to it. Component1 can update its value, and component2 can see the updated value.
Here is the demo I created: https://stackblitz.com/edit/angular-ivy-qj7mer


text:
Q: how to call your yacc from a c file? i want to parse a command line using a yacc but i want to call it from a c file. how it is possible ?

A: The code generated by YACC creates a function called yyparse(). Simply call it.
See for example: http://dinosaur.compilertools.net/yacc/index.html (section 8).


text:
Q: Alternative method in PDO for mysql_result() function I have been using a mysql abstraction class in php and now I want to make the class more      usable and solid by using PDO . In my class I had used mysql_result() function which takes three parameters :

*

*result: The result resource that is being evaluated. This result comes from a call mysql_query().

*row: The row number from the result that's being retrieved. Row numbers start at 0.

*field: The name or offset of the field being retrieved.

How could I achieve similar output by using PDO ?
Here is the code written with native mysql functions.
public function SQLtoJSON($query, $indented = false)
    {
        $query = mysql_query($query) or die ('MyJSON - SQLtoJSON - Cannot make query');

        if (!$numFields = mysql_num_fields($query)) {
            $this->errors[] = 'SQLtoJSON - Cannot get number of MySQL fields';
            return false;
        }

        $fields = array();
        for ($i = 0; $i < $numFields; $i++)
            $fields[$i] = mysql_field_name($query, $i);

        if (!$numRows = mysql_num_rows($query)) {
            $this->errors[] = 'SQLtoJSON - Cannot get number of MySQL rows';
            return false;
        }

        $res = array();
        for ($i = 0; $i < $numRows; $i++) {
            $res[$i] = array();
            for ($j = 0; $j < count($fields); $j++)
                $res[$i][$fields[$j]] = mysql_result($query, $i, $j);
        }

        $json = json_encode($res);
        if ($indented == false)
            return $json;

and here is the updated version of the code using PDO:
class MySql_To_Json
{

    private $connection;
    public $errors = array();

    public function __construct($db_server, $db_username, $db_password, $db_name)
    {
        $this->connection = new PDO("mysql:host=$db_server;dbname=$db_name",   $db_username, $db_password);
    }

    public function MySQLtoJSON($query)
    {
        $query = $this->connection->query($query) or die("Unable to execute the query");
        if (!$numFields = $query->columnCount()) {
            $this->errors[] = "Unable to get the number of fields";
            return false;
        }

        $fields = array();
        $colNames = array();

        for ($i = 0; $i < $numFields; $i++) {
            $fields[$i] = $query->getColumnMeta($i);
            foreach ($fields as $field) {
                $colNames[] = $field['name'];
            }
        }

        if (!$numRows = $query->rowCount()) {
            $this->errors[] = "Unable to get the number of rows";
            return false;
        }

    // return $numRows;
        $result = array();
        for ($i = 0; $i < $numFields; $i++) {
            $result[$i] = array();
            for ($j = 0; $j < count($field); $j++) {
                return $result[$i][$field[$j]] = $query->fetch($i);
            }
        }

        $json = json_encode($result);
        return $json;
    }
}

A: As I suspected and alluded to in the comments, your original use of mysql_result() was unnecessary. What you had in the old class was a collection of C-style incremental for loops, which are rarely appropriate in PHP. Instead it's much more common to iterate arrays with foreach and when dealing with database APIs, to do something like:
// This is the normal and easy way to get an associative array of results:
while ($row = mysql_fetch_assoc()) {
  $results[] = $row;
}

...where you don't need to worry about the number of rows or columns.
In any case, all of that is entirely unnecessary now and can be replaced with a single call to fetchAll() in PDO, since all it did was retrieve all rows into a column-name indexed array. That is about as standard as a fetch operation gets.
   // ALL of this...
   // $res = array();
   // for ($i = 0; $i < $numRows; $i++) {
   //     $res[$i] = array();
   //     for ($j = 0; $j < count($fields); $j++)
   //         $res[$i][$fields[$j]] = mysql_result($query, $i, $j);
   // }

   // ...may be replaced with simply:
   $res = $query->fetchAll(PDO::FETCH_ASSOC);

This also means that you don't really need the two preceding blocks which retrieve the number of rows and columns.  All of that is implicit in the call to fetchAll().  The only parts you actually now need are the query and the fetch:
public function MySQLtoJSON($input_query)
{
    // Do your query...
    $query = $this->connection->query($input_query) or die("Unable to execute the query");

    // Fetch the rows as associative arrays
    $result = $query->fetchAll(PDO::FETCH_ASSOC);

    // And encode it as JSON
    $json = json_encode($result);
    return $json;
}

Note that since you are executing arbitrary SQL statements in the $query parameter, you will need to be cautious about what gets passed in there to avoid SQL injection. If you are accepting any user input rather than static queries, you'll need to look into adapting this to use PDO::prepare() and execute them as parameterized queries.


text:
Q: Can MVC run on 3.5 IIS6? NON SP1 I was lead to believe that MVC apps were BIN-deployable, so could be deployed to any ASP.net 3.5 compatible server. I'm trying to deploy to a Windows Server 2003 x64 with 3.5 (no SP1) and am having trouble getting it working.
I get the following when hitting the homepage, which redirects to the /Account/LogOn view due to our app config.

The page cannot be found

I've got the three (plus Extensions, I can't remember why) MVC dll's set to Copy Local, so they end up in the bin-folder. I'm publishing and then copying over the app to the server:

*

*System.Web.Abstractions.dll

*System.Web.Mvc.dll

*System.Web.Routing.dll

*System.Web.Extensions.dll

Does anyone know what I'm doing wrong? The app works on another machine we have with 3.5 SP1, and on development machines, also SP1 and with MVC installed.
I've gone over everything I can think of, ensured the permissions are correct, etc.

A: IIS 6 does not handle .mvc extensions correctly.  Among other things you have to map .mvc to the ASP.NET handler.  Here is a walkthrough for you: http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx

A: Have you set up wildcard mapping on the server that does not work?  See "Deploying ASP.NET MVC to IIS 6" for an example.  You basically need to map all requests to the ASP.NET ISAPI DLL and tell IIS not to try to verify that the file exists.  Don't know if that's your issue, but it has bitten me a few times in deployments.

A: With IIS6, you can't do extensionless URLs like /Account/LogOn.  You have to do something like /Account.aspx/LogOn  The ".aspx" can really be almost any arbitrary extension, but you need that extension.  Your routes need to take the extension into account as well.

A: Check to make sure the app pool your site is running under is configured to run ASP .Net 2.0, sometimes it defaults to 1.1 which causes issues similar to yours.


text:
Q: Docker with yarn First time trying to get yarn and docker working together.
How can I stop yarn from installing the packages every single time I run docker build command?
I've found some solutions like storing node_modules in a temporary directory and then linking it, but with various packages installed I get too many errors to handle. Is there maybe a way to compare my yarn.lock with the one existing inside Docker or any other solutions?
Dockerfile:
FROM node:8.9.1-alpine

COPY package.json yarn.lock /usr/src/
RUN cd /usr/src \
    && yarn install --pure-lockfile

COPY . /usr/src
EXPOSE 3005

With this setup I get a message saying Sending build context to Docker daemon  375.2MB, then the yarn install is run as usual, fetching the packages every single time.

A: You should use the docker cache better.
If you have your Dockerfile prepared as follows:
FROM node:carbon

COPY package.json yarn.lock /app
RUN cd /app \
    && yarn install --pure-lockfile

COPY . /app
CMD doStuff

The docker build won't touch the package.json unless it has changed. The next RUN command won't execute unless the cache has been invalidated in the earlier step.
NOTE: keep the node_modules inside your .dockerignore file

A: Definitely pay attention to docker caching. Basically you want to run the most stable instructions earlier than less stable ones. Instructions which would result in the same image changes as an earlier run should not be rerun (exluding issues with ENV/ARG instructions). But once an instruction does need to be run, all instructions following will be run regardless of what's in the cache.
.dockerignore will also help, but it can be easy for things to slip in. I've adopted the practice of inverting the file by ignoring everything and then specifying exactly what should be copied.
To minimise fetching from the web, I like using the yarn offline cache. This stores the tarballs of installed dependencies and reuses them for future installs. You get the benefit over npm rebuild of fresh installs every time (if the cache has been invalidated). You configure the offline cache with a .yarnrc file which could be in your home directory but for this purpose you keep one in your repo along with a directory to store the tarballs.
You have the option of checking-in the mirror directory to your repo. A typically large npm module install will still only be in the region of 20 megs.
If you use the files below, customised for your needs, and run yarn locally, the yarn-offline-mirror will contain the tarballs needed to install the app.
.dockerignore
*

!yarn-offline-mirror/
!src/
!package.json
!yarn.lock
!.yarnrc

.yarnrc
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1

yarn-offline-mirror "./yarn-offline-mirror"

Dockerfile
ENV HOME /usr/src/
WORKDIR $HOME

# copy the tarballs
COPY ["yarn-offline-mirror", "$HOME/yarn-offline-mirror/"]

# copy files needed for the install
COPY ["package.json", "yarn.lock", ".yarnrc", "$HOME/"]

# the offline flag will mean that an error is raised if any
# module needs to be fetched remotely. It can be removed to allow
# yarn to fetch any missing modules if that was to happen.
RUN yarn --offline --frozen-lockfile --link-duplicates

# copy the rest.. could be further broken up into multiple instructions
# for cache optimisation
COPY . $HOME

CMD npm start


text:
Q: How to position check boxes under a column header vertical in angular material? I have a angular material table with some header column. But under one header column I have some checkboxes for the name of the project.
I have it like this:

 <ng-container matColumnDef="projects">

              <mat-checkbox
                (click)="$event.stopPropagation()"
                (change)="filterProjects($event, i, item)"
                [checked]="selected === i"
                [disabled]="isDisabled"
                >{{ item.name }}
              </mat-checkbox>

          Project

        {{ row.projects }}
      </ng-container>

But now it looks like this:
But of course the header column project has to bee positioned above the checkboxes in line with the other column headers.
So what I have change?
Thank you


text:
Q: Plaid only giving "ITEM_LOGIN_REQUIRED" for Capital One I'm using plaid to attempt to get transactions from a linked account. In sandbox I was not getting any errors but once I moved into development I started seeing "ITEM_LOGIN_REQUIRED" while trying to get transactions. I'm using the plaid react component and plaid ruby gem. I suspect that there isn't an error in my code as much as the flow through Plaids api which like the following
User interacts with Link -> logs into account with creds -> account is linked and public_token is returned -> public_token exchanged for access_token which is stored in DB -> access_token used to lookup transactions -> Plaid returns error. -> take user through update mode -> lookup transactions -> error -> rinse and repeat.
Below is where I'm looking up transaction and where I get the error.
    start_date = Date.new(date[0].to_i, date[1].to_i, 1).strftime('%Y-%m-%d')
    end_date = Date.new(date[0].to_i, date[1].to_i, -1).strftime('%Y-%m-%d')

    plaid_env = Rails.application.config.plaid_env
    client_id = Rails.application.config.client_id
    secret = Rails.application.config.secret
    public_key = Rails.application.config.public_key

    client = Plaid::Client.new(env: plaid_env,
                               client_id: client_id,
                               secret: secret,
                               public_key: public_key)

    transaction_response = client.transactions.get(access_token, start_date, end_date)

    transactions = transaction_response.transactions

A: According to Plaid support this one is actually on their end.

Plaid Support Nov 8, 2019,
Thanks for reaching out to Plaid Support!
I've confirmed that there is an issue with our Capital integration
  that is causing this issue. Our engineering team is aware of this
  issue and currently working to resolve it. We will reach out here as
  soon as this is resolved.
Please let us know if you have any further questions or concerns.
  Thanks for your patience while we work to resolve this!
Best, Phillippa Plaid Suppor

I asked if there was an ETA or Workaround and here is their reply.

We are dedicating ongoing resources to resolving this issue, but
  unfortunately Capital One hasn't been cooperative and we can't
  anticipate a timeline for a technical resolution at this point. There
  isn't currently a workaround that I'm aware of. I sincerely apologize
  for the inconvenience that this causes – this issue is unique to our
  Capital One integration, and does not affect the other institutions
  that we support.
We'll be sure to reach back out here as soon as we have any updates!
Best, Nicole

Plaid Support


text:
Q: raspi not seeing teensy, udev rules probably at fault I am pretty deep into this now and operating at about 50% understanding. We have a Raspi 3B+ running Ubuntu 20.04 for Raspi. We have a Teensy 3.7. They are connected together with a USB cable. I know that the Teensy is getting power.
This is the rule that I am being told to use:
KERNEL=="ttyACM?", SUBSYSTEM=="tty", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="0478", ATTRS{serial}=="000F0B8C", MODE="0666" SYMLINK+="linobase"

Not sure what udev rules do exactly
I have the feeling the the udev rule is not "matching" and that's why it is not creating the symlink. But I really am not at all sure. But honestly I don't really understand udev. I am just kind of plowing through with "common sense' which is not working for me.
Cable?
I was also suspecting it might be the usb cable? As I understand it many usb cables are "power only". However, the problem didn't go away when I used a "known good" data USB cable.
Code 43?
There may be an esoteric problem known as the "Code 43" problem that is in play here - see pjrc.com/teensy/troubleshoot.html. Anyone know anything about it?


text:
Q: Spinnaker for job deployments? Does anyone use Spinnaker for deployment of short running jobs, similar in spirit to what Kubernetes or Nomad do? If so, how do they do it? If not, are there any plans to support it one day?

A: The kubernetes provider specifically supports a Run Job stage in a pipeline that allows execution of a container that is expected to run to completion.
Similarly there is an option to run a jenkins job as a stage which I've seen teams use to execute arbitrary work (not just CI type of tasks)


text:
Q: Why EF6 LINQ does not generate proper "is null" SQL for null string variable comparison? We have an EDMX-based EF6 application, where we'd like to run a LINQ query like this.
string category = ... // comes from somewhere and equals to null
context.Product.Where(e => e.Category == category).ToArray();

The problem I see is that the generated SQL contains a [table].[Category] = @p... in the where clause, regardless of the variable category being null or not. So at the end of the day the query returns no results if the variable is null, instead of generating a proper is null criteria and return the proper rows.
I've tested with the explicit e => e.Category == null expression and that does generate the is null as expected.
I've also checked the EDMX and the SQL, and the corresponding Category column is nullable indeed in both places, so that might not be the issue.
Any help would be appreciated.

A: Try to set context.Configuration.UseDatabaseNullSemantics to false. This is the property which affects the mentioned behavior.
See the documentation here


text:
Q: TS types for rows in custom re-usable table component I'm creating re-usable component, but not sure how I can specify type for rows.
const CustomTable = ({ columns, rows, actions }: TablePropsTypes) => {}

Types:
export interface IColumn {
    field: string;
    fieldName: string;
    fieldType: 'number' | 'string';
    editable?: boolean;
}

export interface IColumns extends Array<IColumn> {}

export type TablePropsTypes = {
    columns: IColumns;
    rows: Array<Object>; // Not sure how to add here a type if user can pass different data here
    actions: boolean;
}

A: Probably your best choice is to make the component generic. This allows yo to capture the call site type, and offer validation for the field property:
const CustomTable = <T,>({ columns, rows, actions }: TablePropsTypes<T>) => {
    return <></>
}

export interface IColumn<T> {
    field: keyof T;
    fieldName: string;
    fieldType: 'number' | 'string';
    editable?: boolean;
}

export interface IColumns<T> extends Array<IColumn<T>> {}

export type TablePropsTypes<T> = {
    columns: IColumns<T>;
    rows: Array<T>;
    actions: boolean;
}

const data = [{ name: "", value: 0}]
let t = <CustomTable actions={true} rows={data} columns={[
    { field: "name", fieldName: "Name", fieldType: "string" }
]} />

let terr = <CustomTable actions={true} rows={data} columns={[
    { field: "name2", fieldName: "Name", fieldType: "string" }
]} />

Playground Link


text:
Q: optaplanner pareto compasion and bendable score I am playing with Timed Window VRP and i have a over constrained situation.
In my soft constraints
i have mentioned to reduce miles
Also i dont want free truck if there are a number of tasks assigned to dummy vehicles.
Currently i have kept hard medium and soft.
To achieve, use spare vehicles when dummy vehicles get load, can i approach this using Bendable score? as i dont want to save miles when i can take more task with my free vehicle in this case i am okay to drive more.
Any advise?


text:
Q: Backtracking in Legend of Grimrock Is every secret you missed on previous floor always obtainable later in the game or is there any blocking factor or any floor not reachable?
EDIT: I want to know if every level is always accessible, but also if every secret is still doable later in the game. For instance:

after beating level 4 the four portals to the puzzles disappeared and if there is some secret still in there is not doable anymore.

A: I can only answer up to level 11 (there are 13), but at anytime can you go back to the previous levels.  With the exception of:

 Level 6 Trapped where you are trapped in that level till you complete it and reach the stairs that go down, then the upstairs become unblocked again.

*Update
After beating the game, you can go back at anytime up until (super end game spoiler)

 Till you insert all 4 pieces of machinery into the cube and activating the end game boss.

A: Yes, you can always go back and look for the secrets you've missed.
About the question in the spoiler,

 in level 4 there's a hidden lever that will make the four portals reappear and let you explore everything you've missed. It's placed in the corridor that opens up once you solve the scroll's puzzle.


text:
Q: Adding a minus sign to the UITextField's .NumberPad keyboard Fairly new to iOS development so forgive me for asking something that might be quite obvious. As you all know the UITextField's keyboard with keyboardType set to .NumberPad looks like the following...
.NumberPad keyboard
What I would like to do is replace the empty space in the lower left corner with a minus sign. Is this possible or does one need to write an entire custom keyboard to achieve this?
Would really appreciate the help.

A: Add a toolbar to your textfield inputAccessoryView and when the textfield will become the responder then the keyboard will show the toolbar (Swift 3.0):
func addToolBar(){
   let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 44))
   let minusButton = UIBarButtonItem(title: "-", style: .plain, target: self, action: #selector(toggleMinus))
   toolbar.items = [minusButton]
   theTextField.inputAccessoryView = toolbar
}

func toggleMinus(){

    // Get text from text field
    if var text = theTextField.text , text.isEmpty == false{

        // Toggle
        if text.hasPrefix("-") {
            text = text.replacingOccurrences(of: "-", with: "")
        }
        else
        {
            text = "-\(text)"
        }

        // Set text in text field
        theTextField.text = text

    }
}

hope it helps.

A: Swift 5.2
Set up the UIToolbar as described above and then use an extension on UITextField:
import UIKit

extension UITextField {
    func toggleMinus() {
        guard let text = self.text, !text.isEmpty else { return }
        self.text = String(text.hasPrefix("-") ? text.dropFirst() : "-\(text)")
    }
}

Usage:
@objc func toggleMinus() {
    yourTextField.toggleMinus()
}


text:
Q: Compiling cuda from command line - win32 I don't want the whole VS install, especially since it would eat up most of my C space, so I grabbed the SDK.  I've also installed the cuda SDK.  I'm running into a rather absurd problem though:
d:\cuda\class>nvcc --cubin unit1-1.cu
unit1-1.cu
unit1-1.cu
tmpxft_00001224_00000000-5_unit1-1.cudafe1.gpu
tmpxft_00001224_00000000-11_unit1-1.cudafe2.gpu
'nvopencc' is not recognized as an internal or external command,
operable program or batch file.

d:\cuda\class>nvopencc
nvopencc: no input files
For general help: nvopencc --help
To search help: nvopencc -help:<string>

It's saying that nvopencc isn't a valid command and yet I can run it!  Anyone have any idea at all how to fix this??  I found --cubin on a command somewhere and hoped it would work...I have no idea if it's supposed to be there.  At any rate, with or without I get the same error.

A: Here's a typical call to nvcc.exe, generated by Visual Studio 2010. Looks like you need to specify the location of the compiler binaries.

nvcc.exe -gencode=arch=compute_30,code=\"sm_30,compute_30\"
  --use-local-env --cl-version 2010 -ccbin "c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin"
  -I"\C\common\inc" -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v5.0\include" -I"C:\Program Files\NVIDIA GPU Computing
  Toolkit\CUDA\v5.0\include" --keep --keep-dir "Release" -maxrregcount=0
  --machine 32 --compile -D_MBCS -Xcompiler "/EHsc /W3 /nologo /O2 /Zi /MD " -o "Release\kernel.cu.obj" "c:\test_cuda\test_cuda\kernel.cu"


text:
Q: What is the reason for the error message `Can't locate object method "get_ok"` when using WWW::Mechanize::TreeBuilder? I couldn't really figure out how to use WWW::Mechanize::TreeBuilder. Basically I get a HTML page using WWW::Mechanize. There is a //div[@class='cars'] whose text I want to extract.
I tried:
my $mech = WWW::Mechanize->new();
$mech->get('the url');
WWW::Mechanize::TreeBuilder->meta->apply($mech);
$mech->get_ok('//div[@class="cars"]');
print $mech->look_down(_tag => 'p')->as_trimmed_text . "\n";

It says:
Can't locate object method "get_ok" via package "Class::MOP::Class::__ANON__::SERIAL::2" at orpi_crawler.pl

A: get_ok is from Test::WWW::Mechanize which you neglected to load. Read the synopsis of WWW::Mechanize::TreeBuilder carefully.


text:
Q: Three Js load texture/ material of model from js file
Possible Duplicate:
Three.js not possible to load textures

I am a beignner as far as ThreeJs and blender is concerned so this may seem a silly question. I am trying to load a model using JSONLoader. I used the threejs blender export and exported the collada model to js. However I am unable to get the material directly from the file.
Upon checking I found that the attribute to the image file is missing in the js file i.e "mapDiffuse" attribute is absent. Is that an error. If so any suggestions? Or is there some other way of loading the materials?
P.S  This was a collada model i downloaded, so texture images were provided with it, though blendor export did not notice it.
A part of my model js file
{
"metadata" :
{
    "formatVersion" : 3.1,
    "generatedBy"   : "Blender 2.64 Exporter",
    "vertices"      : 1172,
    "faces"         : 2209,
    "normals"       : 736,
    "colors"        : 0,
    "uvs"           : [1722],
    "materials"     : 1,
    "morphTargets"  : 0,
    "bones"         : 0
},

"scale" : 1.000000,

"materials" : [ {
    "DbgColor" : 15658734,
    "DbgIndex" : 0,
    "DbgName" : "material_2_81_0",
    "blending" : "NormalBlending",
    "colorAmbient" : [0.6400000190734865, 0.6400000190734865, 0.6400000190734865],
    "colorDiffuse" : [0.6400000190734865, 0.6400000190734865, 0.6400000190734865],
    "colorSpecular" : [0.5, 0.5, 0.5],
    "depthTest" : true,
    "depthWrite" : true,
    "shading" : "Lambert",
    "specularCoef" : 50,
    "transparency" : 1.0,
    "transparent" : false,
    "vertexColors" : false
},
.
.
.
.
.

"vertices" : [1159.45,531.608,-1808.68,......]
"morphTargets" : [],
"normals" : [-0.101077,0,-0.994873,......]
"colors" : [],
"uvs" : [[0,0,1,0,0,1,....]
"faces" : [42,0,1,2,0,0,1,2,0,1,2,42,0...]

"bones" : [],

"skinIndices" : [],

"skinWeights" : [],

"animation" : {}
}

Thank You

A: I will point you toward this question that I answered not long ago, which is almost an exact duplicate. I am not sure whether it is possible to get your material loaded using only the file. The only way I have had luck is loading the textures manually from in my code and then applying them. Just use the exporter to export your geometry and UV mapping and don't worry about exporting the textures. Simply gather them up and if you are running this locally make sure you are using a server, otherwise you won't be able to load the images from the disk. At this point it is very simple code to load up your model and apply your texture. For future reference you should post up your code that you use to load your model as well. You need to utilize the arguments of the given functions to pass in callbacks so that you do not try to render anything before it is completely loaded.
var tex, mat, mesh;

$(window).load(function () {
    /** Load mesh from JSON, position, scale, add texture and add to scene */
    tex = THREE.ImageUtils.loadTexture('../img/texture.jpg', null, function () {
            mat = new THREE.MeshPhongMaterial({ map: tex });
            loader.load('model.js', function (geo) {
                mesh = new THREE.Mesh(geo, mat);
                mesh.position.set(0, 0, 0);
                mesh.scale.set(20, 20, 20);
                // etc, etc
                scene.add(mesh);
            });
        });
});