text:
Q: Delete all records from table in sqlite database I know this is very frequently asked question and i tried everything that i found here. But problem is still there.
Now the problem is i am trying to delete all records from 3 tables with following code but they are not being deleted
const char *dbpath = [dbPathString UTF8String];
sqlite3 *sqliteDB;

if (sqlite3_open(dbpath, &sqliteDB) == SQLITE_OK)
{
    //Delete all records from attempts
    sqlite3_stmt *statement;

    NSString *deleteSQL = [NSString stringWithFormat: @"DELETE FROM table1"];

    const char *delete_stmt = [deleteSQL UTF8String];
    sqlite3_prepare_v2(sqliteDB, delete_stmt, -1, &statement, NULL);

    sqlite3_finalize(statement);
    sqlite3_close(sqliteDB);
}
if (sqlite3_open(dbpath, &sqliteDB) == SQLITE_OK)
{
    //Delete all records from attempts
    sqlite3_stmt *statement;

    NSString *deleteSQL = [NSString stringWithFormat: @"DELETE FROM table2"];

    const char *delete_stmt = [deleteSQL UTF8String];
    sqlite3_prepare_v2(sqliteDB, delete_stmt, -1, &statement, NULL);

    sqlite3_finalize(statement);
    sqlite3_close(sqliteDB);
}
if (sqlite3_open(dbpath, &sqliteDB) == SQLITE_OK)
{
    //Delete all records from attempts
    sqlite3_stmt *statement;

    NSString *deleteSQL = [NSString stringWithFormat: @"DELETE FROM table"];

    const char *delete_stmt = [deleteSQL UTF8String];
    sqlite3_prepare_v2(sqliteDB, delete_stmt, -1, &statement, NULL);

    sqlite3_finalize(statement);
    sqlite3_close(sqliteDB);
}

I have tried with if conditions like
if (sqlite3_prepare_v2(sqliteDB, delete_stmt, -1, &statement, NULL) == SQLITE_OK) {
    NSLog("All records deleted");
}

And this if condition get executed and i do have statement in console log.
I am using Xcode 5.0.
Please help me. Thanx in advance

A: Dear friend this is little bit complex coding try to use external class for easy coding
this link will help you
How to insert update delete in database operation and also save database in document directory
for delete record you can use
NSString *strDelete = [Database executeScalarQuery:@"DELETE FROM table1"];

Happy Coding!!!

A: sqlite3_prepare_v2 just prepares the statement.
To actually execute it, you must also call sqlite3_step.


text:
Q: how to disable scroll wheel zoom in here maps javascript we use javascript here maps and try to disable the scroll wheel zoom with map.scrollWheelZoom.disable();
this creats an error: Uncaught TypeError: Cannot read property 'disable' of undefined
is there an alternative?
here is the code from the map section:

<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1542186754" />

A: Use the disable method on the H.mapevents.Behavior instance variable:
[...]
var behavior = new H.mapevents.Behavior( new H.mapevents.MapEvents(map) )

// disable wheel zoom behavior
behavior.disable(H.mapevents.Behavior.WHEELZOOM)

Alternatively, you can choose what behaviors to enable, when you instantiate the H.mapevents.Behavior object. To do that, use the optional second argument, like that:
var behavior = new H.mapevents.Behavior(
    new H.mapevents.MapEvents(map),
    {
        enabled: H.mapevents.Behavior.DRAGGING | H.mapevents.Behavior.DBLTAPZOOM
    }
);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to (actually) protect an object from being modified? The const type qualifier causes the compiler to issue an error message in case an attempt to modify an object declared as const,but that is not enough protection.For example the following program modifies both elements of the array declared as const:
#include <stdio.h>

int main(void)
{
    const char buf[2] = { 'a','b' };
    const char *const ptr = buf;
    unsigned long addr = (unsigned long)ptr;

    *(char *)addr = 'c';
    addr = addr + 1;
    *(char *)addr = 'd';

    printf("%c\n", buf[0]);
    printf("%c\n", buf[1]);
    return 0;
}

So,it turns out to be that the compiler is not enough guard to protect the objects from being modified.How can we prevent this sort of thing?

A: I don't think more protection can nor should be provided.
The C programming language lets you do almost everything you want freely, especially accessing objects from pointers. However, freedom is never free, so C programmers must always be careful (and avoid casting if it isn't necessary).

A: A standard tool for finding memory overruns is watchpoints, or data breakpoints as they are called in MS Visual Studio.
If you need to protect your object just for debugging, use your debugger to set a watchpoint inside your object. The bug will be discovered at runtime (not compile time) - when your program tries to write to the specified address, the debugger will stop it.
You might be able to set your watchpoints in your code, but their number is limited (the maximum is 4 on x86 platform), so this cannot be a general-purpose feature of your program.

A: I think the philosophy behind protection is the comfort of one who is using your code as ready library in his own code.
Otherwise if it was possible to make the object completely non-modifiable in C language, there would be some crackers who could modify whatever they want :) :)


text:
Q: How do I update MongoDB document fields only if they don't exist?

I have collection foo with documents like:
{site_id: 'xxx', title: {ru: 'a', en: 'b'}, content: {ru: 'a', en: 'b'}}
{site_id: 'xxx', title: {ru: 'c', de: 'd'}, content: {ru: 'c', de: 'd'}}

I need to update multiple fields which are can exists or not:
db.foo.update(
    { site_id: 'xxx'},
    { $set: {'title.de': '', 'content.de': ''}},
    {multi: true}
)

But I need something like $set which will not overwrite value if it exists.

A: You can add a query to your update statement:
db.foo.update({'title.de': {$exists : false}}, {$set: {'title.de': ''}})

Update
For your modified question my solution looks like this - would that work for you? (If not, why?)
db.foo.update({site_id: 'xxx', 'title.de': {$exists : false}}, {$set: {'title.de': ''}, {multi: true})
db.foo.update({site_id: 'xxx', 'content.de': {$exists : false}}, {$set: {'content.de': ''}}, {multi: true})

A: If anyone encounters the problem as me:

My solution is to set _id only if the update results in insert a new on (upsert: true)
return {
    updateOne: {
        filter: {
            email: shadowUser.email,
        },
        update: {
            $set: user,
            $setOnInsert: { _id: shadowUser._id },
        },
        upsert: true,
    },
};

A: Even though the answer given essentially outlines the approach, you can do this sort of thing with MongoDB 2.6 or greater due to the implementation there that supports "bulk updates".
This are still, "atomically speaking", separate update statements. But you can submit them "over the wire" in one go. Which at least makes sure that the latency between the updates is much shorter as they are executed on the server:
var bulk = db.foo.initializeBulkOrderedOp();
bulk.find({ "site_id": "xxx",
    "title.de": { "$exists" false } })
    .update({ "$set": { "title.de": "" } });
bulk.find({ "site_id": "xxx",
    "content.de": { "$exists" false } })
    .update({ "$set": { "content.de": "" } });
bulk.execute();

So that is actually one round trip to the server as everything only sends on .execute()
But in your present form (though this may not be a accurate representation of your data), you can actually "re-structure" in order to do this in a single operation. So if your documents looked like this:
{
    "site_id": "xxx",
    "docs": [
        { "title": "a", "content": "a", "lang": "ru" },
        { "title": "b", "content": "b", "lang": "en" }
    ]
},
{
    "site_id": "xxx",
    "docs": [
        { "title": "c", "content": "c", "lang": "ru" },
        { "title": "d", "content": "d", "lang": "de" }
    ]
}

Then the following works by the rule of $addToSet where the "set" element would be "unique":
db.foo.update(
    { "site_id": "xxx" },
    { "$addToSet": { "docs": { "title": "d", content: "d", "lang": "de" } } },
    { "multi": true }
)

Or even without the logic there and just checking for presence:
db.foo.update(
    { "site_id": "xxx", "docs.lang": { "$ne": "de" } },
    { "$push": { "docs": { "title": "", "content": "", "lang": "de" } } },
    { "multi": true }

)
Which in that last case would result in this:
{
    "_id" : ObjectId("53c936265117367f5ff2038b"),
    "site_id" : "xxx",
    "docs" : [
            {
                    "title" : "a",
                    "content" : "a",
                    "lang" : "ru"
            },
            {
                    "title" : "b",
                    "content" : "b",
                    "lang" : "en"
            },
            {
                    "title" : "",
                    "content" : "",
                    "lang" : "de"
            }
    ]
}
{
    "_id" : ObjectId("53c936265117367f5ff2038c"),
    "site_id" : "xxx",
    "docs" : [
            {
                    "title" : "c",
                    "content" : "c",
                    "lang" : "ru"
            },
            {
                    "title" : "d",
                    "content" : "d",
                    "lang" : "de"
            }
    ]
}

So the choice is there to either "handle" things differently or otherwise just change your schema to accommodate the sort of updates you want to do atomically.

A: Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:
This way, we can move field checks within the update stage rather than within the match stage, thus making it a one-pass update:
// { site_id: "xxx", title: { ru: "a", en: "b" }, content: {} }
// { site_id: "xxx", title: { ru: "c", de: "d" }, content: { ru: "c" } }
db.collection.updateMany(
  { site_id: "xxx" },
  [{ $set: {
    "title.de": { $cond: [ { $not: ["$title.de"] }, "", "$title.de" ] },
    "content.ru": { $cond: [ { $not: ["$content.ru"] }, "", "$content.ru" ] }
  }}]
)
// { site_id: "xxx", title: { ru: "a", en: "b", de: "" }, content: { ru: "" } }
// { site_id: "xxx", title: { ru: "c", de: "d"         }, content: { ru: "c" } }

*

*The first part { site_id: "xxx" } is the match query, filtering which documents to update.

*The second part [{ $set: { ... } }] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias of $addFields. The rest of this stage checks with $cond if the title.de exists, and if yes, then keep it as it is, or otherwise create it as an ''.

A: there is a update field operator $setOnInsert which meets your requirement. Please read the documents here: https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/#up._S_setOnInsert

A: @nutlike's answer does solve the issue, however, if you would like to update multiple fields on the item it will require many database operations. In short, what you want is not exactly possible.
If your doc has more updates to do than you'd like to do one at a time (any greater than 2, IMO), then you should just get the document, update the fields and then save it. This is what I do on a couple of OAuth user creating/updating routes.

A: As update query is deprecated use updateOne or updateMany as per your requirement.
updateMany to update all at once.
db.foo.updateMany({'title.de': {$exists : false}}, {$set: {'title.de': ''}})

A: I have a solution for one particular case, but may be it helps someone.
My case was:
Update several fields, among which was a field that had to be updated only once (lets call it "Date_of_first_update").
> db.test.find();
{ "_id" : ObjectId("57f298fdeb30478a033c70e4"), "a" : "1", "b" : "2" }

First update:

> db.test.updateOne({ "_id" : ObjectId("57f298fdeb30478a033c70e4")},
  {$set: {a: 100, b: 200 }, $min : {'Date_of_first_update' : (new Date())  }});

Result: 'a', 'b' updated, 'Date_of_first_update' is set.

{ "_id" : ObjectId("57f298fdeb30478a033c70e4"), "a" : 100, "b" : 200, "Date_of_first_update" : ISODate("2016-10-03T**17:47:43**.570Z") }

Second update:

> db.test.updateOne({ "_id" : ObjectId("57f298fdeb30478a033c70e4")},
  {$set: {a: 400, b: 800 }, $min : {'Date_of_first_update' : (new Date()) }});

Result: 'a', 'b' updated, 'Date_of_first_update' left unchanged, as I needed!!!

{ "_id" : ObjectId("57f298fdeb30478a033c70e4"), "a" : 400, "b" : 800, "Date_of_first_update" : ISODate("2016-10-03T**17:47:43**.570Z") }

A: // Add a field with some values in all documents if the field does not exist,
Here, I am saying that adding lob: 'Marine' if the lob field is not there in all documents.
db.collections.updateMany({'lob': { $exists: false }}, { $set: { lob: 'Marine'}});


text:
Q: What's the correct way to update a @ViewChild component on app load I have a small Angular app which has a storage logic that should update a child component if there's something in it.
The way it's today is like the following:
export class HomeComponent implements AfterViewInit {
    @ViewChild(WidgetComponent)
    private widgetChild: WidgetComponent;

    constructor(private storageService: StorageService) {}

    ngAfterViewInit(): void {
      const widget = this.storageService.loadData();
      this.widgetChild.updateData(widget);
      this.cdr.detectChanges(); // Prevents error
    }
}

This logic is working fine as it's today but if I remove the line with comment I get the error:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '[object Object]'.

This solution doesn't seem to be a good one to me, can somebody help me improve it?


text:
Q: Animations not working outside of parent component in React 16.13.1 I'm facing a problem where if I separate my child components outside my main component, my keyframe animations stop working.
The animation in question is a simple expanding container, which plays every time the content of a container changes.
My Abouts.js (main component):
const About = React.forwardRef((props, ref) => {
  const [ topic, setTopic ] = useState('react')
  const [ logo, setLogo ] = useState(topicsList[0].logo)
  const [ active, setActive ] = useState(0)

  ...

  const handleTopicChange = (topic, index, logo) => {
    setTopic(topic.toLowerCase())
    setLogo(logo)
    setActive(index)
  }

  //Creates buttons from a list of topics and adds the functionality to switch between them
  const createButtons = () =>
    topicsList.map((topic, index) => (
      <Button
        key={topic.name.toLowerCase()}
        onClick={() => handleTopicChange(topic.name, index, topic.logo)}
        active={active === index}
      >
        {topic.name.toLowerCase().includes('csharp') ? 'C#' : topic.name.toUpperCase()}
      </Button>
    ))

  ...

  //Renders the Container with content based on the topic hook which gathers content from an i18next file
  const Topic = props => {
  const value = props.value.includes('c#') ? 'csharp' : props.value
  return (
    <TopicContainer>
      <TopicTitle
        style={{ textAlign: 'left' }}
        $color={props.theme === dark ? dark.colors[value] : light.colors[value]}
      >
        {t(`titles.about.${value}`)}
      </TopicTitle>

    </TopicContainer>
    )
   }

   return(
   ...
   {createButtons()}
   <Topic theme={props.theme} value={topic}>
      {t(`paragraphs.${topic}`)}
   </Topic>
   ...
)
}

My styles.js (Styled Components file):
...

const expand = keyframes`
  from {
    transform: scale(0.5);
  }
  to {
    transform: scale(1);
  }
`

const expandAnimation = css`
  animation: css`${expand} 300ms ease`;
`

const blogText = css`
  font-size: ${props => props.theme.fonts.size.xs};
  font-weight: ${props => props.theme.fonts.weight.normal};
  color: ${props => props.theme.colors.neutralLight};
  @media ${device.greaterThan.laptopLMin} {
    font-size: ${props => props.theme.fonts.size.md};
  }
`

export const TopicContainer = styled.div`
  ${expandAnimation};
  ${blogText};
  width: 85%;
  margin: 0 auto;
  margin-bottom: 2rem;
  & div {
    width: 100%;
    float: left;
  }
  & p {
    width: 100%;
    @media ${device.greaterThan.laptopLMin} {
      width: 70%;
    }
  }
`
...

Now, everything works perfectly fine, and as intended. The problem is that when I move the child (Topic) component outside of its parent (About) component, my animations stop working (except for the first render a.k.a. when you refresh the page). Even though the content inside the container changes just as before, and I'm not getting any negative messages in my console.
I would have specified that I'm using Styled Components, but I tried to create a css file for the same purpose, in case the problem had something to do with Styled Components, but the result was the same. Everything works perfectly fine until my child moves out...
Please let me know in case there is a lack of information.

A: For you animation to run you need to pass either props.main or props.signature to down to styled component
const expandAnimation = css`
  animation: ${props => (props.signature || props.main ? 'none' : css`${expand} 300ms ease;`)};
`const expandAnimation = css`
  animation: ${props => (props.signature || props.main ? 'none' : css`${expand} 300ms ease;`)};
`

Your TopicContainer should be;
let isSignature=true;
let isMain=true;

   <TopicContainer signature={isSignature} main={isMain}>
      <TopicTitle
        style={{ textAlign: 'left' }}
        $color={props.theme === dark ? dark.colors[value] : light.colors[value]}
      >
        {t(`titles.about.${value}`)}
      </TopicTitle>

    </TopicContainer>

Since I did not find any reference to the signature or main i am creating dummy variables to pass as prop.


text:
Q: Содержит ли словарь хотя бы одно слово из строки/списка Есть строка или список: 'i like girls'   или   ['i', 'like', 'girls']
И словарь со словами {'i': None, 'like': None, 'birds': None}
Есть ли быстрый способ проверить, есть ли хотя бы одно слово из строки/списка в этом словаре? В идеале за О(1)

A: Можно решить вот так.
my_list = ['i', 'like', 'girls']
my_dir = {'i': None, 'like': None, 'birds': None}

s1 = set(my_list)  # Множество различных слов в списке
s2 = set(my_dir.keys())  # Берем множество ключей словаря
if len(s1 & s1) > 0:  # Если размер пересечения больше 0 - то такое слово есть
    print('есть такое слово')
else:
    print('нет такого слова')

A: list_of = ['i', 'like', 'girls']
dict_of = {'i': None, 'like': None, 'birds': None}

Вариант 1:
set(list_of) & set(dict_of)
>>> {'like', 'i'}

Вариант 2:
[i for i in list_of for j in dict_of if i == j]
>>> ['i', 'like']


text:
Q: How to obtain the primary key of the selected row in bs_grid I'm using bs_grid to display a list of company names.  Each company name has a GUID identifier.  I define the grid as such:
$(function() {
  $('#grid1').bs_grid({
    ajaxFetchDataURL: 'CompaniesList.asmx/GetCompanies',
    row_primary_key: 'CompanyUID',
    useFilters: false,
    usePagination: false,
    columns: [{
      field: 'CompanyUID',
      visible: 'no'
    }, {
      field: 'CompanyName',
      header: 'Company Name'
    }],
    sorting: [{
      sortingName: 'CompanyName',
      field: 'CompanyName',
      order: 'ascending'
    }],
    onRowClick: function(event, data) {
      var selectedIds = $('#grid1').bs_grid('selectedRows', 'get_ids');
      // here I need the primary key of the row, not the row index:
      location.href = 'CompanyDetails.aspx?CompanyUID=' + selectedIds[0];
    }
  });
});

I've poured over the bs_grid js source and it's not jumping out at me how to obtain the data for a row based on the row_id.  How should I go about getting this information?

A: OK, bs_grid expects the primary key to be an int.  This results in the GUID not being read correctly and data.row_id being "random".
To solve this, I had to add a row counter, starting at 1, to my results that I then use to get the UID of the hidden column for CompanyUID.
$(function() {
                $('#grid1').bs_grid({
                    ajaxFetchDataURL: 'CompaniesList.asmx/GetCompanies',
                    row_primary_key: 'RowID',
                    useFilters: false,
                    usePagination: false,
                    columns: [
                        { field: 'RowID', visible: 'no'},
                        { field: 'CompanyUID', dataClass: 'td_code hidden', headerClass: 'td_code hidden'},
                        { field: 'CompanyName', header: 'Company Name'}
                    ],
                    sorting: [
                        { sortingName: 'CompanyName', field: 'CompanyName', order: 'ascending'}
                    ],
                    onRowClick: function(event, data) {
                        if(data.row_status == 'selected')
                        {
                            var row =  $('[id^=tbl_grid1_tr_]:eq(' + data.row_id + ')');
                            var uid = row[0].childNodes[0].innerText;
                            location.href = 'CompanyDetails.aspx?CompanyUID=' + uid;
                        }
                    }
                });
            });


text:
Q: Overview of observations that meet conditions I have a dataframe of 20.000 observations based on 130 participants. There are several observations from each participant.
I'm calculating the participants' response time.
The average is 25.01.
I want to identify the participants that have an average response time >= 10 seconds.
I can't get my head around this. The ideal output would be a matrix/list of names and their corresponding average response time (but only if it's below 10 seconds).

A: Something like:
library("dplyr")
my_data %>% group_by(subject) %>%
        summarise(avg_response=mean(response_time)) %>%
        filter(avg_response>=10)

You could also use aggregate() and subset() from base R.


text:
Q: Materialize css modal not showing I've got a following code:
<?php if(UserModel::getInstance()->isLoggedIn()) { ?>
    + Add New Topic

<?php } ?>

<?php if(UserModel::getInstance()->isLoggedIn()) { ?>

Add New Topic

            asdf

When I click on a button nothing is showed up. No errors were triggered in javascript console. What could be the problem?

A: You need to initialise the modal plugin before you can use it. Add this to your JS file:
$(document).ready(function() {
    $('.modal').modal();
});


text:
Q: Is coercion different from "coercion polymorphism"?
*

*If just coercion is a kind of polymorphism, then coercion happens even in non-oops languages. So, i want to know whether the term "coercion" is different from "coercion polymorphism"?

*If coercion happens at the time of function call where the type of the argument passed in a function call coerces to the type of the parameter in the function definition and if the same happens with an operator, then we call it "coercion polymorphism". Is this statement, correct? If so, whether such a thing happens in language C(non-oops language)?

*In Java, BOXING concept is an example of coercion. Can that be considered as "coercion polymorphism" too?

*Passing a subclass object reference to a superclass object reference during a method call can also be considered as "coercion polymorphism"?(I read somewhere). In that case upcasting and coercing polymorphism means the same in a sense. So, is that correct?


text:
Q: What are the correct headers for this rest request? I have a Rest server in java which has this as the post method handler
@POST
@Path("{add}")
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void newTodo(@FormParam("id") Integer id, @FormParam("name") String name, @FormParam("mark") Integer mark, @Context HttpServletResponse servletResponse) throws IOException {
    Student student = new Student(name, mark, id);
    StudentDao.instance.getModel().put(id, student);
    servletResponse.sendRedirect("../create_student.html");
}

And I'm sending a request through the following
$service_url = "http://localhost:8080/RestWS/rest/Students/add";
$curl = curl_init($service_url);
$curl_post_data = array(
        "name" => "juan",
        "mark" => "10",
        "id" => "10"
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_response = curl_exec($curl);
//print_r (curl_getinfo($curl));
//print_r (curl_errno($curl));
//print_r (curl_error($curl));
curl_close($curl);
print_r($curl_response);

I'm getting a HTTP 415 - Unsupported Media Type error response, I'm guessing that it's a problem with the headers, but after trying different stuff and looking it up online I've come to nothing... I've tried passing it with json headers, XML/HTML and changing the mediatype at the server, but I don't seem to be able to get it right, which is the correct set of headers I should use here?


text:
Q: How to do filter for a field generated by using MAX(CASE WHEN ... END)? I have retrieved data successfully using the query below from a data in January until May generating every first and second purchase for each customer.
SELECT
    MAX(CASE WHEN row_num = 1 THEN month END) AS month,
    customer_id,
    1 AS row_num,
    DATE_DIFF(MAX(CASE WHEN row_num = 2 THEN verified_date END),
              MAX(CASE WHEN row_num = 1 THEN verified_date END), DAY) AS difference
FROM yourTable
GROUP BY
    customer_id;

Now, I would like to filter the month to get all the user doing FIRST transaction in Jan - Apr, and doing SECOND transaction anytime (Jan - May) and try this query:
SELECT
    MAX(CASE WHEN row_num = 1 AND month IN (1,2,3,4) THEN month END) AS month,
    customer_id,
    1 AS row_num,
    DATE_DIFF(MAX(CASE WHEN row_num = 2 THEN verified_date END),
              MAX(CASE WHEN row_num = 1 THEN verified_date END), DAY) AS difference
FROM yourTable
GROUP BY
    customer_id;

The query successfully runs, however, it generated month 1 2 3 4, and NULL in the month field.
Why there's NULL in it?
Thank you

A: Assuming there's a row_num in yourTable that orders transactions of each customer chronologically, MAX(CASE WHEN row_num = 1 AND month IN (1,2,3,4) THEN month END) AS month, will end up null when the row with row_num = 1 has a month different from 1, 2, 3, or 4, i.e. "first transaction is in May".
To filter, use HAVING MAX(CASE WHEN row_num = 1 AND month IN (1,2,3,4) THEN month END) is not null.


text:
Q: Windows batch file to log in to remote server and kill processes? I am a QA Engineer running automated UI tests overnight, distributed over several VM's. However, sometimes a job might hang and it causes a major headache. Can I write a batch file to log into the remote server (headless would be best, since the job itself will run on a master VM) and kill the process that I need to, and then log back out? I have NO experience writing Windows batch scripts. Also - I'm using a service account, so no need to hide the password.  Thanks!

A: This will kill any process whose executable is "notepad.exe" on the remote machine REMOTE_HOST (so long as you are an admin on the machine)
taskkill.exe /S REMOTE_HOST /FI "ImageName EQ notepad.exe"

See taskkill.exe /? for more info.

A: it's better you Use powershell script to Invoked-command because has switch named Credential on machine for authentication
see example
$s = New-PSSession -ComputerName dc -Credential dc\jack
Invoke-Command -Session $s -ScriptBlock {stop-process -name notepad}


text:
Q: How to show a png image in Gtk3 with Python? First of all, it is important to mention that I'm learning Python and Gtk+ 3, so I'm not an advanced programmer in these languages.
I'm trying to make a graphical interface in Gtk3 for a Python script that creates a png image, and I'd like to display it, but the PyGobject documentation is so scarce that I haven't found a way to do that. So far, my interface looks like this:

The buttons and text entries are arranged in a grid, and I'd like to keep empty the big space (represented by the big button) to the right until the script finishes building the image, and then show it in that area. The code is here.
Is there a way to do that using Python in Gtk3?
Thanks in advance,
Germán.
EDIT
Taking a look at the demos pointed out by @gpoo I discovered the Frame widget, and I implemented it in my GUI. This is how it looks like:

Inside the window class, I add the Frame to the grid:
self.frame_rgb = Gtk.Frame(label='RGB image')
self.frame_rgb.set_label_align(0.5, 0.5)
self.frame_rgb.set_shadow_type(Gtk.ShadowType.IN)
self.grid.attach_next_to(self.frame_rgb, self.label_img_name,
                         Gtk.PositionType.RIGHT, 3, 8)

I also connect the Run button to a callback function, so that when I click on it, my script creates and then displays the png image:
self.button_run = Gtk.Button(stock=Gtk.STOCK_EXECUTE)
self.button_run.connect('clicked', self.on_button_run_clicked)
self.grid.attach_next_to(self.button_run, self.entry_b_img,
                         Gtk.PositionType.BOTTOM, 1, 1)

Finally, my callback function is (no calculations yet, only render the image to the Frame for testing purposes):
def on_button_run_clicked(self, widget):
    self.img = Gtk.Image.new_from_file('astro-tux.png')
    self.frame_rgb.add(self.img)

but I got the following error when I click the Run button:

(makeRGB.py:2613): Gtk-WARNING **: Attempting to add a widget with
  type GtkImage to a GtkFrame, but as a GtkBin subclass a GtkFrame can
  only contain one widget at a time; it already contains a widget of
  type GtkImage

Any help is appreciated!

A: You can use Gtk.Image.  If you generate a file, you could use:
img = Gtk.Image.new_from_file('/path/to/my_file.png')

and add img to the container (GtkGrid in your case).  Or, if you already have the Gtk.Image there, you can use:
img.set_from_file('/path/to/my_file.png')

Instead of ...from_file you can use from_pixbuf, and you can create a Gdk.Pixbuf from a stream.
In general, you can use the documentation for C and change the idiom to Python.  Also, you can check the demos available in PyGObject, in particular, the demo for handling images.


text:
Q: How to fix these error "Implicit declaration of function is invalid in C99" and "Conflicting types" in .c file in Xcode objective-C? Actually iam importing .C file library in objective-c.I have fixed most of errors.but below two errors iam not able to resolve..
The first one is : "Implicit declaration of function 'read_binary_profile' is invalid in C99"
The second one is : "Conflicting types for 'read_binary_profile'"
Can you please help to resolve this issuse.
Below is code
    #include <math.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <time.h>
    #define __EXTRA_CMDL_SERVICE
    #define __TEXT_ERRORS_PRINT

    #include "profile.h"
    #include "vcp-api.h"
    #define PROFILE "/vendor/etc/profile.bix"
    extern char* vcp_errorv(err_t err);
    vcp_profile_t* read_binary_profile(void* pmem, int allocate);

    vcp_profile_t *p;
    void *b_profile ;
    mem_reg_t reg[NUM_MEM_REGIONS];
    void *smr[NUM_MEM_REGIONS];
    #define FRAME_VCP  80//120      //  Frame handle lenght 120: 7.5ms 16Bit, 16K  so defined here,   but buffer lenght is 120* size of short
    short *input_frame[4];
    short *spk[2];
    short aec[FRAME_VCP] ;   //¥À¥¶»Áπ˚√ª"–ACE , ø…"'"√ø' ˝◊È

    void alango_vcp_init()
{
    unsigned int smem = 16000; //1792;
    void *mem;
    err_t err;
    FILE *fp, *fp2 ;
    int flen , fsize ;

    fp=fopen(PROFILE,"rb");
    fseek(fp,0,SEEK_END);
    flen=ftell(fp);
    b_profile=(char *)malloc(flen);
    if(b_profile==NULL){
        fclose(fp);
        printf("Alango VCP Can't find profile configuration.\n");
        return ;
    }
    if(fp==NULL){
        printf("Alango VCP Can't open profile configuration.\n");
        return ;
    }
    fseek(fp,0,SEEK_SET);
    fsize=fread(b_profile,1,flen,fp);
    if(fsize!=flen){
        printf("read file error , read len ==== %d , return size ===%d", flen, fsize);
        fclose(fp);
        return;
    }
    p=read_binary_profile(b_profile,0);
    printf("alango_vcp_init 111 \n");
    err = vcp_check_profile(p);
    printf("alango_vcp_init 222 \n");
    if (err.err){
         if (err.err == ERR_INVALID_CRC)
             printf("alango_vcp_init Profile error: Invalid CRC!");
         else
             printf("alango_vcp_init Profile error: vcp_errorv(err) \n");
    }
    smem = vcp_get_hook_size();
    mem = malloc(smem);
    printf("alango_vcp_init 333 \n");
        vcp_get_mem_size(p, reg, mem);
        printf("alango_vcp_init 444 \n");
    free(mem);

    input_frame[0] = malloc(FRAME_VCP*sizeof(short));    //  5ms 16K 16bit buffer
    input_frame[1] = malloc(FRAME_VCP*sizeof(short));    //  5ms 16K 16bit buffer
    input_frame[2] = malloc(FRAME_VCP*sizeof(short));    //  5ms 16K 16bit buffer
    input_frame[3] = malloc(FRAME_VCP*sizeof(short));    //  5ms 16K 16bit buffer
    spk[0] = malloc(FRAME_VCP*sizeof(short));    //  5ms 16K 16bit buffer
    spk[1] = malloc(FRAME_VCP*sizeof(short));    //  5ms 16K 16bit buffer
    for (int i = 0; i < NUM_MEM_REGIONS; i++){
        reg[i].mem = smr[i] = (void *)malloc(reg[i].size);
        printf("alango_vcp_init I need %d bytes of memory in memory region %d to work.\n", reg[i].size, i + 1);
    }
    err = vcp_init_debug(p, reg);
    if (err.err == ERR_NOT_ENOUGH_MEMORY)
    {
        printf("alango_vcp_init %d more bytes needed in region %d!\n", -reg[err.pid].size, err.pid);
    }
    else if (err.err == ERR_UNKNOWN)
    {
        printf("alango_vcp_init vcp_init_debug() returns UNKNOWN error\n!");
    }
    else if (err.err != ERR_NO_ERROR)
    {
        printf("alango_vcp_init vcp_init_debug() returns error __text_error[err.err], err.pid!\n");
    }
}

    vcp_profile_t * read_binary_profile(void *pmem, int allocate)
    {
       vcp_profile_t *prof;//base_profile();
       prof= malloc(sizeof(profile_tab));
    }

After solving that errors by declaring method its showing below error
ld: warning: ignoring file /Users/yq12462/Desktop/ImportingCfileDemo/ImportingCfileDemo/libvcp_32.a, building for iOS-arm64 but attempting to link with file built for unknown-unsupported file format ( 0x21 0x3C 0x61 0x72 0x63 0x68 0x3E 0x0A 0x2F 0x20 0x20 0x20 0x20 0x20 0x20 0x20 )
ld: warning: ignoring file /Users/yq12462/Desktop/ImportingCfileDemo/ImportingCfileDemo/libvcp_64.a, building for iOS-arm64 but attempting to link with file built for unknown-unsupported file format ( 0x21 0x3C 0x61 0x72 0x63 0x68 0x3E 0x0A 0x2F 0x20 0x20 0x20 0x20 0x20 0x20 0x20 )
Undefined symbols for architecture arm64:
  "_vcp_check_profile", referenced from:
      _alango_vcp_init in AlangoBasic.o
  "_vcp_get_hook_size", referenced from:
      _alango_vcp_init in AlangoBasic.o
  "_vcp_get_mem_size", referenced from:
      _alango_vcp_init in AlangoBasic.o
  "_vcp_init_debug", referenced from:
      _alango_vcp_init in AlangoBasic.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

A: "Implicit declaration of function" means that no function declaration was visible to the compiler when you called the function. This is no longer allowed in C since the C99 standard.
Apparently upon facing such a function call, your compiler still tries to make an old C90 "implicit int" out of it, meaning that upon spotting this p=my_read_binary_profile(b_profile,0), it will treat the function as if it was declared as int my_read_binary_profile (int, int) and generate machine code accordingly, which is obviously wrong.
This gives the second error, the "implicit int" crap doesn't match the correct function definition vcp_profile_t * my_read_binary_profile(void *pmem, int allocate), hence conflicting types.
Solve this by adding a function declaration prototype on top of the file:
vcp_profile_t* my_read_binary_profile(void* pmem, int allocate);


text:
Q: A column has value like {10,20,30}, need to find the sum,avg,max and min of the value using SQL query I need to find the sum,avg,max and min of a column:
Table_ab
col1 | col2   | col3

ab   |10 am   | {10,20,30}

ab   |10.15am | {20,30,40}

Expected result
col1  | col2    | col3      | sum_col3 | avg_col3 | max_col3 | min_col3

ab    |10 am    |{10,20,30} |60        |20        |30        |  10

A: Not the best data model, as you've already been told. Anyway: one (usual) option is to  split values in col3 into rows to perform those calculations. Here's how (sample data in lines #1 - 4; query begins at line #6):
SQL> with table_ab (col1, col2, col3) as
  2    (select 'ab', '10 am'  , '10,20,30' from dual union all
  3     select 'ab', '10.15am', '20,30,40' from dual
  4    ),
  5  -- split col3 into rows
  6  temp as
  7    (select col1,
  8            col2,
  9            col3,
 10            to_number(regexp_substr(col3, '[^,]+', 1, column_value)) val
 11     from table_ab cross join
 12       table(cast(multiset(select level from dual
 13                           connect by level <= regexp_count(col3, ',') + 1
 14                          ) as sys.odcinumberlist))
 15    )
 16  -- aggregate!
 17  select col1,
 18         col2,
 19         col3,
 20         sum(val) sum_col3,
 21         avg(val) avg_col3,
 22         max(val) max_col3,
 23         min(val) min_col3
 24  from temp
 25  group by col1, col2, col3;

CO COL2    COL3       SUM_COL3   AVG_COL3   MAX_COL3   MIN_COL3
-- ------- -------- ---------- ---------- ---------- ----------
ab 10.15am 20,30,40         90         30         40         20
ab 10 am   10,20,30         60         20         30         10

SQL>


text:
Q: What's that app or library that allows one to add functionality to cocoa apps? I recall reading about an application or library that allows to add some functionality to Cocoa apps.
I found it when searching for an application for using mouse gestures in Finder and applications other than browsers, but I didn't pay too much attention to it because I didn't know Objective-C or Cocoa at the time.
Do you have any idea of which one could it be?

A: Perhaps you're thinking of SIMBL?


text:
Q: Image upload says its working but no file Im using a tutorial to upload imageas to my server only I can't seem to get it to actually place the image in my folder on my server?
I have the following...
if (isset($_POST['submit'])) {

$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "
";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "
";
    echo "Type: " . $_FILES["file"]["type"] . "
";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB
";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
";

    if (file_exists("/upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "/upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "/upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }

  };

Can anybody see whats wrong? As ive said i receive a success message yet nothing seems to appear in the correct folder...

html
<form action="#" method="post" enctype="multipart/form-data">
Filename:
<input type="file" name="file" id="file">

<input type="submit" name="submit" value="Submit">
</form>

Array
(
[file] => Array
    (
        [name] => Screen shot 2012-12-16 at 8.40.49 PM.png
        [type] => image/png
        [tmp_name] => /tmp/phpVr7glY
        [error] => 0
        [size] => 6289
    )

)

A: This looks like a path-problem to me.
Have you tried changing the path to "upload/":
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);

And ofcourse that the name is upload and not uploads or something like that.
Relative and absolute paths can be somewhat tricky, and to be honest I don't really recall how for example apache/php handles absolute paths.
Also this is asuming that you're on Linux and using apache, if you're on windows and using ISS I recall having problems with the temp-folder. Howvever I don't have a solution for you.
Okay so after looking at this for a while and finally testing it. It seems that calling end on the returnvalue of explode is causing all the problems. So if you change it to something like this it should work:
$parts = explode(".", $_FILES["file"]["name"]);
$extension = $parts[sizeof($parts)-1];

The error output was this:

Strict standards: Only variables should be passed by reference in:

So look over your error-reporting and try installing a debugger like xdebug.


text:
Q: Handle multiple pre-commit hooks I have a need to use multiple pre-commit hook scripts. Not sure how to handle them. Should all of them be combined into one single large pre-commit script ? if not, how to handle multiple pre-commit scripts ?

A:
Should all of them be combined into one single large pre-commit script ?

Yes and no: you can only declare one pre-commit script, so this script should be in charge to:

*

*call the actual pre-commit scripts

*chose an order for those scripts to be called.

So:

*

*one pre-commit script

*calling multiple scripts, each one allowing or not (with their exit status) the commit to proceed.

A: You can use a delegating script that only calls others scripts (subhooks):
https://gist.github.com/carlos-jenkins/89da9dcf9e0d528ac978311938aade43
Usage:
Make your building system to create a symbolic link in the Git hooks directory to this script with the name of the hook you want to attend.
For example, pre-commit.
This hook will then execute, in alphabetic order, all executables files
(subhooks) found under a folder named after the hook type you're attending
suffixed with .d.
For example, pre-commit.d.
How it could look:
.git/hooks/
 |_ pre-commit -> ../../tools/git/multihooks.py
 |_ pre-commit.d/
    |_ 01-cpp_coding_standard
    |_ 02-python_coding_standard
    |_ 03-something_else

This requires Python3, but you could came with something similar using other technologies.

A: You can only have one pre-commit script, so you'll have to use that one to call multiple other scripts.
Create an executable /PATH/TO/GIT/.git/hooks/pre-commit file, with these contents:
#!/bin/bash

cd "$(dirname "$0")/pre-commit.d"

for hook in *; do
    bash $hook
    RESULT=$?
    if [ $RESULT != 0 ]; then
        echo "pre-commit.d/$hook returned non-zero: $RESULT, abort commit"
        exit $RESULT
    fi
done

exit 0

Then put all your pre-commit scripts inside a new pre-commit.d/ directory.
/PATH/TO/GIT/.git/hooks/
└── pre-commit.d
    └── SCRIPT1
    └── SCRIPT2

Make sure the script files are executable. Remember that the working dir will be /PATH/TO/GIT/.git/hooks/pre-commit.d/ by default inside the scripts.


text:
Q: Material UI Autocomplete list items have padding I can't get rid off I have this Autocomplete component in a React app as:
 <Autocomplete
    placeholder="Enter Suburb"
    id="custom-input-demo"
    options={Suburbs.map((suburb) => suburb.suburb)}
    onChange={(event,value) => addSuburb(value)}
    onFocus={()=>scrollToSuburb()}
    defaultValue={customer.suburb ? customer.suburb : ''}
    renderInput={(params) => (
    <div ref={params.InputProps.ref}>
      <input style={{ width: 300 }} placeholder="Type.."  type="text" {...params.inputProps} />
    </div>
        )}
        />

It appears with huge padding on the items as:
Render screenshot
I tried every possible way to alternate this style but wasn't able to.
What is the best way to style the Material UI react Autocomplete list?


text:
Q: Why am I getting "Unsupported binding form" error when implementing protocol in clojure? I am trying to implement a protocol with a record in a clojure program I'm writing. the error I'm getting is "Unsupported binding form".
    (defprotocol query-rows
        (query-text [table])
        (trans-cols [table rows])
        (set-max [table] [table id]))

    (defrecord Submissions [data max-id]
        query-rows
        (query-text [table]
            (gen-query-text "SubmissionId" "Valid" "Submission"))
        (trans-cols [table rows]
            (let
                [trans-data
                    (->>
                        rows
                        (trans-col #(if % 1 0) :valid :valid_count)
                        (trans-col #(if % 0 1) :valid :non_valid_count)
                        (trans-col format-sql-date :createdon :date))]
                (assoc table :data trans-data)))
        (set-max
            ([table]
                (when-let [id (gen-get-max "SubmissionAgg2")]
                (assoc table :max-id id)))
            ([table id] (assoc table :max-id id))))

The "set-max" function is what's throwing the error. I have a feeling I'm trying to use multiple arity incorrectly. Does anyone know what I'm doing wrong?

A: You have correctly diagnosed the problem. You'll need to follow the examples at http://clojure.org/protocols and define the multiple arities of your set-max method separately in the body of defrecord.
...
(set-max [table] ...)
(set-max [table id] ...)
...


text:
Q: "NETWORK SERVICE" account seems highly privileged on my Windows 2008 SP2 (standard) installation I have a fresh install of Windows 2008 Standard in a Godaddy dedicated hosting account. I upgraded the installation to SP2.
Several apps are running in IIS, in application pools using "NetworkService" as the pool identity. I am accessing the apps anonymously over the internet.
Unlike in Windows 2003, this seems to be a highly privileged account. I find that my applications have read access to every directory on the disk. I verified this by creating a simple app in IIS that read the contents of an arbitrary directory and printed the contents of the first text file it encountered. This worked for every folder I tried it on, including C:\Windows\System32. Attempts to write failed, however.
My gut is telling me this can't possibly be the correct behavior, but my Win2k8-fu is not strong.
Is what I'm seeing normal? Should I be running the application pools using a different identity?

A: What you are seeing is normal. The "Network Service" account is equivalent to the local SYSTEM account, which is a very privileged account. IIRC, Network Service is different than Local Service or System in that in a Domain context it can access resources on remote computers; rights assigned to the machine account limit what it can see on the Domain.
The account used by an IIS7 application is defined by the account used by the supporting Application Pool.

The "ApplicationPoolIdentity" is a new feature of IIS7. For details on setting rights for that, there is a serverfault question that covers this (link). The safest method is to create a custom user on that box just for the Application Pool, and assign rights to that user.
To get to the above drop-down screen:

*

*Open IIS Manager.

*Open the application-pools.

*Select the app pool in question.

*On the right-side frame, select "Advanced Settings"

*Under "Process Model" you will find "Identity". This is where the dropdown is.


text:
Q: How to add an attribute to a collection marked with XmlArrayAttribute? I have an XML of the format like here: http://pastie.org/1311506 (not inserting it here because comment parser deletes tags).
This XML is serealized/deserialized using the following code:
[XmlRoot("products")]
public class Products
{
    [XmlElement("label")]
    public string Label { get; set; }

    [XmlArray("cars")]
    [XmlArrayItem("car")]
    public Car[] Cars { get; set; }
}

public class Car
{
    [XmlAttribute("name")]
    public string Name { get; set; }
}

...

var products = new Products
                   {
                       Label = "1",
                       Cars = new[]
                                  {
                                      new Car {Name = "BMW"},
                                      new Car {Name = "Volvo"}
                                  }
                   };
var serializer = new XmlSerializer(typeof(Products));
var writer = new StringWriter();
serializer.Serialize(writer, products);
Console.WriteLine(writer);

I need an additional attribute to <cars> node called type (like here: http://pastie.org/1311514). How can I do it?
In other words, how to define data classes (Products and Car and maybe others if necessary) in order to parse XML of the format shown in the second pastie link?

A: There's no easy way to do that, because for collections the XmlSerializer ignores all members, it only serializes the items of the collection. However, if you only want to deserialize it and ignore the type attribute, it's not an issue : unknown attributes will just be ignored.
If you need to get the value of type, you can declare a class that is not a collection, but contains the collection. Something like that:
public class Cars
{
    [XmlElement("car")]
    public Car[] Items { get; set; }

    [XmlAttribute("type")]
    public string Type { get; set; }
}

In your Products class, just declare the Cars property of type Cars with just a XmlElement attribute:
[XmlRoot("products")]
public class Products
{
    [XmlElement("label")]
    public string Label { get; set; }

    [XmlElement("cars")]
    public Cars Cars { get; set; }
}


text:
Q: How to make api request to Github repository using restapi? I am new to C# and .Net and I am struggling to understand this issue that I have. I feel like what I have is enough but not sure myself. SO if someone can just review the codes that I have below and tell me were to correct and what is wrong.Thank you
This is my Model Class
namespace github_project.Models
{
    public class GithubItem
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string FullName { get; set; }
        public string City { get; set; }
        public string ProjectName { get; set; }
        public string Commits { get; set; }
        public double Rating { get; set; }
        public string AvatarUrl { get; set; }
    }
}

and this is my database context
namespace github_project.Database
{
    public class GithubContext : DbContext
    {
        public DbSet<GithubItem> Github { get; set; }
        public GithubContext(DbContextOptions<GithubContext> options) : base(options)
        {
        }

        public GithubItem ItemsList()
        {
            List<GithubItem> build = Build();
            GithubItem itemsList = JsonConvert.DeserializeObject<GithubItem>(build);
            return itemsList;
        }

        public List<GithubItem> Build()
        {
            var getData = GetGithubData();
            return System.Text.Json.JsonSerializer.Deserialize<List<GithubItem>>(getData);
        }

        private string GetGithubData()
        {
            string username = "**test**";
            var url = "https://api.github.com/users/" + username + "/repos?page=1";

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/json";
            request.UserAgent = "TestApp";

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                return reader.ReadToEnd();
            }
        }

        public List<GithubItem> getGithub() => Github.Local.ToList<GithubItem>();
    }
}

finally this is my controller
[HttpGet("/github")]
public GithubItem GetAll()
{
    return _context.ItemsList();
}

I am making a request to github in order to get all the data and use it in my request. I am getting an here here of converting Collection.List to String on this method below:
public GithubItem ItemsList()
{
    List<GithubItem> build = Build();
    GithubItem itemsList = JsonConvert.DeserializeObject<GithubItem>(**build**);
    return itemsList;
}

Can someone help me and and someone tell me what is wrong here??? Thank you

A: You cannot deserialize an object or convert an object from List<GithubItem> to single GithubItem. That is what you are doing.
As you can see, you have build:
List<GithubItem> build = Build();

This build variable is a List<GithubItem. Now you want to convert it to single using Deserialize of JsonConvert?
You can just get one record, whatever your requirements is using this code:
 GithubItem itemsList = build.FirstOrDefault();

That would build fine. But this is just an example since I am not sure what is your requirement. If you need to filter your record, you can also pass a argument on FirstOrDefault:
 GithubItem itemsList = build.FirstOrDefault(x => x.UserName == "John");

That would also work fine.


text:
Q: How to set o real copy of a hashtable inside a array in java? I'm trying to do a arraylist of a hashtable for that i did:
ArrayList<java.util.Hashtable<String, String>> info = new ArrayList<java.util.Hashtable<String, String>>();

this did the job but later i needed to add some hashtables inside info using a for cycle:
java.util.Hashtable<String, String> e = new java.util.Hashtable<String, String>();
while(rs.next()){
    e.clear();
    for(String a:dados){
        e.put(a,rs.getString(a));
    }
    info.add(e);
}

The problem is that method add doesnt copy e to info, it only define a pointer to e so when i update e all inserted elements gets the new e values.
Can anyone give some help ?
thx for your time.

A: This should work:
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
import java.util.List;

List<Map<String, String>> info = new ArrayList<Map<String, String>>();

while (rs.next()) {
    Map<String, String> e = new Hashtable<String, String>();
    e.clear();
    for (String a : dados) {
        e.put(a, rs.getString(a));
    }
    info.add(e);
}

You should try to avoid declaring collections by their implementation class (declare them as List instead of ArrayList, or Map instead of Hashtable).

A: Don't need the clear() if you are using new everytime inside the loop.
java.util.Hashtable e = new java.util.Hashtable();
while(rs.next()){
    e = new java.util.Hashtable();
    for(String a:dados){
        e.put(a,rs.getString(a));
    }
    info.add(e);
}


text:
Q: nGINX / Angular 4 HTTP 1st load performance I have one angular4 App deployed and linked to NGINX, the problem is.

*

*If I open the web application locally on the server, it's working very fast | ex : localhost:80

*If I open the web application from my client machine it takes a long time in the first load/opening more than 1 minute, and after that, it seems fine.

any suggestions to improve NGINX first load performance?
nginx/1.14.0
Angular 4

proxy_cache_path /alf/cache levels=1:2 keys_zone=my_cache:10m max_size=20g inactive=50000m use_temp_path=off;

server {
#    listen 80 http2;
#    server_name localhost;
    listen 80 default_server;
    listen [::]:80 default_server;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

   location / {
#      root   /usr/share/nginx/html;
       proxy_cache my_cache;
       root   /var/www/html/bluemortar;
      index  index.html index.htm;
      try_files $uri $uri/ /index.html?$args;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
#        root   /usr/share/nginx/html;
         root   /var/www/html/bluemortar;

    }


text:
Q: Aplicativo Android funciona no emulador, mas não no aparelho físico Todo o projeto, inclusive o back-end funciona perfeitamente quando executado no emulador do Android no Visual Studio, mas quando gero o arquivo APK em modo release e executo no meu smartphone, somente o front-end funciona, já o back-end não funciona.
Eu sinceramente não sei onde está o problema, alguém pode me apontar uma solução?


text:
Q: Are There Realistic/Useful Solutions for Source Control for Ladder Logic Programs Version control for ladder logic (LL) programs for programmable logic controllers (PLCs) seems to be virtually non-existent. It may be because LL is a visual language and tends to be stored in binary files, or it may be because source code control hasn't "caught on" in process control engineering circles - or perhaps my Google-Fu is weak tonight.
Do you know of any realistic and useful solutions for version control for such systems?
Definitions:

*

*realistic = changes to the programs are tracked by user and subject to reversion and merges

*useful = the system integrates with visual LL designers, is not limited to LL from a single PLC manufacturer, and does not cost a ridiculous amount of money?

Note: I have heard of people using SVN or Mercurial et al to track the binary files, but I don't think the diff/merge capabilities would display readable differences.
ADDENDUM:
At first we only had to support Allen-Bradley PLCs. Now we also have Siemens and MicroLogix PLCs. Still searching for a viable solution...

A: If you can, look at B&R Automation.
Full Disclosure... I work for a sales partner of B&R Automation.
Modern B&R Automation projects work very well with versioning software.  I currently use GIT (which is not integrated), though there is supposed to be integration with SVN in the software.  All of the HMI source is saved as XML, and all of their PLC language sources (including ladder) is saved text based instead of binary (mostly XML as well).  If you have to do manual merges then you do have to "figure out" the XML to some extent, but I did not find it that difficult.  And the automatic merge usually makes that unnecessary anyways.

A: I only just saw this question, and there is actually a canned solution - from GE-IP of all places.  Check out Proficy Change Management.  This product does version control from a PLC control systems point of view, rather than a pure version control of files point of view - it works as a layer sitting on top of a VCS (the scary part is that originally this VCS was Visual SourceSafe) and handles rights management, reporting and checkout/checkin.
While the product is from GE-IP, it is designed to support a variety of PLC and HMI systems out of the box.
Full disclosure, I used for work for a company selling and installing PCM (but that was 7 years ago).  So if you ask me what it was like back then I'm likely to tell you where it all went wrong!

A: Unfortunately the answer is going to depend on the PLC vendor you're using.  Most of them store their code in proprietary file formats, so it makes it difficult to use regular source control.
Rockwell offers FactoryTalk AssetCenter if you're using Allen-Bradley.  I haven't priced it, but it's likely expensive.  It does more than source control though.
I have used regular (Mercurial) source control with Beckhoff TwinCAT PLC files.  That seems to work OK, but I never had to merge with anyone.  Their new version of TwinCAT (3) coming out later this year is supposed to be built on Visual Studio 2010, and I'm assuming will have much better out-of-the-box offerings for version control integration.  Fingers crossed.
Start Edit
I just wanted to add that I've now used the new TwinCAT 3 product, and I am using Mercurial (TortoiseHg and the VisualHg add-in for Visual Studio).  It is working pretty well.  First of all VisualHg makes it feel very integrated into the Visual Studio 2010 IDE that TwinCAT 3 uses.  However, the source code for TwinCAT 3 programs are generally stored in XML files.  This is a vast improvement over other vendor's proprietary binary formats that I've used, but it still doesn't merge well.  Some of the files don't have any line breaks in the XML (I've written to Beckhoff about this) which means a line-by-line source control system doesn't do much.  Also, since it's XML, the ordering of the nodes in the XML file seems to change randomly, even when you don't make any changes.  Also, I think it sometimes generates new IDs for some nodes when it doesn't have to, which makes for superfluous changes that Hg picks up on.  This effectively makes it impossible to make changes to a TwinCAT 3 program by 2 programmers at the same time, and then merge the changes.  It's an unfortunate oversight by the TwinCAT 3 developers, who undoubtedly use source control regularly in their own work, and didn't see the advantage for us lowly automation programmers to have access to similarly powerful tools.  :(
End Edit
Start Edit #2
I would like to point out that TwinCAT 3.1 now has file formats that are better suited to source control, particularly the structured text language files.  In fact, the product is now built to support integration to Team Foundation Server, I believe.
End Edit #2
The other alternative is that most PLC programs can be exported to text files.  RSLogix 5000, for instance, exports its projects to an L5K file, which is just text.  I've run scripts against those files before - they're fairly easy to parse.  They would work well with source control.  Of course that means exporting every time, which sucks.
If you do go with any standard version control, I highly suggest a distributed VCS, like Git or Mercurial, because with PLCs, half the time you're onsite and can't connect to your home server, so the ability to do local commits is a real bonus.
The other thing you have to realize is that some PLC programming environments, like RSLogix, already include a diff tool, so you can run diffs against two versions of your projects.  This, combined with saving a new file with today's date every day, is what most automation shops seem to get by with.

A: As horrifying as this sounds, in one case I ended up using the "Print to PDF" feature of the ladder logic software (in this case it was Horner's CScape) and then a free graphical PDF differencing program (e.g. DiffPDF) to compare changes because the source code was only available in a proprietary, binary format.


text:
Q: Invoking a method on SignalR connection in Redux middleware to send message to server I'm using middleware in Redux to connect to my signalR hub, which works perfectly and I can receive messages no problem.
Now I have got to the point where I want to invoke a method on the server to "Join a Group".
What is the best way to do so? I have a connection, so recreating the connection on the action "JOIN_GROUP" seems counter intuitive.
I thought I might be onto something when I read xxx, so I could chain
import {
JsonHubProtocol,
  HttpTransportType,
  HubConnectionBuilder,
  LogLevel,
} from '@microsoft/signalr';

import actionTypes from '../actions/actionTypes';
const startSignalRConnection = (connection) =>
  connection
    .start()
    .then(() => console.info('SignalR Connected'))
    .catch((err) => console.error('SignalR Connection Error: ', err));

const signalRMiddleware =
  ({ dispatch, getState }) =>
  (next) =>
  async (action) => {
    let connection;
    // register signalR after the user logged in
    if (action.type === actionTypes.USER_SIGNED_IN) {
      const connectionHub =
        window.globalConfig?.hubUrl || process.env.REACT_APP_HUB_URL;

      const protocol = new JsonHubProtocol();
      // let transport to fall back to to LongPolling if it needs to
      const transport =
        HttpTransportType.WebSockets | HttpTransportType.LongPolling;
      const options = {
        transport,
        logMessageContent: true,
        logger: LogLevel.Critical,
        accessTokenFactory: () => action.user.access_token,
      };

      // create the connection instance
      connection = new HubConnectionBuilder()
        .withUrl(`${connectionHub}/hub/notificationhub`, options)
        .withHubProtocol(protocol)
        .build();

      //add "on" events here...

      // re-establish the connection if connection dropped
      connection.onclose(() =>
        setTimeout(startSignalRConnection(connection), 5000)
      );

      startSignalRConnection(connection);
    } else if (action.type === actionTypes.JOIN_GROUP) {
      connection.invoke('JoinGroup', action.groupName);
    }

    return next(action);
  };
export const joinGroup = (groupName) => (dispatch, getState, invoke) => {
  invoke('JoinGroup', groupName);
};
export default signalRMiddleware;

When I dispatch the "JOIN_GROUP" action, the connection is undefined:
} else if (action.type === actionTypes.JOIN_GROUP) {
          // connection is undefined
          connection.invoke('JoinGroup', action.groupName);
}

I did read somewhere about being able to pass the invoke method from the connection onto another method. Hence:
export const joinGroup = (groupName) => (dispatch, getState, invoke) => {
      invoke('JoinGroup', groupName);
    };

But I have no idea how to use it, or populate the invoke in order to use it in my component.
Any help would be much appreciated.
Alex

A: Managed to work it out. In the end it was a very small tweak, in that the let connection needed to be before the initial (next)
import {
  JsonHubProtocol,
  HttpTransportType,
  HubConnectionBuilder,
  LogLevel,
} from '@microsoft/signalr';

import actionTypes from '../actions/actionTypes';
const startSignalRConnection = (connection) =>
  connection
    .start()
    .then(() => console.info('SignalR Connected'))
    .catch((err) => console.error('SignalR Connection Error: ', err));

const signalRMiddleware = ({ dispatch, getState }) => {
  let connection;
  return (next) => async (action) => {
    // register signalR after the user logged in
    if (action.type === actionTypes.USER_SIGNED_IN) {
      const connectionHub =
        window.globalConfig?.hubUrl || process.env.REACT_APP_HUB_URL;

      const protocol = new JsonHubProtocol();
      // let transport to fall back to to LongPolling if it needs to
      const transport =
        HttpTransportType.WebSockets | HttpTransportType.LongPolling;
      const options = {
        transport,
        logMessageContent: true,
        logger: LogLevel.Critical,
        accessTokenFactory: () => action.user.access_token,
      };

      // create the connection instance
      connection = new HubConnectionBuilder()
        .withUrl(`${connectionHub}/hub/notificationhub`, options)
        .withHubProtocol(protocol)
        .build();

      //add "on" events here...

      // re-establish the connection if connection dropped
      connection.onclose(() =>
        setTimeout(startSignalRConnection(connection), 5000)
      );

      startSignalRConnection(connection);
    } else if (action.type === actionTypes.JOIN_GROUP) {
      connection.invoke('JoinGroup', action.groupName);
      return;
    }
    return next(action);
  };
};
export default signalRMiddleware;


text:
Q: Stop propagation of 'drag' event for marker in Leaflet Is there a possibility to prevent Leaflet dragstart event from triggering just moment after start dragging a marker.
According to Leaflet documentation all you have to do is:
L.DomEvent.on(div, 'click', function (ev) {
    L.DomEvent.stopPropagation(ev);
});

But this obviously will ONLY work for few particular event (e.g. click, dblclick, mouseup, mousedown) because L.DomEvent.stopPropagation(e) and L.DomEvent.preventDefault(e) are just calling e.stopPropagation() and e.preventDefault() respectively otherwise it will try to access the originalEvent object inside the event.

This is the stopPropagation code in Leaflet 1.7.1:
export function stopPropagation(e) {

    if (e.stopPropagation) {
        e.stopPropagation();
    } else if (e.originalEvent) {  // In case of Leaflet event.
        e.originalEvent._stopped = true;
    } else {
        e.cancelBubble = true;
    }
    skipped(e);

    return this;
}

This is everything i tried until now to prevent the Leaflet dragstart event from being firing but no success:
marker.on("dragstart", function (e) {
    if (logic) {
L.DomEvent.stopPropagation(e);
L.DomEvent.preventDefault(e);
L.DomEvent.stop(e);
stopPropagation(e.originalEvent);
preventDefault(e.originalEvent);
stop(e.originalEvent);
e.originalEvent.stopPropagation();
marker.on("dragstart", L.DomEvent.stopPropagation);
marker.off("dragstart");
marker.bubblingMouseEvents = false;
    }
});

Jsfiddle
https://jsfiddle.net/sgf1uxoL/3/
What we need is really the ability to cancel the dragstart event sometimes depending on a logic that we evaluate in the last moment (when the user is about to start dragging) and NOT MAKING THE MARKER NON DRAGGABLE because this would break our design (completely block user from dragging the markers) therefore we don't and we can't use marker.dragging.disable();

A: Instead of dragstart event, which is fired too late to prevent dragging, you can use mousedown event, which is fired early enough, so that .dragging.disable() method can be used to prevent dragging.
Code could then look something like this:
marker.on('mousedown', function(evt){
  if (dragDisabled) evt.target.dragging.disable();
});
marker.on('mouseup', function(evt){
  if (dragDisabled) evt.target.dragging.enable();
});


text:
Q: How to get list of video responses YouTube API Objective C I'm trying to get the list of videos returned from querying the URL of video responses in my app, but I can't seem to find any documentation on the topic especially for Objective C. I can get the url of the response list (see code below), but what kind of GData class do I use to have the url return a list of entries or videos in an array or list?
//get video object and get the link from it
GDataEntryYouTubeVideo *video = [videoList objectAtIndex:i];
GDataLink *vidResponses = video.videoResponsesLink;

//resulting link returns an xml feed
vidResponses= https://gdata.youtube.com/feeds/api/videos/luCT5A02n5w/responses

A: In the completion handler, the feed variable will be a GDataFeedYouTubeVideo, which has a property called entries, which is an array of GDataEntryYouTubeVideos
GDataQueryYouTube * query = [[GDataQueryYouTube alloc] init];

query.feedURL = [NSURL URLWithString:@"https://gdata.youtube.com/feeds/api/videos/luCT5A02n5w/responses"];

GDataServiceGoogleYouTube * service = [[GDataServiceGoogleYouTube alloc] init];

service.userAgent = @"App Name";

[service fetchFeedWithQuery:query
                      completionHandler:^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error)
 {
     if(!error)
     {
         NSArray * entries = feed.entries;

         if(entries.count)
         {
             GDataEntryYouTubeVideo * firstVideo = entries[0];
         }
     }
 }];

It appears that URL has no video responses.


text:
Q: 'npm ERR! could not determine executable to run' in OpenShift pod I am trying to deploy an Angular app to OpenShift and below is a copy of my package.json
{
  "name": "app-admin",
  "version": "0.1.0",
  "scripts": {
    "global": "npm install",
    "start": "npx ng serve",
    "build": "npx ng build",
    "watch": "npx ng build --watch --configuration development",
    "test": "npx ng test",
    "e2e": "npx ng e2e",
    "cypress:open": "cypress open",
    "cypress:run": "cypress run"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^14.2.0",
    "@angular/common": "^14.2.0",
    "@angular/compiler": "^14.2.0",
    "@angular/core": "^14.2.0",
    "@angular/forms": "^14.2.0",
    "@angular/platform-browser": "^14.2.0",
    "@angular/platform-browser-dynamic": "^14.2.0",
    "@angular/router": "^14.2.0",
    "drag-on-drop": "^3.6.1",
    "npm": "^9.2.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.2.6",
    "@angular/cli": "~14.2.6",
    "@angular/compiler-cli": "^14.2.0",
    "@cypress/schematic": "^2.2.0",
    "@types/jasmine": "~4.0.0",
    "axe-core": "^4.4.3",
    "cypress": "^10.10.0",
    "cypress-axe": "^1.0.0",
    "jasmine-core": "~4.3.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.7.2"
  },
  "overrides": {
    "loader-utils@>2.0.0 <3": "2.0.4",
    "loader-utils@>3.0.0 <4": "3.2.1"
  }
}

The pods failed at npx ng serve with the following error
ERROR: ld.so: object 'libnss_wrapper.so' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
ERROR: ld.so: object 'libnss_wrapper.so' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
ERROR: ld.so: object 'libnss_wrapper.so' from LD_PRELOAD cannot be preloaded (cannot open shared object file): ignored.
npm info using npm@9.2.0
npm info using node@v18.9.1
npm http fetch GET 200 https://registry.npmjs.org/npm 828ms (cache miss)
npm http fetch GET 200 https://registry.npmjs.org/npm 881ms (cache miss)
npm http fetch GET 200 https://registry.npmjs.org/ng 1096ms (cache miss)
npm ERR! could not determine executable to run

I have tried every answer in this link and read this reddit thread. The solutions from the other stackoverflow post worked in the debug pod but when I add the step in the scripts. The pods failed with the same error in the next build again.
Things I have tried adding to the scripts:
"install": "npm install -g npm@9.2.0"
"prestart": "npm install -g"

Also tried put npm version in the dependencies and specified the npm version using engines. None worked for me.
Any help is appreciated.

A: You probably miss the glibc or nss_wrapper-libs package into your container. Some npm module require it to perform compilation during install (like couchbase module).
You could try to use a multi-stage build dockerfile an have glibc only in the builder image, not the final one.

A: In my case, the issue occurred because the devdependencies in the package.json was not installed. I have to pass an environment variable NODE_DEV=development for them to be installed which solved my issue. Thanks to this post.
For future readers who encounter the same issue: If my solution does not work for you, please check if the other answers help with your situations.


text:
Q: Force line break for each word I have "strings" = word representing characters put in array called "bWord" to put the characters in button, the problem is that space " " is considered a character and also put in a button. I wan't the string " " to create a break line instead of calling bWord
words like Book Cover would appear like this :
[B][O][O][K][ ][C][O][V][E][R]
I want it to appear like
[B][O][O][K]
[C][O][V][E][R]
this a picture of the current issue :

I was told to create a new layout, but I don't how to go about this
this is the code I'm using
        // draw word buttons

    RelativeLayout wordLayout = (RelativeLayout) findViewById(R.id.wordlayout);
    String[] word = ld.getLevelSpecific().getProcessedWord();

    for (int i = 0; i < word.length; i++) {
        Button temp = new Button(this);
        temp.setText("");
        temp.setTypeface(null, Typeface.BOLD);
        temp.setTextSize(TypedValue.COMPLEX_UNIT_SP, isd.getWordTextSize());
        temp.setIncludeFontPadding(false);
        temp.setId(idCount * 2 + i);
        temp.setTag(Integer.valueOf(i));
        temp.setBackgroundResource(R.drawable.button_shape_letter);
        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
                (int) (isd.getWordButtonSize() * orm.getScaleRatio()-2),
(int) (isd.getWordButtonSize() * orm.getScaleRatio()+6*orm.getScaleRatio()));

        if (i > 0) {
            p.addRule(RelativeLayout.RIGHT_OF, idCount * 2 + i - 1);
        } else {
            p.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            p.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        }

        p.setMargins(isd.getExtraspaceWord()+1, isd.getExtraspaceWord(),
                isd.getExtraspaceWord()+1, isd.getExtraspaceWord());
        temp.setLayoutParams(p);
        bWord[i] = temp;
        temp.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                onWordPressed((Integer) v.getTag());

            }
        });
        wordLayout.addView(temp);
    }

A: I'm not sure if I understand your question properly.
You mentioned words "Book Cover" but your screenshot shows "Bill Clinton"...
I made a fix to show:
[B][I][L][L]
[C][L][I][N][T][O][N]
Instead of:
[B][I][L][L][ ][C][L][I][N][T][O][N]
How to fix:
Option 1:
You can replace your RelativeLayout by two LinearLayouts. Line1 and Line2, for example.
Then, during runtime, you call:
LinearLayout Line1 = (LinearLayout) findViewById(R.id.line1);
LinearLayout Line2 = (LinearLayout) findViewById(R.id.line2);
...
if(word[i].equals(" "))
    insertingInFirstLine = false;
...
if(insertingInFirstLine)
    Line1.addView(newButton);
else
    Line2.addView(newButton);

Good point is that you don't need worry about View IDs. Just create to linear layouts with horizontal orientation and put them one below the other.
When the word has one line only, you can set Line2 visibility to "View.GONE"
Options 2:
If you really need to use Relative Layout, I updated your "FOR" loop. This way, after a space char (" "), all new views will be added below the first line.
Below is the example:
int lineDivider = 1000;
for (int i = 0; i < word.length; i++) {
    if(word[i].equalsIgnoreCase(" ")) {
        lineDivider = i;
    } else {
        Button temp = new Button(this);
        ...
        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
                    (int) (isd.getWordButtonSize() * orm.getScaleRatio()-2),
                    (int) (isd.getWordButtonSize() * orm.getScaleRatio()+6*orm.getScaleRatio()));

        if (i > 0) {
            if(i < lineDivider) {
                // First Line Items
                p.addRule(RelativeLayout.RIGHT_OF, idCount * 2 + i - 1);
            } else if (i == lineDivider + 1) {
                // First Item of Second Line
                p.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                p.addRule(RelativeLayout.BELOW, idCount * 2);
            } else {
                // Second Line Items
                p.addRule(RelativeLayout.BELOW,  idCount * 2);
                p.addRule(RelativeLayout.RIGHT_OF, idCount * 2 + i - 1);
            }
        } else {
            // First ITEM
            p.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            p.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        }
        ....
    }
}


text:
Q: Dockerfile not creating a running container? I am learning docker by following an online course and have successfully built an image with my Dockerfile but afterwards it is not creating and running the container; It does not say "Successfully built <CONTAINER_ID>" like in the course.
I thought my image should automatically create and run a container as specified by the last step: CMD ["npm","run","dev"]
Before docker, I would start my node app with "npm run dev" in the terminal and as you can see in my package.json script below, my dev command uses nodemon to run the file from src/index.js.
I am wondering if this is still the correct path to run index.js from with Docker because the Dockerfile step WORKDIR '/app'?? I tried changing the dev script to run from  "/app/src/index.js -e js" because of the command WORKDIR '/app' as well but no difference???
Any idea on why my created image is not creating a running container after being built?
Thank you!
Dockerfile
FROM node:14-alpine
WORKDIR '/app'
COPY package.json .
RUN apk update
RUN apk add --no-cache python3 py3-pip
RUN npm install bcrypt@5.0.0
RUN npm install
COPY . .
CMD ["npm", "run", "dev"]

package.json scripts for CMD to run
"scripts": {
  "dev": "env-cmd -f ./config/dev.env nodemon src/index.js -e js",
  "prod": "env-cmd -f ./config/prod.env nodemon src/index.js",
},

OUTPUT from "docker build ."
Why isn't it running a container from CMD ["npm", "run", "dev"]???
[+] Building 5.5s (14/14) FINISHED
 => [internal] load build definition from Dockerfile                                                           0.0s
 => => transferring dockerfile: 504B                                                                           0.0s
 => [internal] load .dockerignore                                                                              0.0s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load metadata for docker.io/library/node:14-alpine                                              0.6s
 => [auth] library/node:pull token for registry-1.docker.io                                                    0.0s
 => [1/8] FROM docker.io/library/node:14-alpine@sha256:4af...........4d66779  0.0s
 => [internal] load build context                                                                              0.9s
 => => transferring context: 1.85MB                                                                            0.9s
 => CACHED [2/8] WORKDIR /app                                                                                0.0s
 => CACHED [3/8] COPY package.json .                                                                           0.0s
 => CACHED [4/8] RUN apk update                                                                                0.0s
 => CACHED [5/8] RUN apk add --no-cache python3 py3-pip                                                        0.0s
 => CACHED [6/8] RUN npm install bcrypt@5.0.0                                                                  0.0s
 => CACHED [7/8] RUN npm install                                                                               0.0s
 => [8/8] COPY . .                                                                                2.5s
 => exporting to image                                                                                1.4s
 => => exporting layers                                                                                1.4s
 => => writing image sha256:9738.......5d80b4316a8                   0.0s

A: Are you sure that the files are copied correctly?
You set the workdir, but I suggest to copy artifacts like this:
COPY . /app


text:
Q: How to execute code from another program as a result of a command I'm thinking on how to design a program that as a result of all events, checks a command file (which essentially holds key-value pairs where the key is a command and the value is the code to execute) and runs that command's matching code.
It'll be run on a unix/linux machine.
For simplicity's sake, the program will be as follows:
It'll wait for the user's input. When the user inputs a valid command (i.e a command that appears in the commands file), the matching code will be executed. If it doesn't match any command it'll print "No matching command".
So if my command file looks like:
run1='a.py'
run2='b.py'

and I enter "run1" then a.py will be executed. If I enter "run3" then "No matching command" will be printed.
I want to implement this in C++ and I've seen similar implementations where people used system() to execute the commands but this feel like a bad way to achieve this.
What other options do I have to achieve this?
p.s - I wrote in my example that the code being run is in python. I'm not sure I want that to be the only option (so I'll need to be able to identify the type. Lets assume I can do that).
Is this still achievable?

A: There are LOTS of options. system("a.py"); will do what you want (assuming python is installed correctly on the system you are running on). If that is the "best" solution really depends on what you want to achieve, and that isn't entirely clear from your question.
Most other solutions will be more or less system specific. You could, for example, in Unix/Linux use fork() and one of the flavours of exec() [with python as the actual executable, and "a.py" as the file to run in python], but that won't work in Windows, where you would have to use, for example, spawn() (again with python as the executable file and for example "a.py" as the code to run).


text:
Q: Django Tables 2 - Accessing Fields I recently upgraded from django-tables (version 1) to djangotables2 in order to upgrade my code to Django 1.11 (from Django 1.6). I have a table containing several fields, and I am trying to access specific fields.
The following code is not working in the HTML:
    {{ item.entered_by }}
    {{ item.last_updated|date:"m/d/Y j:i a" }}

('item' is a BoundRow object from the Django Table.
I can iterate through all fields, and all fields will be displayed if I write:
{% for field in item%}

    {{ field }}

{% endfor %}

However, I only want certain fields to be printed (for instance, the 'entered_by' and 'last_updated') fields. How can I do this/check the field name?
I've looked through the documentation here: http://django-tables2.readthedocs.io/en/latest/pages/api-reference.html# without success. The code worked correctly in Django 1.6, so the problem is not the name of the column, I know it has something to do with how I'm trying to access the actual column data.


text:
Q: How can I format the output of my SQL query to display nicely? I've defined my own database to play around and learn SQL (using SQL*Plus via SSH to remote into my school's linux machines). However, I've been having problems displaying my tables nicely, specifically this one:
CREATE TABLE customer_account
(
  ACCOUNT_ID NUMBER(10) NOT NULL,
  PHONE_NUMBER VARCHAR(20) NOT NULL,
  EMAIL VARCHAR(100) NOT NULL,
  FNAME VARCHAR(100) NOT NULL,
  LNAME VARCHAR(100) NOT NULL,
  ADDRESS_STREET VARCHAR(50) NOT NULL,
  ADDRESS_CITY VARCHAR(20) NOT NULL,
  ADDRESS_STATE VARCHAR(2) NOT NULL,
  ADDRESS_ZIP VARCHAR(5) NOT NULL,
  BIRTH DATE DEFAULT NULL,
  PRIMARY KEY (ACCOUNT_ID)
);

INSERT INTO customer_account
VALUES (1, '9174560091', 'jhunters01@cuny.edu', 'Jack', 'Hunter', '11 67ST', 'New York', 'NY', '10024', TO_DATE('1998/01/22 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));
INSERT INTO customer_account
VALUES (2, '7134560012', 'L.Larson@gmail.com', 'Linda', 'Larson', '100-9 Brooklyn Hwy', 'New York', 'NY', '11225', TO_DATE('1996/12/20 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));
INSERT INTO customer_account
VALUES (3, '5303056927', 'sciencerules@gmail.com', 'Albert', 'Newton', '1206 Francis Mine', 'Sacramento', 'CA', '95814', TO_DATE('2001/05/17 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));
INSERT INTO customer_account
VALUES (4, '5106204676', 'luvlucy@yahoo.com', 'Ricky', 'Ricardo', '90 maple street west', 'Trenton', 'NJ', '08861', TO_DATE('1942/12/01 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));
INSERT INTO customer_account
VALUES (5, '3237843058', 'RalphJRiggins@dayrep.com', 'Ralph', 'Riggins', '3373 Hillhaven Drive', 'Los Angeles', 'CA', '90017', TO_DATE('1964/10/02 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));
INSERT INTO customer_account
VALUES (6, '2133384287', 'lavonnaRWilliams@mail.com', 'Lavonna', 'Williams', '1305 Zimmerman Lane', 'City of Commerce', 'CA', '90040', TO_DATE('1983/03/03 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));
INSERT INTO customer_account
VALUES (7, '6313604478', 'antoninetteRe@gmail.com', 'Antoinette', 'Reynolds', '2329 Wayback Lane', 'Smithtown', 'NY', '11787', TO_DATE('1990/10/25 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));
INSERT INTO customer_account
VALUES (8, '9736948587', 'Mcdonald@yahoo.com', 'Berger', 'McDonald', '3024 Spring Haven Trail', 'Mountain View', 'NJ', '07470', TO_DATE('1960/06/17 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));
INSERT INTO customer_account
VALUES (9, '9082074677', 'M.Lester@gmail.com', 'Moe', 'Lester', '2980 Williams Mine Road', 'Lakewood', 'NJ', '08701', TO_DATE('1988/10/05 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));
INSERT INTO customer_account
VALUES (10, '8282351937', 'son@rhyta.com', 'Dam', 'Son', '98 McVaney Road', 'Canton', 'NC', '28716', TO_DATE('1957/08/28 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

Whenever I did
SQL> SELECT * FROM customer_account;

the entire table does not come out nicely no matter what I tried. I've used set linesize to no avail. This is the best I could do

Is there too much going on per column in the actual table or could I do something to fix this?

A: I recommend using SQL developer.
Here are 2 suggestions.
Oracle SQL Developer
http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index-097090.html
SQuirreL SQL
http://squirrel-sql.sourceforge.net/


text:
Q: Induction on Formulas (Induction on the number of connectives in a formula) I am working through the textbook of Richard Hodel on an Introduction to Mathematical Logic. I came accross this theorem 1 on page 52 (picture attached below) and I am stuck at trying to figure out this proof. It does not seem right to me, because the proof is referencing it's own conclusion to prove a statement.
The first such instance occurs in the statement "a formula with no connectives is a propositional variable, and each propositional variable has property Q by (1)"
The second such instance occurs in the statement "Now apply (3) to conclude that ..."
How is it possible the theorem is referencing it's own conclusions to prove the it?
I can't imagine a mistake in this textbook would go unnoticed. I feel that perhaps I am not understanding something correctly about the proof.

A: The proof of the theorem is allowed to depend on $(1)$, $(2)$, and $(3)$ because they aren't conclusions of the theorem. They're premises. To clarify, here's a restatement of Theorem $1$:

If $Q$ is a property of formulas, and if we assume that $(1)$, $(2)$, and $(3)$ are all true, then it necessarily follows that every formula of propositional logic also has property $Q$.


text:
Q: Project to NAD83 (epsg:26912) with projectRaster - gives epsg:2152 I am working with some Landsat 8 images from the U.S. Geological Survey (USGS) Earth Resources Observation and Science (EROS) Center. I am processing the images in R, and after masking the clouds, I want to project from the following CRS "+proj=utm +zone=12 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0" (as they are defined in the original data) to NAD 1983 UTM 12N.
I apply de following function (because I have 70 images):
test <- raster(xmn=220785, xmx=455115, ymn=4029285, ymx=4267815, res=30)
crs(test) <- "+proj=utm +zone=12 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0"

vals <- 1:ncell(test)
test <- setValues(test, vals)

pred.list <- list(test)
names(pred.list) <- c("test")

NAD83proj <- "+init=epsg:26912 +proj=utm +zone=12 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0"

projtoNAD1983 <- function(x) {
    l8_NAD1983 <- list()
    for (i in 1:length(x)) {
        print(i)
        l8_NAD1983[[i]] <- projectRaster(from="+proj=utm +zone=12 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0",crs=NAD83proj, filename= paste0(names(pred.list[i]), "_nad83.tif"), type="GTiff", overwrite=T)
    }
    return(l8_NAD1983)
    gc()
}

test_nad1983 <- projtoNAD1983(pred.list)

But the output GTiff has a deprecated crs: "+proj=utm +zone=12 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"
I do not know what I do wrong. My version of rgdal is 1,1-1, GDAL 1.11.2 (2015/02/10).
Should I just assign the projection epsg:26912 manually?

A: Please always simplify your example to allow focusing on the essence of your question (no need for a function, or a loop here). It had an error (the from argument is wrong). I also made test smaller.
test <- raster(xmn=220785, xmx=224595, ymn=4263885, ymx=4267815, res=30)
crs(test) <- "+proj=utm +zone=12 +datum=WGS84 +units=m"
values(test) <- 1:ncell(test)
NAD83proj <- "+init=epsg:26912 +proj=utm +zone=12 +datum=NAD83 +units=m"
x <- projectRaster(from=test, crs=NAD83proj)

So you get
crs(x)
# CRS arguments:
# +proj=utm +zone=12 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs

Which, I think, is the same thing as what you want, expressed differently. Somehow it states the ellipsoid but not the datum. Perhaps because of using an epsg code. I do not know what that code stands for --- I know you can look that up -- but why make things opaque and not simply ask for what you want:
NAD83proj2 <-"+proj=utm +zone=12 +datum=NAD83 +units=m"
y <- projectRaster(from=test, crs=NAD83proj2)
crs(y)

# CRS arguments:
#  +proj=utm +zone=12 +datum=NAD83 +units=m +ellps=GRS80 +towgs84=0,0,0

Whether it is a good idea to do all this (see mkennedy's comment) is another matter. Note tha tin both cases you have: +towgs84=0,0,0, i.e., no difference.


text:
Q: SinkBinding fails to inject K_SINK environment variable I am trying to set up a Knative eventing pipeline, where exists a container that accepts external gRPC requests and fires events into a broker for further processing.
In my toy example, I am failing to use SinkBinding to inject K_SINK environment variable. This is the relevant section of my configuration:
apiVersion: v1
kind: Namespace
metadata:
  name: bora-namespace
  labels:
    eventing.knative.dev/injection: enabled

---

apiVersion: eventing.knative.dev/v1
kind: Broker
metadata:
  name: my-broker
  namespace: bora-namespace

---

apiVersion: apps/v1
kind: Deployment
metadata:
  name: ease-pipeline-server
  namespace: bora-namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: ease-pipeline-server
  template:
    metadata:
      labels:
        app: ease-pipeline-server
    spec:
      containers:
        - name: ease-pipeline-server
          image: docker.io/boramalper/ease-pipeline-server:latest
          imagePullPolicy: Always

---

apiVersion: sources.knative.dev/v1
kind: SinkBinding
metadata:
  name: bind-ease-pipeline-server
  namespace: bora-namespace
spec:
  subject:
    apiVersion: apps/v1
    kind: Deployment
    selector:
      matchLabels:
        app: ease-pipeline-server
  sink:
    ref:
      apiVersion: eventing.knative.dev/v1
      kind: Broker
      name: my-broker

---

kind: Service
apiVersion: v1
metadata:
  name: ease-pipeline-server
  namespace: bora-namespace
spec:
  type: NodePort
  selector:
    app: ease-pipeline-server
  ports:
    - protocol: TCP
      port: 80
      targetPort: 8080
      nodePort: 30002

My container gets stuck in an infinite crash loop due to missing environment variable.
The SinkBinding object seems to have no issues:
$ kubectl --namespace bora-namespace get sinkbinding
NAME                        SINK                                                                                AGE   READY   REASON
bind-ease-pipeline-server   http://broker-ingress.knative-eventing.svc.cluster.local/bora-namespace/my-broker   22m   True

System information:
$ kn version
Version:      v20210526-local-0c6ef82
Build Date:   2021-05-26 06:34:50
Git Revision: 0c6ef82
Supported APIs:
* Serving
  - serving.knative.dev/v1 (knative-serving v0.23.0)
* Eventing
  - sources.knative.dev/v1 (knative-eventing v0.23.0)
  - eventing.knative.dev/v1 (knative-eventing v0.23.0)

$ kubectl version
Client Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.6", GitCommit:"8a62859e515889f07e3e3be6a1080413f17cf2c3", GitTreeState:"clean", BuildDate:"2021-04-15T03:28:42Z", GoVersion:"go1.15.10", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.7", GitCommit:"132a687512d7fb058d0f5890f07d4121b3f0a2e2", GitTreeState:"clean", BuildDate:"2021-05-12T12:32:49Z", GoVersion:"go1.15.12", Compiler:"gc", Platform:"linux/amd64"}

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.1 LTS
Release:    18.04
Codename:   bionic

$ uname -a
Linux REDACTED 4.15.0-137-generic #141-Ubuntu SMP Fri Feb 19 13:46:27 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

A: The SinkBinding object has a subject configured using a label selector:
subject:
  apiVersion: apps/v1
  kind: Deployment
  selector:
    matchLabels:
      app: ease-pipeline-server

However, there is no such label set on the Deployment object:
metadata:
  name: ease-pipeline-server
  # no labels

The solution here would be to either:

*

*add the corresponding label(s) to the Deployment's metadata
metadata:
  name: ease-pipeline-server
  labels:
    app: ease-pipeline-server

*use a subject matching on the Deployment's name (API documentation)
subject:
  apiVersion: apps/v1
  kind: Deployment
  name: ease-pipeline-server


text:
Q: How to see JIT-Compiled code in .NET VM (CLR) How can I have a trace of native code generated by the JIT-Compiler ?
Thanks

A: You should look for the files output from the NGen tool. NGen compiles and stores pre-jitted versions of assemblies in the Global Assembly Cache.

A: You can even use Sharplab to see generated code => https://sharplab.io/ . In this, you can quickly see the generated code based on what C# code you write in both Debug and Release configuration.
Recently popular compiler explorer also started supporting .NET languages. Here is the example => https://godbolt.org/z/P49Y6Ejh6
It's not fast as SharpLab, but still it's a viable option to look for.

A: In Visual Studio place a breakpoint in the code and start debugging. When it breaks, open the Disassembly window (Debug > Windows > Disassembly or Alt+Ctrl+D).

A: If you just use Debug->Windows->Disassembly on a standard Debug or Release exe, without modifying Visual Studio Debugging options, you will just see a version of non optimized .NET code.
Have a look at this article "How to see the Assembly code generated by the JIT using Visual Studio". It explains how to inspect generated JIT optimized code.
One relevant quote from the article:

*Configure the Debugging Options in Visual Studio to allow the JIT to generate optimized code and to allow you to debug the optimized
  code.

  Go to Tools => Options => Debugging => General ·         Make sure
  that box labeled 'Suppress JIT optimization on module load' is
  Unchecked.
·         Make sure that the box labeled 'Enable Just My Code' is
  Unchecked.

A: There's a more cross-platform, cross-architecture, local-only and open source approach possible with recent versions of .NET. This also allows you to build/modify the JIT itself and see the results. The complete steps are described at:
https://github.com/dotnet/runtime/blob/main/docs/design/coreclr/jit/viewing-jit-dumps.md
The downside is that it's not as "simple" or easy to use out of the box.
It boils down to:

*

*Build your application and publish it. Something like this:
dotnet publish -c Release -r linux-x64
But replace linux-x64 with the appropriate OS/architecture combo, like win-x64 or osx-arm64 as appropriate.

*Build a Debug build of the clrjit:
git clone https://github.com/dotnet/runtime
cd runtime
./build clr -c Debug

*Replace your application's clrjit with the one you built
cp /path/to/dotnet/runtime/artifacts/bin/coreclr/Linux.x64.Debug/* bin/Release/net6.0/linux-x64/publish/
Adjust Linux.x64, net6.0 and linux-x64 as appropriate.

*Set the COMPlus_JitDump=<Method> environment variable and run the application to dump the JIT output to the standard output.
COMPlus_JitDump=Main ./bin/Release/net6.0/linux-x64/publish/Application