text:
Q: How to get login and pass from rest request in spring boot? I'm writing REST app with spring boot and spring security with JWT.
I created registration end point which just creates an account.
I wanted to implement authentication througn basic auth with login and password which would returns a jwt token. Other requests would authenticate by token.
But I can't implement security by login and password and JWT both, so I tried to perform basic auth manually and leave spring security by token.
How can I get login and password from rest request in controller to check if the account exists in the database manyally?
The example of basic auth:

A: JWT token is an string joined by points. It has three pieces and these are encoded in base64. The second piece has the information of the user. You can pass this information to the security context and get wherever you want.
Decode the token, set the information in UserDetails (you can extend this class) and pass it to the UsernamePasswordAuthenticationToken. Pass this object to the security context and get the information in your controllers using SecurityContextHolder.getContext().getAuthentication();
More info here: https://www.toptal.com/spring/spring-security-tutorial
// Get user identity and set it on the spring security context
        UserDetails userDetails = userRepo
            .findByUsername(jwtTokenUtil.getUsername(token))
            .orElse(null);

        UsernamePasswordAuthenticationToken
            authentication = new UsernamePasswordAuthenticationToken(
                userDetails, null,
                userDetails == null ?
                    List.of() : userDetails.getAuthorities()
            );

        authentication.setDetails(
            new WebAuthenticationDetailsSource().buildDetails(request)
        );

        SecurityContextHolder.getContext().setAuthentication(authentication);

A: Basic auth and JWT are so different. Basic authenticatio requires that you send the username and password joined by : and encoded in base64. JWT requires a service (may be external like firebase auth or internal in your spring boot) that generates the JWT token. The JWT token should be passed in Authorization header.
Read this https://security.stackexchange.com/questions/248195/what-are-the-advantages-of-using-jwt-over-basic-auth-with-https


text:
Q: How to restore /sysroot on Fedora 20 I can't boot my Fedora 20 system as usual. Upon boot I get the message
Entering emergency mode. Exit the shell to continue.

journalctl reveals the following:
systemd[1]: Starting Switch Root...
systemd[1]: Not switching root: /sysroot does not seem to be an OS tree. /etc/os-release is missing.
systemctl[391]: Failed to issue method call: Invalid argument
systemd[1]: initrd-switch-root.service: main process exited, code=exited, status=1/FAILURE
systemd[1]: Failed to start Switch Root.
systemd[1]: Startup finished in ...

I ran fsck on /dev/mapper/fedora-root, which appeared to direct a lot of stuff to /lost+found. It's now clean, apparently.
ls / (from emergency mode) gives:
bin dev dracut-state.sh etc init lib lib64 proc root run sbin shutdown sys sysroot tmp usr var

I can ls each of these directories, but they appear much smaller than usual and lack stuff I know was there. Is this a consequence of emergency mode or a corrupted file system?
My direct question is: how do I restore /sysroot and /etc/os-release? However, I'm worried that this isn't the only damage, and that when this is fixed more problems will be revealed, so my secondary question is: how do I detect and fix any further problems that might have been caused? I do not have a backup of these (I've just discovered that I'm stupidly only backing up /home, when I thought I was backing up everything).
Background to the problem: I dual boot Windows and Fedora 20 on separate hard disks. /dev/sda and /dev/sdb both contain NTFS partitions for Windows. /dev/sdc is and SSD for /boot and everything except /home; /home is on /dev/md127. Everything was working fine, I booted into Windows for the first time in quite a while to use some Windows software, then booted back into Linux and had this problem. I've done this many times before in the past, so not sure whether or not this is the cause of the issue.
/dev/sdc2 (where the OS resides) is an LVM partition.
Please tell me if I can be any more specific, if I can provide any more information that is relevant, or if there are any additional diagnostics I can run.
Thank you!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get only digits using regexp I have in table column pnum_s
I need get only that rows, which value in column pnum_s is exactly 10 symbol and all these symbols are only digits
what query must write for this?
I am trying
SELECT * FROM mytable WHERE pnum_s REGEXP '^\d+$'
But this not returns 0 rows

A: I think with Mysql you'll want something like this:
^[[:digit:]]{10}$

A: Check out the reference page.
http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
What you're looking for is this:
SELECT * FROM mytable WHERE pnum_s REGEXP '^[[:digit:]]{10}$';

A: The pattern you are looking for is either '^[0-9]{10}$' or '^[[:digit:]]{10}$'.
Everything is in the manual.

A: try this pattern:
'^[0-9]{10}$'


text:
Q: How to link map marker to detail view on Sencha Touch (Architect 2) I have a map with a marker, and i want to make the marker clicktable to show some basic info.
I am new to Sencha, and I need advice what should I implemante in listener function to get the same effect as i click on list item:
for example, this is my code of maprender function
var lat = 37.428607;
var lng = -122.169344;

var latLng = new google.maps.LatLng(lat, lng);

var marker = new google.maps.Marker({
    position: latLng,
    map: gmap,
    draggable: false,
    animation: google.maps.Animation.DROP,
    title: 'cool'
});

var contentString = 'bla bla bla';

var infowindow = new google.maps.InfoWindow({
    content: contentString
});

google.maps.event.addListener(marker, 'click', function() {
      /* here comes something that will make my detail list visible with the marker details*/
});

and i want to make it work in the same way as my function for "itemtap" which i use in my list... something like this:
onMyListItemTap: function(dataview, index, target, record, e, options) {
this.setActiveItem('detalji');this.down('#back').show();
this.down('#detalji').setData(record.data);
}

A: There is a great example on Github for Sencha Touch 1...I believe it's called World Map. If you unzip that (the app is in one of the many folders) you can see a Google map wil multiple custom markers. This project is very useful for learning, as it not only shows custom map markers, but also popup overlays on a marker click.
I have yet to adapt it to Sencha Touch 2, but it shouldn't be too difficult...here is some example code (after multiple markers have been added):
   google.maps.event.addListener(marker, 'click', function()
                {
        if (!this.popup)
                    {
          this.popup = new Ext.Panel(
                            {
            floating: true,
            modal: true,
            centered: true,
            width: 500,
            styleHtmlContent: true,
            scroll: 'vertical',
            items:[{
              xtype:'button',
              ui:'round',
              text:'See Country Profile',
              handler:goToCountryWrapper,
              scope : this
            },
            (new countryOverlay(country)).overlayPanel
            ],
                layout: {
              type: 'auto',
              padding: '55',
              align: 'left'
            },
            dockedItems: [{
              dock: 'top',
              xtype: 'toolbar',
              title: country.title
              }],
          });
        };
        this.popup.show('pop');
      });

Also I think from what I understand about Sencha Touch 2, you would have to put a listener in your map controller (MyApp.map.controller file)....read up about the refs, as the refs 'finds' the marker(s) you have defined and adds a listener to the item.
If you have any progress please post your findings :-)


text:
Q: How to separate css code blocks in javascript? How to separate css code blocks in javascript?
Following are some css in the serialised form:
const css = "body { background-color: lightblue; } h1 { color: white; text-align: center; } p { font-family: verdana; font-size: 20px; }"

How can I parse it and get it in the following form as array (along with adding whitespaces (preserving whitespaces. i.e. in formatted form):
const parsedCss = [
'body {
  background-color: lightblue;
}',

'h1 {
  color: white;
  text-align: center;
}',

'p {
  font-family: verdana;
  font-size: 20px;
}',

]

A: You could use const parsedCss = css.split(/(?<=\})/)
This splits the css on the  "}" symbol, and uses lookahead assertion to retain it.
The output would be
[
'body {
  background-color: lightblue;
}',

'h1 {
  color: white;
  text-align: center;
}',

'p {
  font-family: verdana;
  font-size: 20px;
}',

]

A: Try splitting with regex
/(?<=})\s+/

const css = "body { background-color: lightblue; } h1 { color: white; text-align: center; } p { font-family: verdana; font-size: 20px; }"

const beautifiedCss = css_beautify(css)

const parsedCss = beautifiedCss.split(/(?<=})\s+/)

console.log(parsedCss.join(',\n\n'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.13.0/beautify-css.js"></script>

A: const css =
  "body { background-color: lightblue; } h1 { color: white; text-align: center; } p { font-family: verdana; font-size: 20px; }";

let parsedCss = css
  .trim()
  .split("}")
  .map((word) => (word + "}").trim());
parsedCss.pop();

console.log(parsedCss);

/*
OUTPUT:
[ 'body { background-color: lightblue; }',
  'h1 { color: white; text-align: center; }',
  'p { font-family: verdana; font-size: 20px; }' ]
*/

we can add \n for newline to get the formatted output:
const css =
  "body { background-color: lightblue; } h1 { color: white; text-align: center; } p { font-family: verdana; font-size: 20px; }";

let parsedCss = css
  .trim()
  .split("}")
  .map((word) =>
    (word.replace(/[;]/gi, ";\n").replace(/[{]/gi, "{\n") + "}")
      .trim()
      .toString()
  );
parsedCss.pop();

parsedCss.map((parsed) => console.log(parsed + ","));

/*
OUTPUT:

body {
 background-color: lightblue;
 },
h1 {
 color: white;
 text-align: center;
 },
p {
 font-family: verdana;
 font-size: 20px;
 },

*/


text:
Q: Terminal keeps asking for password and sometimes showing "keychain cannot be found to store" error For example if I pull from a git repo it keeps asking my for the username and password and if I use oauth2:xxx@xxx it says "a keychain cannot be found to store oauth2."

I can see system in my keychain access.


text:
Q: Nest JS two instances of the same provider Hi on a test suite it appears to me that I have 2 living instances of a same provider, one for the implementation and another one for the real implementation.
I base my conclusion in a fact that on my test I tried replace a method by a jest.fn call but still, on the service I am testing the method still points to the original implementation.
What makes it even more odd is that I was able to mock another service performing exactly the same procedure, as if, depending on how those services were injected (where they came from in the container graph) it would or not work.
I'll try to share some snippets, but of course, only a small repo could actually reproduce it, but perhaps someone has an insight:
 beforeAll(async done => {
    app = await Test.createTestingModule({
      imports: [
        SOME_MODULES,
      ],
      providers: [
        EssayApplicationService,
        ReviewFacade,
        ExamCacheResultService,
      ],
    }).compile();

    essayApplicationService = app.get<EssayApplicationService>(EssayApplicationService)
    reviewFacade = app.get<ReviewFacade>(ReviewFacade)
    examCacheResult = app.get<ExamCacheResultService>(ExamCacheResultService)
    await app.init()
    done()
  })

it('should invoke review only once', async done => {

    reviewFacade.startReview = jest.fn() --> this works
    examCacheResult.clearCachedResult = jest.fn() --> this fails

    await essayApplicationService.finishApplication()

    expect(reviewFacade.startReview).toHaveBeenCalledTimes(1)
    expect(reviewFacade.startReview).toHaveBeenCalledWith(expect.objectContaining({ id: 1 }))
    expect(examCacheResult.clearCachedResult).toHaveBeenCalledTimes(1) ---> here this fails, although it's called!!

So,the issue boils down to the fact that I'm 100% positive that both methods were called on the service under test, but the second for some reason wasn't replaced by the mock

A: You are mixing the concepts of unit tests and end to end (e2e) tests. You are importing a module and at the same time you import single providers directly. I'm assuming that one of your imported modules also imports ExamCacheResultService. This way, you have two of them in your test application. When you call app.get(ExamCacheResultService), you will get the instance that is directly declared in your testing module. But the one that is used when you call finishApplication is the other one. Decide what you want to test and follow the following principles:
Unit test
In a unit test you want to test a single provider/controller isolated from other dependencies, e.g. UserService or UsersController. You import this provider and its injected dependencies as mocks. You do not import a module.
Let's assume we have a UsersService that depends on a DatabaseConnection:
export class UsersService {
  constructor(private connection: DatabaseConnection) {}
  // ...
}

In your unit test, you import the UsersService, you mock the DatabaseConnection but you do not import the UsersModule.
module = await Test.createTestingModule({
  providers: [
    UsersService,
    { provide: DatabaseConnection, useClass: DbConnectionMock },
  ],
}).compile();
databaseMock = module.get(DatabaseConnection);
databaseMock.findMany.mockReturnValue([]);

E2E test
In an end to end test, you want to test your whole application and therewith the interaction between the parts that you have unit tested beforehand. So you do not import single providers but instead a module, typically the AppModule. You can then override single providers, e.g. if you want to test on an in-memory database instead of an actual one or you want to mock the results of an external API.
const moduleFixture = await Test.createTestingModule({
      imports: [AppModule],
    }).overrideProvider(DatabaseConnection).useClass(InMemoryDatabaseConnection)
      .overrideProvider(ExternalApiService).useValue(externalApiMock)
      .compile();
    app = moduleFixture.createNestApplication();
    externalApiMock.get.mockReturnValueOnce({data: [...]});
    await app.init();

How to create mocks?
See this answer.


text:
Q: Prestapyt and Prestashop 1.6.0.9, error on post I'm trying to follow the example given with prestapyt, I have to sync products and categories from csv files to Prestashop, version 1.6.0.9.
prestapyt says it may not be compatible with version newer than 1.5.9.0.
As in the example my code is:
#!/usr/bin/python
# -*- coding: utf-8 -*-

from prestapyt import PrestaShopWebService
from xml.etree import ElementTree

prestashop = PrestaShopWebService('http://myshop.com/api','mykey')
prestashop.debug = True

prestashop.get('')

print "ADD"
address = """
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<category>
<id></id>
<id_parent></id_parent>
<active>1</active>
<id_shop_default></id_shop_default>
<is_root_category></is_root_category>
<position></position>
<date_add></date_add>
<date_upd></date_upd>
<name><language id="1">Jackets Exp test</language><language id="2">Giacche exp prova</language></name>
<link_rewrite><language id="1"></language><language id="2"></language></link_rewrite>
<description><language id="1"></language><language id="2"></language></description>
<meta_title><language id="1"></language><language id="2"></language></meta_title>
<meta_description><language id="1"></language><language id="2"></language></meta_description>
<meta_keywords><language id="1"></language><language id="2"></language></meta_keywords>
<associations>
<categories>
<categories>
<id></id>
</categories>
</categories>
<products>
<products>
<id></id>
</products>
</products>
</associations>
</category>
</prestashop>
"""

prestashop.add('categories', address)

and this is the answer on server side
[error] [client **] [PHP Warning #2] SimpleXMLElement::__construct(): Entity: line 1:   parser error : Start tag expected, '<' not found   (**/prestashop/trunk/classes/webservice/WebserviceRequest.php, line 1454)
[error] [client **] [PHP Warning #2] SimpleXMLElement::__construct(): %0A%3Cprestashop+xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E (**/prestashop/trunk/classes/webservice/WebserviceRequest.php, line 1454)
[error] [client **] [PHP Warning #2] SimpleXMLElement::__construct(): ^ (**/prestashop/trunk/classes/webservice/WebserviceRequest.php, line 1454)

So it sounds like it's a encoding error, I tried to edit prestapyt https://github.com/guewen/prestapyt/blob/master/prestapyt/prestapyt.py @ line 283 removing the urlencode, but it didn't work. Help!!! :D


text:
Q: Can report data be accessed programatically? Is there any way to access existing reports and their data to be used in apex? Sure, I could write the SOQL manually but if I want it to mirror a specific report I would have to make code changes anytime the report was updated.
I don't think it can currently be done but I'd love to be wrong.

A: Update for Winter '14

API:
  I think the biggest announcement that developers have been waiting for API wise is the availability of our Analytics API. We introduced a limited pilot in summer 13 and now the Analytics REST API is generally available. The Analytics API lets you integrate Salesforce report data into your apps programmatically and has several resources that let you query metadata, and record details.
  Source - Winter '14 Developer Preview

The Salesforce1 Reporting REST API
Run Reports in Apex

Update with Lightning enabled
Stick with the official API as above where possible. The direct URL access from below is now breaking when Lightning is enabled in an org as the HTML content that comes back is instead a redirect into Lightning. E.g.

window.location.href ='https://na1.lightning.force.com/one/one.app#/alohaRedirect/00O?export=1&enc=UTF-8&xf=xls&rt=48';

In the past I have used a bit of a grey area (not an official / supported API) to pull the list of reports and then the corresponding report data.
While it worked well, it was to be part of a product that people would purchase. In the end the feature never saw the light of day as it seemed like we might end up talking to Salesforce lawyers.
I was working from .NET, but you should be able to to make the same requests from apex.
Firstly, you can get a list of reports in XML from: https://instance.salesforce.com/servlet/servlet.ReportList (replacing instance with the actual server instance, such as na1)
Note: Not all session types will have sufficient access to this URL. For instance, an API only session will return: <?xml version="1.0"?><result>Invalid session.</result>
Once you have extracted the required report Id (00O key prefix) you can then request the report data in either CSV or HTML.

*

*CSV https://instance.salesforce.com/00Ox0000000xxxx?export=1&enc=UTF-8&xf=csv

*HTML https://instance.salesforce.com/00Ox0000000xxxx?export=1&enc=UTF-8&xf=xls (Last time I checked this was HTML rather than a native Excel file format. Excel does the conversion when it is opened).

As for working with the CSV output, I found Parse a CSV with APEX but I haven't tested it yet.
If you want to get fancy, you can set filters for the report too. See BUILDING SALESFORCE CUSTOM LINKS - Linking to Reports for the pv0, pv1... query string parameters.
Reference:

*

*Progmatic Access to Salesforce.com Reports This post was from 2006, but shows that the approach has been working for a several years now. That still doesn't mean it might not work tomorrow.

A: Just to clarify for fellow rookies how will find this, when the question was asked you could access your report data programatically, but you had to use some hacky, and prone to errors methods.
This is all fixed  you can now access your reports via the API. Winter '14 release added API access to Reports.
Documentation here - http://www.salesforce.com/us/developer/docs/api_analytics/index.htm
Go to town on those custom dashboards etc.

A: No, currently there's no API to access the results of running a report.

A: Yes, but no.
Everything you need to know about the report is available via the metadata API. So, technically you could use that and generate the result set based on what the metadata api tells you about the report.
However, as far as I am aware, there is no existing tool to do this. So, you would need to implement it yourself.

A: Yes it is possible and it's pretty easy too!
    System.debug('describeReport: '+Reports.ReportManager.describeReport(reportId));

    //Reports.ReportResults results = Reports.ReportManager.runReport(reportId, true); // with detail
    Reports.ReportResults results = Reports.ReportManager.runReport(reportId); // without detail
    System.debug('runReport results: '+results);
    Reports.ReportFact fact0T = results.getFactMap().get('0!T');
    System.debug('getFactMap(0!T): '+fact0T);
    LIST<Reports.SummaryValue> fact0Taggregates = fact0T.getAggregates();

    // from run to run the report will not have the same "sections" in its grouping...so we can't but sure that the key 0_3!T will always contains the Feb 2017, Proposal/Price Quote
    label1 = fact0Taggregates[0].getLabel();
    value1 = (Decimal)fact0Taggregates[0].getValue();
    label2 = results.getFactMap().get('1!T').getAggregates()[0].getLabel();
    value2 = (Decimal)results.getFactMap().get('1!T').getAggregates()[0].getValue();
    label3 = results.getFactMap().get('0_3!T').getAggregates()[0].getLabel();
    value3 = (Decimal)results.getFactMap().get('0_3!T').getAggregates()[0].getValue();

    // we can rely for sure on this way to get what we want in the report
    Reports.Dimension groupingDownDim = results.getGroupingsDown();
    List<Reports.GroupingValue> firstLevelGrouping = groupingDownDim.getGroupings();

    // first level of grouping
    for (Reports.GroupingValue gv : firstLevelGrouping) {

        String key1;
        if (gv.getLabel() == 'February 2017') {

            key1 = gv.getKey();
            labelForSure1 = results.getFactMap().get(key1+'!T').getAggregates()[0].getLabel(); // will always contains Feb 2017 total

            // second level of grouping
            List<Reports.GroupingValue> secondLevelGrouping = gv.getGroupings();
            for (Reports.GroupingValue gv2 : secondLevelGrouping) {

                if (gv2.getLabel() == 'Proposal/Price Quote') {

                    String key2 = gv2.getKey();
                    labelForSure3 = results.getFactMap().get(key2+'!T').getAggregates()[0].getLabel(); // will always contains the Feb 2017, Proposal/Price Quote
                    break; // I don't have all night!
                }
            }
        } else if (gv.getLabel() == 'January 2017') {

            key1 = gv.getKey();
            labelForSure2 = results.getFactMap().get(key1+'!T').getAggregates()[0].getLabel(); // will always contains Jan 2017 total
            break; // I rest my case!
        }
    }

Ref:

*

*Reports Namespace

*ReportManager Class

A: Yes ... and it works fine !
http://brendansterne.com/2012/12/11/download-scrape-salesforce-reports-in-4-lines-of/
The solution above use's Python and the lib "Requests".
You can found the lib and its installation instructions here : http://docs.python-requests.org/en/latest/user/install/
It is very easy to install and to use.
Enjoy !


text:
Q: How do I make a dictionary with multiple values per key from two separate lists? I'm trying to create a dictionary that has multiple values per key. For example:
top_10 = ['Volkswagen_Golf_1.4', 'BMW_316i', 'Ford_Fiesta', 'BMW_318i', 'Volkswagen_Polo', 'BMW_320i', 'Opel_Corsa', 'Renault_Twingo', 'Volkswagen_Golf', 'Opel_Corsa_1.2_16V']

common_brands = ['volkswagen', 'bmw', 'opel', 'mercedes_benz', 'audi', 'ford']

I want to create a dictionary that looks like this:
{'volkswagen': ['Volkswagen_Golf_1.4', 'Volkswagen_Polo', 'Volkswagen_Golf'], 'bmw': ['BMW_316i', 'BMW_318i', 'BMW_320i'], 'opel': ['Opel_Corsa', 'Opel_Corsa_1.2_16V'],'ford': ['Ford_Fiesta'], 'Renault': ['Reanault_Twingo']}

With the code I've tried, I can only get one model per brand, and I can't find a way to add the brands that aren't in the common_brands list.
models_by_brand = {}

for brand in common_brands:
    for model in top_10:
        if brand in model.lower():
            models_by_brand[brand] = [model]

models_by_brand

Output:
{'bmw': ['BMW_320i'],
 'ford': ['Ford_Fiesta'],
 'opel': ['Opel_Corsa_1.2_16V'],
 'volkswagen': ['Volkswagen_Golf']}

A: You could use defaultdict and split the name of the vehicles to get the brand (if these are normalized):
from collections import defaultdict

models_by_brand = defaultdict(list)

for model in top_10:
    brand = model.lower().split('_')[0]
    models_by_brand[brand].append(model)

By using defaultdict, you  can write models_by_brand[brand].append(model) and if there are currently no models for brand in the dictionary, an empty list will be created and used.

A: If you want to keep the structure of your code, use a list:
models_by_brand = {}

for brand in common_brands:
    model_list=[]
    for model in top_10:
        if brand in model.lower():
            model_list.append(model)
    models_by_brand[brand] = model_list
models_by_brand = {k:v for k,v in models_by_brand.items() if v!=[]}

Output:
{'volkswagen': ['Volkswagen_Golf_1.4', 'Volkswagen_Polo', 'Volkswagen_Golf'],
 'bmw': ['BMW_316i', 'BMW_318i', 'BMW_320i'],
 'opel': ['Opel_Corsa', 'Opel_Corsa_1.2_16V'],
 'ford': ['Ford_Fiesta']}

@Holt's answer would be the most efficient answer, though.

A: # The following code should work just fine.
top_10 = ['Volkswagen_Golf_1.4', 'BMW_316i', 'Ford_Fiesta', 'BMW_318i', 'Volkswagen_Polo', 'BMW_320i', 'Opel_Corsa',
          'Renault_Twingo', 'Volkswagen_Golf', 'Opel_Corsa_1.2_16V']

common_brands = ['volkswagen', 'bmw', 'opel', 'mercedes_benz', 'audi', 'ford']

result = {}
cars = []
# For each car brand
for k in common_brands:
    # For each car model
    for c in top_10:
        # if car brand present in car model name append it to list
        if k.lower() in c.lower():
            cars.append(c)
    # if cars list is not empty copy it to the dictionary with key k
    if len(cars) > 0:
        result[k] = cars.copy()
    # Reset cars list for next iteration
    cars.clear()

print(result)

A: The traditional solution to your problem would be to check if the key exists in your dictionary. If it does not, you initialise it to an empty list, else you append to that list.
models_by_brand = {}

for brand in common_brands:
    for model in top_10:
        if brand in model.lower():
            if brand not in models_by_brand:
                models_by_brand[brand] = list()
            models_by_brand[brand].append(model)

print(models_by_brand)

The other solution would be to use a defaultdict. Defaultdict is used to pre-initialise a default value for any key.
from collections import defaultdict
models_by_brand = defaultdict(list)

for brand in common_brands:
    for model in top_10:
        if brand in model.lower():
            models_by_brand[brand].append(model)

print(models_by_brand)


text:
Q: Edit RGB values in an image dependant on each pixel's red value What I want to do is take every pixel of an image and make the green and blue values match the red value of each pixel.
I've tried converting to black and white in Paint.net but it averages the RGB values and doesn't give me the right shades of black/grey.
I've just started learning Python and I don't know where to start for something like this. I would think there's a different program that would let me do this but I'm not sure where to look.

A: from PIL import Image
import requests
from io import BytesIO
response = requests.get('https://www.ricoh-imaging.co.jp/english/products/q-s1/ex/img/bod_mainImg_01.jpg')
img = Image.open(BytesIO(response.content)).resize((400, 300)).convert('RGB') # make sure to be in RGB format
img

Then the convert to a numpy array and you can easily copy the red (0) channels to green and blue channels (1 and 2).
import numpy as np
arr = np.array(img)
arr[:,:,1] = arr[:,:,0]
arr[:,:,2] = arr[:,:,0]
Image.fromarray(arr)


text:
Q: State of modifier keys in fullscreen flash content I have a small browser-based tool which works best in fullscreen. I'm adding in keyboard shortcuts, but I've run into a limitation of Flash: it blocks most keyboard access when in fullscreen mode.
The SPACE key does work, and since I've only got a few commands which are semi-related it would be OK to make them all work with the space key (SPACE, alt+SPACE, etc). But the modifier keys don't get sent in fullscreen mode either!
Is there a way around this? (some other way of reading the modifier keys' states?)
(I've heard about interactive fullscreen mode in flash player 11, but this is no good for me; most of the audience are on older versions and I don't want the "allow" message box)

A: I'm afraid that the interactive fullscreen mode for Flash Player 11.3 or later is your only option.  Othherwise you're limited to, I believe, the space and arrow keys.  However, I wouldn't be too concerned with the Allow dialog that appears at the top of the screen when entering full screen mode as it's been quite common for a while now - users will expect it.
You might also consider distributing an AIR application instead of a browser-resident flash application if you want to avoid the keybaord limitations and the dialog popup.


text:
Q: Should I downvote feature-requests I don't like? This is similar to Should we allow downvotes on Meta feature-requests if they just don't *like* the *feature*?, but that question was (incorrectly) closed as a duplicate of Encouraging people to explain downvotes and Down-voting on questions - Require a comment below a certain rep?. Additionally, I feel this question could be more clearly asked (or I misunderstood it).

What is the significance of an upvote or downvote on a feature-request?
Like the rest of SE, the title text for upvote is

This question shows research effort; it is useful and clear

For a downvote,

This question does not show any research effort; it is unclear or not useful

But for feature requests, some believe that an upvote means

I agree with this feature suggestion

and that a downvote means

I disagree with this feature suggestion

These seem quite different to me. When I see a feature request that is well researched, clear, and perhaps even useful (in that it is valid, and a reasonably good idea), but with which I ultimately firmly disagree, should I vote it down?

A: This is answered (emphasis original):

Voting is different on meta.
...
Unlike normal Stack Exchange sites, Meta invites the community to discuss, debate and propose changes to the way the community itself behaves, as well as how the software itself works. On posts tagged feature-request, voting indicates agreement or disagreement with the proposed change rather than just the quality or usefulness of the post itself.

Thanks to @hims056 and @Mat for pointing that out. It turns out to be surprisingly difficult find "meta meta" answers with a search engine :P
A different title tip would make this far more clear.


text:
Q: Google Compute Engine: Internal DNS server and issues with the resolving Since google Compute engine does not provides internal DNS i created 2 centos bind machines which will do the resolving for the machines on GCE and forward the resolvings over vpn to my private cloud and vice versa.
as the google cloud help docs suggests you can have this kind of scenario. and edit the resolv.conf on each instance to do the resolving.
What i did was edit the ifcg-eth0 to disable the PEERDNS and in /etc/resolv.conf
i added the search domain and top 2 nameservrs my instances.
now after one instance gets rebooted..it wont start again because its searching for the metadata.google.internal domain
Jul  8 10:17:14 instance-1 google: Waiting for metadata server, attempt 412
What is the best practice in this kind of scenarios?
ty
Also i need the internal DNS for to do the poor's man round-robin failover, since GCE does not provides internal balancers.

A: As mentioned at https://cloud.google.com/compute/docs/networking:

Each instance's metadata server acts as a DNS server. It stores the DNS entries for all network IP addresses in the local network and calls Google's public DNS server for entries outside the network. You cannot configure this DNS server, but you can set up your own DNS server if you like and configure your instances to use that server instead by editing the /etc/resolv.conf file.

So you should be able to just use 169.254.169.254 for your DNS server. If you need to define external DNS entries, you might like Cloud DNS. If you set up a domain with Cloud DNS, or any other DNS provider, the 169.254.169.254 resolver should find it.
If you need something more complex, such as customer internal DNS names, then your own BIND server might be the best solution. Just make sure that metadata.google.internal. resolves to 169.254.169.254.

A: OK, I just ran in to this.. but unfortunately there was no timeout after 30 minutes that got it working. Fortunatly nelasx had correctly diagnosed it, and given the fix. I'm adding this to give the steps I had to take based on his excellent question and commented answer. I've just pulled the info I had to gather together in one place, to get to a solution.
Symptoms: on startup of the google instance - getting connection refused
After inspecting serial console output, will see:
Jul 8 10:17:14 instance-1 google: Waiting for metadata server, attempt 412

You could try waiting, didn't work for me, and inspection of https://github.com/GoogleCloudPlatform/compute-image-packages/blob/master/google-startup-scripts/usr/share/google/onboot
# Failed to resolve host or connect to host.  Retry indefinitely.
6|7) sleep 1.0
log "Waiting for metadata server, attempt ${count}"

Led me to believe that will not work.
So, the solution was to fiddle with the disk, to add in nelasx's solution:
"edit ifcfg-eth and change PEERDNS=no edit /etc/resolv.conf and put on top your nameservers + search domain edit /etc/hosts and add: 169.254.169.254 metadata.google.internal"
To do this,

*

*Best to create a snapshot backup before you start in case it goes awry

*Uncheck "Delete boot disk when instance is deleted" for your instance

*Delete the instance

*Create a micro instance

*Mount the disk
sudo ls -l /dev/disk/by-id/* # this will give you the name of the instances
sudo mkdir /mnt/new
sudo mount /dev/disk/by-id/scsi-0Google_PersistentDisk_instance-1-part1 /mnt/new
where instance-1 will be changed as per your setup

*Go in an edit as per nelasx's solution - idiot trap I fell for - use a relative path - don't just sudo vi /etc/hosts use /mnt/new/etc/hosts - that cost me 15 more minutes as I had to go through the: got depressed, scratched head, kicked myself cycle.

*Delete the debug instance, ensuring your attached disk delete option is unchecked

*Create a new instance matching your original with the edited disk as your boot disk and fire it up.


text:
Q: Running two GPU in parallel (tensorflow) will suddenly shut off computer I am using deep learning in my research and I added a second 1080ti to my computer, because using only one would not let me finish my experiments in time. Tensorflow will utilize almost 100% GPU and some CPU.
Problem: If I run tensorflow with both GPUs the system turns off after about 30s and will not POST. I have to remove the first gpu to power on again (afterwards I can add the first GPU again).
PC specification:

*

*1x be quiet! Dark Power Pro 11 750W ATX 2.4 (BN252)

*1x ASUS Prime X370-Pro (90MB0TD0-M0EAY0)

*1x AMD Ryzen 5 1600 (TDP: 65W), 6x 3.20GHz, boxed (YD1600BBAEBOX)

*2 x MSI
GeForce GTX 1080 Ti (250 W) Gaming X 11G, 11GB GDDR5X, DVI, 2x HDMI, 2x DP
(V360-001R)

*1x Samsung SSD 850 EVO 250GB, SATA (MZ-75E250B)

*3x Seagate IronWolf NAS HDD 10TB, SATA 6Gb/s (ST10000VN0004)

*1x G.Skill Aegis DIMM Kit 16GB, DDR4-3000, CL16-18-18-38 (F4-3000C16D-16GISB)

I use PCIEX16_1 and PCIEX16_2 for the GPUs.
What I tried so far:

*

*Running tensorflow with each of the GPUs (100% GPU utilization) --> OK for both GPUs

*Checking the temperatur of both GPUs while using GPUs in parallel:  --> OK max temp <80°C

*Double checked that nothing is overlocked --> OK

Can someone please guide me trough the next steps to figure out the problem?
Thank you all for your help.

A: A PC shutting down without warning can be many things, but two common problems include:

*

*Overheating something. Typically this will trigger #PROCHOT or similar and a full instant power off.

*Drawing to much power and triggering the safety in the PSU.

You descripbe a situation which you run max power on two very hungry graphics cards, which leads me to suspect the second problem.
Lookign at your graphics card they draw up to a massive 250 Watt each. Theroretical 75Watt of that may be supplied by the motherboards PCI-e slot. If a card needs more power it may add a 6 pin connector and draw up to 75 Watt from that, or a 8 pin connector and draw upto 150 Watt from it.
You card uses two 8 pins connectors and it likely draws most power from those.
(Drawing from the MB is not really recommended unless you want to heat that up. If the choice is for the PCI-e power connector that is the preferred choice).
How you have two cards and a total of 4 8 pins connectors. So in theory you need:
 * 4x 150W output from somewhere, or
 * 2x 300W output and a splitter from pins to 2x 8 pins
 * Or a similar setup where two 6 pins somehow merge to feed 1 pins.
Now your PSU is a great one. It has no fewer than four such plugs. So in theory you are fine.
but...
It is not guaranteed to be able to supply 600W on a single of those plugs. So you cannot use 1 PCI-e power connector on your modular PSU and split it in four.
If you lack the correct cables and draw from fewer plugs on the PSU then you may overload one of those plugs. That can lead to fancy sparks, or in case of a good PSU, overcurrent protection and instant shutdown.
THe latter is likely what happened on your PC.

It gets more complicated because your PSU als has a button to rebalance between different rails. I'll leave that part out of the answer since it would double or triple the size.


text:
Q: Full HTTP URL for IIS URL Rewrite module Is any possibility to match whole url in IIS URL Rewrite module?
I need to write the next condition:
<add input="{FULL_URL}" negate="true" pattern="^https:\/\/www\..+[^/]$" />

I want to ignore all urls that starts with https://www and ended with /.
Does {FULL_URL} or something else exist?

A: In IIS rewrite exists variable {CACHE_URL} which should be suitable for you.
This variable contains full URL including query string. Ex: http://localhost:8080/Home/About?id=5
You can find full list of variables with explanation here: https://msdn.microsoft.com/en-us/library/ms524602(v=vs.90).aspx


text:
Q: Is it possible for using Dlib in android like OpenCV? Well i need a clear site or information on using Dlib in android. I searched in the net throughout to get a sample application in android using Dlib but still i can't find a one. I am not still sure whether we can use Dlib methods in android for generating .a file so that we can use it as a library. Can anyone suggest me or guide me on how to use Dlib in android and what is its purpose.

A: This issue has already been dealt here. You can refer to https://github.com/tzutalin/dlib-android for an example. It describes porting dlib to Andriod platform as dynamic or static library with some samples built.


text:
Q: If $\mathcal{M}$ is an infinite $\sigma$-algebra, then $|\mathcal{M}| \geq \mathfrak{c}$ Let $\mathcal{M}$ be an infinite $\sigma$-algebra. Show that $|\mathcal{M}| \geq \mathfrak{c}$
I was wondering if this procedure works for any representation of numbers in $[0,1)$ to show that an infinite $\sigma$-algebra has cardinality greater than or equal to $\mathfrak{c}$. I saw this done using binary representations of numbers in $[0,1)$. Would it be the same approach using ternary representations?
Let $\{A_n\}_{n \in \mathbb{N}}$ is an infinite sequence of disjoint sets in $\mathcal{M}$. For any $x \in [0,1)$ fix a ternary representation $x=\sum\limits_{k=1}c_k3^{-k}, c_k \in \{0,1,2\}$. Define a function $\phi:[0,1) \rightarrow \mathcal{M}$ by $\phi(\sum\limits_{k=1}c_k3^{-k})=\bigcup\limits_{\substack{k \geq1\\c_k=1}}A_k$. Since $\phi$ is injective, $|\mathcal{M}| \geq \mathfrak{c}=|[0,1)|$. Would this be correct? Finally, how can one show the map $\phi$ is injective.
Also, what are more intuitive ways to do this problem?

A: The map is not injective. Consider $c_{1}=1$ and $c_{k}=0$ for $k>1$ as well as $b_{1}=1$ and $b_{k}=2$ for $k>1$. Then $$x=\sum_{j=1}^{\infty}c_{k}3^{-k}\ne\sum_{i=1}^{\infty}b_{i}3^{-i}=y$$
but $\phi(x)=\phi(y)=A_{1}$.
The simplest in my opinion is to use binary sequences $\{0,1\}^{\mathbb{N}}$ instead of ternary representation since you avoid this kind of counter-example. Note also that this is somewhat different from a binary representation in that a number can have multiple binary representations ($1/2=\sum_{n=2}^{\infty}1/2^{n}$) while binary sequences which differ at a particular entry can be considered different.
For completeness I'll mention the map:
$$\phi:\{0,1\}^{\mathbb{N}}\to\mathcal{M} \quad (b_{k})\mapsto\bigcup_{k, b_{k}=1}A_{k}$$ The uncountability of $\{0,1\}^\mathbb{N}$follows readily from a Cantor diagonal type argument.


text:
Q: Flutter refresh google map every time after come back from second screen I have a HomeScreen which is StatefullWidget and incorporate Googlemap here, Over map multiple floating button like Notification, settings etc; Problem is that, when i am go to second screen like Notification and come to Home screen again, Every time map reloads & show black screen as well. Really its bothering me a lot. So how to solved or take control over reloading or not reloading and solved black screen issues??
Version:
environment:
sdk: ">=2.7.0 <3.0.0"
google_maps_flutter: ^0.5.28+1


text:
Q: Nginx upstreams for POSTs and GETs Is it possible for nginx to handle post and gets with different upstreams?
Let's say I've got an url 'http://example.com/task'. The 'task' uses GET and POST method. Can I configure nginx to proxy_pass GETs to upstreamA and POSTs to upstreamB?
Thank you for your reply :)


text:
Q: Core Data segue issue with saving changes I had my project working, and decided I will introduce a settings page for users to make basic adjustments.
Entity name: "Setting"
Attribute: "settingTimeOverrideSlider"
-> I created the NSManagedObject Subclass

I added (and embedded) the SettingsViewController, the segue, named the segue.
On that page I'm using a button to save changes. This button called a method in my CoreViewController via [super saveAndDismiss] and I know it gets in there (checked with NSLog).
Here's the method:
-(void)saveAndDismiss
{
    NSLog(@"In Save And Dismiss");
    NSError *error = nil;
    if ([self.managedObjectContext hasChanges]) {
        NSLog(@"In Save And Dismiss - has changes");
        if (![self.managedObjectContext save:&error]) {                 // save failed
            NSLog(@"Save failed: %@", [error localizedDescription]);
        } else {                                                        // save succeeded
            NSLog(@"Save Succeeded");
        }
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

But for some reason, it never gets into the first if(), where I have my next debug NSLog.
I believe my problem is my prepareForSegue in my main page, as all the other segues are going to tableViews. I'm not sure if I have my segue setup right
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UITableViewCell*)sender
{
    // segues 1-3
    if ([[segue identifier]isEqualToString:@"segue4"])
    {
        // some other Segue
    }

    if ([[segue identifier]isEqualToString:@"toSettings"])
    {
        UINavigationController *settingsViewController = segue.destinationViewController;

        SettingsViewController *editSettingsViewController = (SettingsViewController*)settingsViewController.topViewController;

        NSIndexPath *indexPath = [self.fetchedResultsController objectAtIndexPath:0];

        Setting *editSettings = (Setting*)[self.fetchedResultsController objectAtIndexPath:indexPath];

        editSettingsViewController.editSetting = editSettings;
    }
}

In my SettingsViewController.h, I subclass my SettingsViewController to be part of my CoreViewController as so:
// SettingsViewController.h
#import <UIKit/UIKit.h>
#import "Setting.h"
#import "CoreViewController.h"

@interface SettingsViewController : CoreViewController
@property (nonatomic, strong)Setting editSetting;

@property (nonatomic, strong)Setting *editSetting;
@property (strong, nonatomic) IBOutlet UIBarButtonItem *editSaveButton;
@property (strong, nonatomic) IBOutlet UITextField *timeOverrideTextlabel;
@property (strong, nonatomic) IBOutlet UISegmentedControl *timeFormatSelector;
@property (strong, nonatomic) IBOutlet UISwitch *timeOverrideSlider;

- (IBAction)cancel:(UIBarButtonItem *)sender;
- (IBAction)editSave:(UIBarButtonItem *)sender;
- (IBAction)timeOverride:(UISwitch *)sender;

Now as I'm trying to retrieve information from persistent memory, do I need to change the above statement to
@interface SettingsViewController : CoreViewController
    <NSFetchedResultsControllerDelegate>

?
//SettingsViewController.m
#import "SettingsViewController.h"
#import "AppDelegate.h"

@interface SettingsViewController ()

@property (nonatomic, strong)NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong)NSFetchedResultsController *fetchedResultsController;

Can't seem to wrap my head around what's wrong here, but I'm sure it is in my prepareForSegue method (listed above).
Like I said, all the other segue if-statement where used to link to TableViews and work fine.
I'm trying to set my Attribute like this
editSetting.settingTimeOverrideSlider = @YES;

and then I call
[super saveAndDismiss];

- (IBAction)editSave:(UIBarButtonItem *)sender
{
    if ([_editSaveButton.title isEqualToString:@"Edit"])
    {
        [self setTitle:@"Edit Settings"];

        _timeFormatSelector.userInteractionEnabled = YES;
        _timeOverrideSlider.userInteractionEnabled = YES;

        _editSaveButton.title = @"Save";
    } else if ([_editSaveButton.title isEqualToString:@"Save"])
    {
        [self setTitle:@"Settings"];

        NSLog(@"SAVING-SVC");
        editSetting.settingTimeOverrideSlider = @YES; // THIS IS WHAT SHOULD CHANGE IN CORE DATA
        [super saveAndDismiss];
    }
}

A: You shouldn't send in the fetchedResultsController nor the managedObjectContext to the SettingsViewController. You should limit the amount of information that needs to be configured where possible. You are already sending in the editSetting, which is enough information to achieve the results you want.
In SettingsViewController, delete the following two lines:
@property (nonatomic, strong)NSManagedObjectContext *managedObjectContext;
@property (nonatomic, strong)NSFetchedResultsController *fetchedResultsController;

Instead, you should access the managed object context from the NSManagedObject directly.
Your saveAndDismiss should now look like this:
-(void)saveAndDismiss
{
    NSLog(@"In Save And Dismiss");
    NSError *error = nil;
    if ([self.editSetting.managedObjectContext hasChanges]) {
        NSLog(@"In Save And Dismiss - has changes");
        if (![self.editSetting.managedObjectContext save:&error]) {                 // save failed
            NSLog(@"Save failed: %@", [error localizedDescription]);
        } else {                                                        // save succeeded
            NSLog(@"Save Succeeded");
        }
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

Notice how self.managedObjectContext became self.editSetting.managedObjectContext.
Better yet, you can probably change [self.editSetting.managedObjectContext hasChanges] to [self.editSetting isUpdated].


text:
Q: how to disconnect the call in android 4.1.2 nexus programmatically i am able to disconnect the call programmatically for incoming unknown number call in android 2.2. But in android 4.1, its not working.
Working Code to disconnect the call in android 2.2:
private Class c;
private  Method m;
private com.android.internal.telephony.ITelephony telephonyService;
public void onReceive(Context context, Intent intent)
{
   Bundle b = intent.getExtras();
   String state = b.getString(TelephonyManager.EXTRA_STATE);
   if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING))
   {
     TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
     c = Class.forName(tm.getClass().getName());
     m = c.getDeclaredMethod("getITelephony");
     m.setAccessible(true);
     telephonyService = (ITelephony) m.invoke(tm);
     telephonyService.silenceRinger();
     telephonyService.endCall();
   }
}

Please help me.Thanks in advance
Finally I got a solution for 2.6 version .
MODIFY_PHONE_STATE permission is no longer working on silenceRinger() since 2.3+, but endCall is just fine. So the solution is to comment out the call to silenceRinger().

A: MODIFY_PHONE_STATE is no longer working on silenceRinger() since 2.3+, but endCall is just fine.
So the solution is to comment out the call to silenceRinger().
And a simple example:
 http://androidbridge.blogspot.ro/2011/05/how-to-answer-incoming-call-in-android.html

Cheers


text:
Q: How do I produce plain binary from object files? How should I produce raw binary file from two object (.o) files?
I want the plain binary format produced by nasm -f bin when compiling a .asm file, but for .o files.
By a plain binary, I mean a file which contains only the instructions, not some extra information, as many executable files contain a lot of extra helpful information.
See http://www.nasm.us/doc/nasmdoc7.html for information on that.
PS: I want to make a "plain binary" to start in QEMU.

A: This brings back memories. I'm sure there is a better way to do this with linker scripts, but this is how I did it when I was young and stupid:
# compile some files
gcc -c -nostdlib -nostartfiles -nodefaultlibs -fno-builtin kernel.c -o kernel.o
gcc -c -nostdlib -nostartfiles -nodefaultlibs -fno-builtin io.c -o io.o

# link files and place code at known address so we can jump there from asm
ld -Ttext 0x100000 kernel.o io.o -o kernel.out

# get a flat binary
objcopy -S -O binary kernel.out kernel.bin

The file kernel.c started with
__asm__("call _kmain");
__asm__("ret");

void kmain(void) { ... }

The fun part is writing the loader in assembler.

A: ld --oformat binary is a more direct option:
ld --oformat binary -o main.img -Ttext 0x7C00 main.o

The downside of this method is that I don't think it is possible to reuse the symbols to debug, as we'd want something like:
qemu-system-i386 -hda main.img -S -s &
gdb main.elf -ex 'target remote localhost:1234'

So in that case you should stick to objcopy. See also: https://stackoverflow.com/a/32960272/895245
Also make sure that you use your own clean linker script: https://stackoverflow.com/a/32594933/895245
Repository with working examples for some common cases:

*

*boot sectors

*multiboot interfacing with C
Similar question: How to generate plain binaries like nasm -f bin with the GNU GAS assembler?


text:
Q: Auto-Upgrade to 4.2.2 fails because theme functions.php is included instead of wp-includes/functions.php I'm trying to upgrade WordPress to the latest 4.2.2.  On the screen, I'm seeing:

Downloading update from https://downloads.wordpress.org/release/wordpress-4.2.2-no-content.zip…
Unpacking the update…
Could not create directory.
Installation Failed

And in the php error log, I get

 PHP Fatal error:  Call to undefined function add_action() in /home/userhome/public_html/wp-content/themes/launchframe/functions.php on line 81, referer: http://example.com/wp-admin/update-core.php?action=do-core-upgrade

What appears to be happening is the theme functions.php file is being included instead of the wp-includes/functions.php.  This is new though - previous upgrades have gone fine.  I've tried including the "missing" files in my theme's functions.php (i.e.)
require_once('/home/userhome/public_html/wp-includes/plugin.php');
require_once('/home/userhome/public_html/wp-includes/theme.php');
require_once('/home/userhome/public_html/wp-includes/shortcodes.php');
require_once('/home/userhome/public_html/wp-includes/media.php');

But ultimately that failed because more and more files ended up being referenced.  I also tried calling wp-load.php from my theme's functions.php file, but that ended up loading my theme again and got "function already defined" errors.
Any suggestions?
Thanks

A: I am not confident your guess at "being included instead" is accurate. The inclusion of core file is hardcoded in wp-settings.php pretty hard, it would be extremely challenging to subvert under normal circumstances.
I have trouble imaging scenario in which functions.php of the theme will be loaded, but add_action() will be unavailable. This simply shouldn't ever happen under normal mechanics.
My best guess is that your installation is strangely customized or otherwise corrupt.
I would start looking into specifics of strange theme's functions.php load, probably by dumping wp_debug_backtrace() from there for starters.


text:
Q: What Type of Test Should Be Used to Determine Between-Group Differences with 2 Separate Conditions? I've been working on a project where I've generated a multivariate graph of the error of a filtered image from a pure signal for four different types of frequency filters and two varying conditions (gaussian noise added to the signal pre-filtering and the cutoff frequency for the filter).
In total there are 600 different combinations of conditions, with trials run on 6 different images (that's why it kinda smears, the individual "points" are actually clusters of 6 points). I would like to find some way of providing a p-value for the distribution of data as a whole as opposed to my current idea of running an ANOVA 600 times. Another idea I had was to look into running a MANOVA, but I'm unsure of how to implement one since I only have one output variable.
Does there exist such a test? Am I misinterpreting what a MANOVA requires? Should I actually run an ANOVA 600 times?


text:
Q: JSON.Net to display Name and Value pairs for Enums A bit of a newbie here using JSON.Net in C# -
string JSONOutput = (JsonConvert.SerializeObject(product));

When I am serializing a Product object in my solution, I'm getting JSON out that looks like this :
{
   "product":{
      "displayStatus":1,
      "drugClass":1,
      "drugType":1
   }
}

The displayStatus, drugClass and drugType values are all from Enums, so the output I'm really wanting is this :
{
   "product":{
      "displayStatus":{
         "name":"Visible",
         "value":1
      },
      "drugClass":{
         "name":"Generic",
         "value":1
      },
      "drugType":{
         "name":"Drug",
         "value":1
      }
   }
}

Does anyone know how to accomplish this? I've been looking at the StringEnumConverter, but the only thing I can see there is that it just returns the string of the Enum instead of the integer value - whereas I would like both.

A: Note, you shouldn't really need anything like this, there are several out of the box way to convert enums. For instance StringEnumConverter. Eg
[JsonConverter(typeof(StringEnumConverter))]

However, for sheer morbid curiosity and academic interest
Given a converter
public class SomeConverter : JsonConverter
{

   public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
   {
      writer.WriteStartObject();
      writer.WritePropertyName("name");
      writer.WriteValue(value.ToString());
      writer.WritePropertyName("value");
      writer.WriteValue(Convert.ChangeType(value,typeof(int)));
      writer.WriteEndObject();
   }

   public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
   {
      // ill leave this up to your imagination
      throw new NotImplementedException();
   }

   public override bool CanConvert(Type objectType)
   {
     return objectType == typeof(Enum);
   }
}

Enums
public enum Bob
{
   one,
   two
}
public enum Blerge
{
   Asd,
   BFG
}

And Class
public class Product
{
   [JsonConverter(typeof(SomeConverter))]
   public Bob Bob { get; set; }

   [JsonConverter(typeof(SomeConverter))]
   public Blerge Blerge { get; set; }
}

Usage
var asd = new Product()
{
   Bob = Bob.two,
   Blerge = Blerge.Asd
};

var bla = JsonConvert.SerializeObject(asd, Formatting.Indented);
Console.WriteLine(bla);

Output
{
  "Bob": {
    "name": "two",
    "value": 1
  },
  "Blerge": {
    "name": "Asd",
    "value": 0
  }
}

A: You can take advantage of the JsonConverter<T>, like this:
public class EnumConverter<T> : JsonConverter<T> where T : System.Enum
{
    public override T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer)
        => throw new NotImplementedException();

    public override void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer)
    {
        var nameAndValue = new { Name = value.ToString("g"), Value = value.ToString("d") };
        var semiJson = JObject.FromObject(nameAndValue);
        semiJson.WriteTo(writer);
    }
}

*

*I've constrained the T to System.Enum

*In the WriteJson I've created an anonymous type and used the Enum Format strings to retrieve the desired values

*I had to create a JObject from the anonymous type because the JsonWriter does not support that directly

Then you can decorate your model class with the following attributes:
public class Product
{
    [JsonConverter(typeof(EnumConverter<DisplayStatus>))]
    public DisplayStatus DisplayStatus { get; set; }
    [JsonConverter(typeof(EnumConverter<DrugClass>))]
    public DrugClass DrugClass { get; set; }
    [JsonConverter(typeof(EnumConverter<DrugType>))]
    public DrugType DrugType { get; set; }
}

And finally the serialization logic looks like this:
var product = new Product()
{
    DisplayStatus = DisplayStatus.Visible,
    DrugClass = DrugClass.Generic,
    DrugType = DrugType.Drug,
};
var result = JsonConvert.SerializeObject(
    new { Product = product },
    new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });

The result will look like this:
{
   "product":{
      "displayStatus":{
         "Name":"Visible",
         "Value":"1"
      },
      "drugClass":{
         "Name":"Generic",
         "Value":"1"
      },
      "drugType":{
         "Name":"Drug",
         "Value":"1"
      }
   }
}

In order to fix the casing for Name and Value all you need to do is to pass the serializer to the FromObject:
var details = JObject.FromObject(nameAndValue, serializer);

After this the end result will look like as expected:
{
   "product":{
      "displayStatus":{
         "name":"Visible",
         "value":"1"
      },
      "drugClass":{
         "name":"Generic",
         "value":"1"
      },
      "drugType":{
         "name":"Drug",
         "value":"1"
      }
   }
}

UDPATE #1: Add Converters to the settings
As it was indicated in the comment the Product class could not be amended with JsonConverterAttributes. So, if you have this restriction then you can overcome on this by passing the converters via the JsonSettings object like this:
var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    Converters = new JsonConverter[] {
        new EnumConverter<DisplayStatus>(),
        new EnumConverter<DrugClass>(),
        new EnumConverter<DrugType>()
    }
};

var result = JsonConvert.SerializeObject(new { Product = product }, settings);

With this approach your model will be serialization attribute free :)


text:
Q: How to remove and destroy labels from arraylist I'm creating a chatting application in javafx. I'm displaying messages using labels and adding them in arraylist. Now i want to remove labels what should i do so that labels will be destroyed from scrollpane.
Here is code:
CONNECTION clientConnection=null;

@FXML ScrollPane chatScrollPane;
VBox chatVBox;
@FXML AnchorPane chatAnchorPane;

private List<Label> messages = new ArrayList<>();

int index = 0;

I'm adding messages like:
messages.add(new Label(m));

Should i assign new memory to messages so that garbage collector will remove labels from it?
eg?
 public void clearall(){
    /*for(int i=0;i<index;i++){

    }*/
    messages = null;
    System.gc();

    messages = new ArrayList<>();

    index = 0;

    System.out.println("cleared chat");
}

A: List has a clear() method, which will clear it.
Don't call System.gc(), that is almost never needed.
You don't show how you actually display the labels and how they actually get into the scroll pane, so I don't know if clearing the array list will actually clear the messages from the UI.  If you have further questions or issues, provide an mcve.


text:
Q: How combine two Google Maps API I use Google Maps API for two things on my website:
First for displaying map:
jQuery(document).ready(function($) {
function initialize_business() {
            var map_move = $(document).width() > 850 ? true : false;
            var map_center = new google.maps.LatLng(parseFloat($('#business_sidebar_map').attr('data-lat')), parseFloat($('#business_sidebar_map').attr('data-lng')));
            var map_options = {
                zoom: 14,
                center: map_center,
                zoomControl: false,
                scaleControl: false,
                draggable: false,
                scrollwheel: false,
                mapTypeControl: false,
                streetViewControl: false,
            };
            var map = new google.maps.Map(document.getElementById('business_sidebar_map'), map_options);

            new google.maps.Marker({
                position: map_center,
                map: map,
                icon: js_string.template_directory + '/images/marker.png'
            });
        }

        google.maps.event.addDomListener(window, 'resize', initialize_business);
        google.maps.event.addDomListener(window, 'load', initialize_business);

});

and for this map I need next api link:
<script src="https://maps.googleapis.com/maps/api/js"></script>

Secondly I use Google Map API for finding of GPS from my Address:
function google_geocoding() {
    var autocomplete = new google.maps.places.Autocomplete(document.getElementById('address'), {
        types: ['geocode'],
        componentRestrictions: {country: 'cz'},
    });
    autocomplete.addListener('place_changed', function() {
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            window.alert('Bohužel jsme nanašli žádnou lokaci');
            return;
        }
        document.getElementById('address_lat').value = place.geometry.location.lat();
        document.getElementById('address_lng').value = place.geometry.location.lng();
    });

}

and for this event I need next api link:
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&region=cz&callback=google_geocoding"></script>

In console I see next bug:
You have included the Google Maps API multiple times on this page.
So I probably need to combine Google script links to one, but I don't know how.
Thanks for help

A: I find solution:
Call google maps API once
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&region=cz">

Insted of callback param I simple Call the function so final script is:
jQuery(document).ready(function($) {
    if($('#business_sidebar_map').length > 0) {
        function initialize_business() {
            var map_move = $(document).width() > 850 ? true : false;
            var map_center = new google.maps.LatLng(parseFloat($('#business_sidebar_map').attr('data-lat')), parseFloat($('#business_sidebar_map').attr('data-lng')));
            var map_options = {
                zoom: 14,
                center: map_center,
                zoomControl: false,
                scaleControl: false,
                draggable: false,
                scrollwheel: false,
                mapTypeControl: false,
                streetViewControl: false,
            };
            var map = new google.maps.Map(document.getElementById('business_sidebar_map'), map_options);

            new google.maps.Marker({
                position: map_center,
                map: map,
                icon: js_string.template_directory + '/images/marker.png'
            });
        }

        google.maps.event.addDomListener(window, 'resize', initialize_business);
        google.maps.event.addDomListener(window, 'load', initialize_business);
    }

    if($('#address').length > 0) {
        function google_geocoding() {
            var autocomplete = new google.maps.places.Autocomplete(document.getElementById('address'), {
                types: ['geocode'],
                componentRestrictions: {country: 'cz'},
            });
            autocomplete.addListener('place_changed', function() {
                var place = autocomplete.getPlace();
                if (!place.geometry) {
                    window.alert('Bohužel jsme nanašli žádnou lokaci');
                    return;
                }
                document.getElementById('address_lat').value = place.geometry.location.lat();
                document.getElementById('address_lng').value = place.geometry.location.lng();
            });

            }
            google_geocoding();
        }

    });


text:
Q: Android navigation component back stack i created a nav graph with fragments fragA->fragB->fragC-fragD->fragE->fragF->fragG. From some push notification user must directly go to fragG with findNavController().navigate(R.id.fragG), and when user tap back button he must go to fragF, but now is back to first fragment of navigation graph because fragB->fragC-fragD->fragE->fragF is not added to back stack. It's possible to add this frag to stack when user navigate to last an press back button? Thanks.

A: It's not an official answer but it works as a workaround.
You can create the back stack manually by navigating sequentially.
fun openGFromPushNotification(){
   navigate(R.id.fragB)
   navigate(R.id.fragC)
   navigate(R.id.fragD)
   navigate(R.id.fragE)
   navigate(R.id.fragF)
   navigate(R.id.fragG)
}


text:
Q: React Native Render Issue I am building a simple weather app and having some issues render the forecast. Not sure if it is the styling. I know the api call through the browser and no errors come from the call in android studio
App.JS
import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TextInput
} from 'react-native';
import Forecast from './components/Forecast';
import Weather from './components/Weather'

class WeatherApp extends Component {
  constructor(props){
    super(props);
    this.state = {
    //setting the state to an empty string while keeping the forecast null
      zip: "",
      forecast: null
    };
  }
  _handleTextChange = event => {
    //this function handles the text change when typing in a zip
    let zip = event.nativeEvent.text;
    Weather.fetchForecast(zip).then(forecast => {
      this.setState({forecast: forecast})
    })
  }
  render() {
    let content = null;
    if(this.state.forecast !== null) {
      content = (
        <Forecast
          main = {this.state.forecast.main}
          description = {this.state.forecast.description}
          temp = {this.state.forecast.temp}
        />
      )
    }
  return (
    <View style = {styles.container}>
      <Text style = {styles.welcome}>
        Please Input {this.state.zip}
      </Text>
      <TextInput
        style = {styles.input}
        onSubmitEditing={this._handleTextChange}
      />
    </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#666666',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  input: {
    fontSize: 20,
    borderWidth: 2,
    padding: 2,
    height: 40,
    width: 100,
    textAlign: 'center'
  },
});

export default WeatherApp;

this is my forecast.js that is suppose to render the forecast after the state is set.
import React, { Component } from "react";
import { StyleSheet, Text, View } from "react-native";

// component renders forecast based on zip code
class Forecast extends Component {
    render(){
        return(
            <View style = {styles.container}>
                <Text style = {styles.bigText}>
                    {this.props.main}
                </Text>
                <Text style = {styles.mainText}>
                    Current condition:
                    {this.props.description}
                </Text>
                <Text style = {styles.bigText}>
                    {this.props.temp}
                </Text>
            </View>
        );
    }
};

const styles = StyleSheet.create({
    container: { height: 130 },
    bigText: {
        flex: 2,
        fontSize: 20,
        textAlign: "center",
        margin: 10,
        color: "#FFFFFF"
    },
    mainText: {
        flex: 1,
        fontSize: 16,
        textAlign: "center",
        color: "#FFFFFF"
    }
});

export default Forecast;

in the react-devtools I do not even see the component render or show. Is this the result of styling from not using flexbox properly?

A: You declare content to be a Forecast component, but never actually reference it in your render().


text:
Q: Dynamic number of epochs with a tensorflow keras model I want to have a neural net that trains until a certain level of accuracy has been reached.  Is there a built in function to use instead of running each epoch individually until the accuracy has been reached?
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer=tf.train.AdamOptimizer(), loss='sparse_categorical_crossentropy', metrics=['accuracy'])

epochs = 0
train_acc = 0
while 1-train_acc > .01:
    model.fit(train_images, train_labels,  initial_epoch=epochs, epochs=epochs+1,verbose=0)
    epochs += 1
    train_loss, train_acc = model.evaluate(train_images,train_labels)

A: No, there isn't any built in function to do this. However, you can easily define a custom callback that stops training once the training accuracy reaches a certain threshold:
import keras

class AccuracyStopping(keras.callbacks.Callback):
    def __init__(self, acc_threshold):
        super(AccuracyStopping, self).__init__()
        self._acc_threshold = acc_threshold

    def on_epoch_end(self, batch, logs={}):
        train_acc = logs.get('acc')
        self.model.stop_training = 1 - train_acc <= self._acc_threshold

Here's a simple example showing how to use it:
import numpy as np
from keras.layers import Dense
from keras.models import Sequential

x = np.random.normal(size=(100,))
y = x > 0

model = Sequential()
model.add(Dense(1, input_dim=1, activation='sigmoid'))
model.compile('sgd', 'binary_crossentropy', metrics=['accuracy'])

acc_callback = AccuracyStopping(0.05)
model.fit(x, y, batch_size=8, epochs=1000, callbacks=[acc_callback])


text:
Q: Subversion repository grows not as much as expected Today I wanted to show a colleague that using windows copy and paste is not a good idea. I have done the following steps:

*

*Created a local repository.

*Checked out that empty repository.

*Added some files to the checkout location and commited them.

*Looked at the size of the repository (~ 9 MB).

*I then copied one Powerpoint file (~ 2 MB) with windows copy and paste, renamed it, and commited it to Subversion. Subversion did not know the file (as expected), so I had to manually add it to Subversion first.

*After the commit, I expected the repository to grow significantly (> 1 MB), because I have added a new file without history. The result was, that the growth of the repo was only 1 KB.

My questions here are:

*

*Is that the correct behavior now for Subversion 1.7?

*When did that change? In the past (at least for Subversion 1.5), when you added an exact copy (with windows copy and paste), it was added as a new file to the repository.

A: After reading parts of the SVN Book again, I found (I think) the answer myself. Here is the relevant part of "How Subversion saves disk space"

Repositories created with Subversion 1.6 or later further enjoy the
  disk space savings afforded by representation sharing, a feature which
  allows multiple files or file revisions with identical file content to
  refer to a single shared instance of that data rather than each having
  their own distinct copy thereof.

I will do some research about the creation with Subversion 1.6 or later, because that would mean that it does not work for repositories migrated from Subversion 1.5.


text:
Q: deleting directory with large amount of files with rsync -a delete I have a directory called crmlogs, how do I use rsync -a --delete to delete it?
mkdir emptydir
rsync -a --delete ./emptydir ./crmlogs

A: according to linuxnote.net's webarchive is rsync -aP –delete empty/ ./dir the fastest way to delete large directories, about three times faster as with rm -rfv ./dir or with find b/ -type f -delete
since it can take a while, a verbose output with -P is convenient or you gaze at an empty prompt line for ever...
and in order to avoid endless scrolling, I redirected the STDOUT to awk to display the output on a single line (with a line counter) like this:
rsync -aP --delete ./emptyDir/ ./dir/ | awk ' { printf ( "\r #%4d: %-200s", NR, $0 ) } '

for skipping the Permission denied lines, use sudo:
sudo rsync -aP --delete ./emptyDir/ ./dir/ | awk'{printf("\r #%4d: %-200s",NR,$0)}'

explanation: awk because printf alone doesn't catch STDOUT, \r to set the cursor at the begin of the output line, NR for a line# counter and %4d right-pads the line# and %-200s for an output string of 200 chars right padded that overwrites the previous line (200 if terminal window has at least this width)

A: The --delete switch deletes files from the destination that do not exist in the source. If you want to delete crmlogs, you need to be copying from a source that does not contain that directory. Your example shows you using rsync between two directories under the root directory. It is easier to see in this example under /tmp:
/tmp $ cd tmp
/tmp $ mkdir foo
/tmp $ mkdir bar
/tmp $ mkdir bar/crmlogs

/tmp $ rsync -a --delete foo/ bar/

/tmp $ ls -l bar
total 0
drwxr-xr-x  2 mint mint  40 Jan 10 23:19 ./
drwxrwxrwt 10 root root 220 Jan 10 23:19 ../

Note that rsync -a --delete foo bar or rsync -a --delete ./foo ./bar just puts a copy of foo under bar.
Judging by your follow-up comment, I'm not sure whether you really want to delete the crmlogs directory at all, or just flush out certain log files that may no longer exist in the source. If so, the --delete switch should be useful to you once those files have been removed from the source folder.


text:
Q: Pytorch Training; "Runtime Error:PyTorch and torchvision versions are incompatible ..." SOLUTION at the bottom!
I want to do Object Detection with this tutorial:
https://towardsdatascience.com/building-your-own-object-detector-pytorch-vs-tensorflow-and-how-to-even-get-started-1d314691d4ae
Although I have compatible versions of Pytorch, Torchvision and Cuda:
conda list torch gives me:

I get the following RunTime Error at the bottom:

RuntimeError: Couldn't load custom C++ ops. This can happen if your
PyTorch and torchvision versions are incompatible, or if you had
errors while compiling torchvision from source. For further
information on the compatible versions, check
https://github.com/pytorch/vision#installation for the compatibility
matrix. Please check your PyTorch version with torch__version__ and
your torchvision version with torchvision__version__ and verify if
they are compatible, and if not please reinstall torchvision so that
it matches your PyTorch install.

when running:
num_epochs = 10
for epoch in range(num_epochs):

    train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)#.to_fp16()

    lr_scheduler.step()

    evaluate(model, data_loader_test, device=device)

Is it really an error resulting from incompatibility of pytorch and torchvision?
Thank you very much.
SOLUTION:
I imported torchvision from the wrong directory. I found out using following:
import torchvision
print(torchvision.__path__)


text:
Q: No injector factory bound for Class<> I saw the same question in stack but they try to fix the error with the @ContributesAndroidInjector but in Dagger documentation says use @ContributesAndroidInjector is only optional, so here are my classes:
My MainActivityComponent:
@Subcomponent(modules = [
    MainBuilder::class
])
@ActivityScope
interface MainComponent: AndroidInjector<MainActivity>{

    @Subcomponent.Factory
    interface Factory: AndroidInjector.Factory<MainActivity>
}

My AplicationBinder:
@Module(subcomponents = [
    MainComponent::class
])
abstract class AppBuilder {

    @Binds
    @IntoMap
    @ClassKey(MainActivity::class)
    abstract fun mainActivityFactoryBind(factory: MainComponent.Factory): AndroidInjector.Factory<out Activity>

}

And my BaseActivity who extends my MainActivity:
abstract class BaseActivity: HasSupportFragmentInjector, AppCompatActivity() {

    @Inject
    lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
    }

    override fun supportFragmentInjector(): AndroidInjector<Fragment> {
        return dispatchingAndroidInjector
    }
}

How i can solve this issue?

A: Actually the dagger documentation says:

Pro-tip: If your subcomponent and its factory have no other methods or
  supertypes other than the ones mentioned in step #2, you can use
  @ContributesAndroidInjector to generate them for you. Instead of steps
  2 and 3, add an abstract module method that returns your activity,
  annotate it with @ContributesAndroidInjector, and specify the modules
  you want to install into the subcomponent. If the subcomponent needs
  scopes, apply the scope annotations to the method as well.

So basically the @ContributesAndroidInjector will generate that subcomponent thing you are doing manually. Since your case matches the Daggers documentation on this step, you can freely use @ContributesAndroidInjector.
Example:
@Singleton
@Component(
    modules = [AndroidInjectionModule::class, ActivityModule::class, BroadCastReceiversModule::class,...]
)
interface AppComponent {
    fun inject(pocketTreasureApplication: MyApplication)

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance application: Application): AppComponent
    }
}

The AndroidInjectionModule is free from Dagger. In that case it tells Dagger: Hey we have Android components to deal with and than Dagger knows how to generate them.
Than, you should use your modules, likeActivityModule to generate your classes that extend Activities, Fragments, Services, BroadCastReceivers etc.
So the ActivityModule hold the@ContributesAndroidInjector`:
    @Singleton
    @ContributesAndroidInjector(modules = [FragmentModule::class])
    abstract fun contributeMainactivity(): MainActivity

And the now Dagger knows that you may magically inject dependencies on MainActivity.
Same works for the FragmentModule inside it.
And than in your MainActivity you can do:
AndroidInjection.inject(this) and inject your dependencies.
That's all. You may check more into my personal article for Dagger-Android here.


text:
Q: Dumping the contents of a multi-dimension array into a new JSON variable I have a multi-dimension array that looks like this:
products = '[["A","Apple","20","apple.html"],["B","Banana","13","banana.html"],["C","Cereal","45","cereal.html"],["D","Dishes","320","dishes.html"]]';

I'm trying to turn this into a JSON object (at least I think that's what the format is), but only indexes 1 and 3... so products[0][1],products[0][3]. This what my results need to look like.
pList = [{value: 'Apple', data: 'apple.html'},{value: 'Banana', data: 'banana.html'}];

How do I go about getting this done?

A: *

*Parse the string to an array by JSON.parse.

*Use Array.prototype.map() to get the values from the array.

var products = '[["A","Apple","20","apple.html"],["B","Banana","13","banana.html"],["C","Cereal","45","cereal.html"],["D","Dishes","320","dishes.html"]]';

products = JSON.parse(products);

var pList = products.map(function(item) {
  return {
    value: item[1],
    data: item[3]
  };
});

console.log(pList);


text:
Q: como hacer un incremento al valor de una imagen en la url en javascript Hola tengo el siguiente código, el caso es que no me incrementa i al recorrerlo con img y añadiendolo a p1, como podría hacerlo correctamente para que vaya sumando uno en cada iteración y que vaya mostrando dicha imagen correspondiente ? gracias de antemano.

var div1 = document.createElement("div");
div1.setAttribute("id", "div1");
var div2 = document.createElement("div");
div2.setAttribute("id", "div2");
var div3 = document.createElement("div");
div3.setAttribute("id", "resultado");

document.body.appendChild(div1);
document.body.appendChild(div2);
document.body.appendChild(div3);

    const xhttp = new XMLHttpRequest();

    let data = [];

    let url1 = 'https://reqres.in/api/users';

    xhttp.open('GET',url1,true);
    xhttp.send();

    xhttp.onreadystatechange = function () {
        if(this.readyState == 4 && this.status == 200){
            let datos = JSON.parse(this.responseText);

            // aquí solo agregué ['data']
            console.log(datos['data']);

            let resultado = document.querySelector('#resultado');
            resultado.innerHTML = '';

            //len variable donde guardo tamaño del array datos['data']
            len = datos['data'].length;
            //cambié a un for tradicional
            for(let i = 0 ; i < len ; i++){
              //igualo la variable item a la correspondiente iteración
              let item = datos['data'][i];
              [item.first_name,item.last_name];

                var div = document.createElement('div');
                var p0 = document.createElement('p');
                var p1 = document.createElement('p');

                p1.setAttribute("id","fotos");

                var hr = document.createElement('hr');
                p0.innerHTML = item.first_name+" "+item.last_name;

                var img = document.createElement("img");
                img.setAttribute("src", item.avatar)
                document.getElementById("fotos");

                p1.appendChild(img);

                div.appendChild(hr);
                div.appendChild(p0)
                div.appendChild(p1);

                resultado.appendChild(div);
            }

        }
    }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ejercicio 3</title>
</head>
<body>
    <script src="api.js"></script>
</body>
</html>

A: Creo que el problema está en esta parte
var img = document.createElement("img");
img.setAttribute("src", "https://reqres.in/img/faces/1-image.jpg")

Creas el elemento y le asignas el atributo de manera hardcodeada
//prueba con esto
img.setAttribute("src", item.avatar)


text:
Q: Showing that sequence converges in distribution Consider the following sequence of random variable: $X_{1}$,$X_{2}$,$X_{3}$,$X_{4}$,$X_{5}$, ... i.i.d with $E(X_{i}=\mu)$ and n even.
Define: $P_{n}=\frac{2}{n}\sum\limits_{i=1}X_{2i}$ and $I_{n}=\frac{2}{n}\sum\limits_{i=1}X_{2i-1}$ the mean of the even and odd terms on the sample.
Suppose we know that: $\sqrt{n} (\overline{X_{n}}-\mu) \sim F$.
Show that $\sqrt{n} (P_{n}-\mu) \sim F$ and $\sqrt{n} (I_{n}-\mu) \sim F$
Any help?


text:
Q: how to get the URL up to a certain position this is the URL im
http://127.0.0.1/vikum/symfony/web/index.php/messenger/getConversation

using i need to get the URL up to
http://127.0.0.1/vikum/symfony/web/index.php/messenger/

how to do this in javascript
remember that the number of / may change what i need is to the point before last /

A: You can use lastIndexOf() to get the position of the last forward slash and then use substring() to get the url substring up to that point.
var url = "http://127.0.0.1/vikum/symfony/web/index.php/messenger/getConversation";
var indexOfLastFwdSlash = url.lastIndexOf("/");
var shortUrl;
if (indexOfLastFwdSlash === -1) { // no forward slash is found
  // Invalid URL
} else {
  shortUrl = url.substring(0, indexOfLastFwdSlash + 1); // +1 to include the last '/'
}

Sample run:

var url = ' http://127.0.0.1/vikum/symfony/web/index.php/messenger/getConversation';
var indexOfLastFwdSlash = url.lastIndexOf("/");
var shortUrl;
if (indexOfLastFwdSlash == -1) {
  // Invalid URL
} else {
  shortUrl = url.substring(0, indexOfLastFwdSlash + 1); // +1 to include the last '/'
}
alert(shortUrl); // alerts 'http://127.0.0.1/vikum/symfony/web/index.php/messenger/'

A: You can use:
url.substring(0,url.lastIndexOf('/') + 1);


text:
Q: Converting XML file to Nib file? I want to know about conversion  from XML file to Nib file in objective-c,My requirement is commonly Xib file after compilation it will converted into NIB file (binary Data Format) now i want to give an external Xml file to My Project and I want to convert this file as a Nib file. Is this possible?Give me suggestions(it means that replacement of Xib file With XML file).

A: Here I listed the details of plain iPad xib configuration, It is in the form of plist.
<?xml version="1.0" encoding="UTF-8"?>
<archive type="com.apple.InterfaceBuilder3.CocoaTouch.iPad.XIB" version="8.00">
    <data>
        <int key="IBDocument.SystemTarget">1536</int>
        <string key="IBDocument.SystemVersion">12A206j</string>
        <string key="IBDocument.InterfaceBuilderVersion">2519</string>
        <string key="IBDocument.AppKitVersion">1172.1</string>
        <string key="IBDocument.HIToolboxVersion">613.00</string>
        <object class="NSMutableDictionary" key="IBDocument.PluginVersions">
            <string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
            <string key="NS.object.0">1856</string>
        </object>
        <array key="IBDocument.IntegratedClassDependencies">
            <string>IBProxyObject</string>
            <string>IBUIView</string>
        </array>
        <array key="IBDocument.PluginDependencies">
            <string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
        </array>
        <object class="NSMutableDictionary" key="IBDocument.Metadata">
            <string key="NS.key.0">PluginDependencyRecalculationVersion</string>
            <integer value="1" key="NS.object.0"/>
        </object>
        <array class="NSMutableArray" key="IBDocument.RootObjects" id="1000">
            <object class="IBProxyObject" id="841351856">
                <string key="IBProxiedObjectIdentifier">IBFilesOwner</string>
                <string key="targetRuntimeIdentifier">IBIPadFramework</string>
            </object>
            <object class="IBProxyObject" id="606714003">
                <string key="IBProxiedObjectIdentifier">IBFirstResponder</string>
                <string key="targetRuntimeIdentifier">IBIPadFramework</string>
            </object>
            <object class="IBUIView" id="766721923">
                <reference key="NSNextResponder"/>
                <int key="NSvFlags">274</int>
                <string key="NSFrame">{{0, 20}, {768, 1004}}</string>
                <reference key="NSSuperview"/>
                <reference key="NSWindow"/>
                <object class="NSColor" key="IBUIBackgroundColor">
                    <int key="NSColorSpace">3</int>
                    <bytes key="NSWhite">MQA</bytes>
                    <object class="NSColorSpace" key="NSCustomColorSpace">
                        <int key="NSID">2</int>
                    </object>
                </object>
                <object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics">
                    <int key="IBUIStatusBarStyle">2</int>
                </object>
                <string key="targetRuntimeIdentifier">IBIPadFramework</string>
            </object>
        </array>
        <object class="IBObjectContainer" key="IBDocument.Objects">
            <array class="NSMutableArray" key="connectionRecords">
                <object class="IBConnectionRecord">
                    <object class="IBCocoaTouchOutletConnection" key="connection">
                        <string key="label">view</string>
                        <reference key="source" ref="841351856"/>
                        <reference key="destination" ref="766721923"/>
                    </object>
                    <int key="connectionID">3</int>
                </object>
            </array>
            <object class="IBMutableOrderedSet" key="objectRecords">
                <array key="orderedObjects">
                    <object class="IBObjectRecord">
                        <int key="objectID">0</int>
                        <array key="object" id="0"/>
                        <reference key="children" ref="1000"/>
                        <nil key="parent"/>
                    </object>
                    <object class="IBObjectRecord">
                        <int key="objectID">-1</int>
                        <reference key="object" ref="841351856"/>
                        <reference key="parent" ref="0"/>
                        <string key="objectName">File's Owner</string>
                    </object>
                    <object class="IBObjectRecord">
                        <int key="objectID">-2</int>
                        <reference key="object" ref="606714003"/>
                        <reference key="parent" ref="0"/>
                    </object>
                    <object class="IBObjectRecord">
                        <int key="objectID">2</int>
                        <reference key="object" ref="766721923"/>
                        <reference key="parent" ref="0"/>
                    </object>
                </array>
            </object>
            <dictionary class="NSMutableDictionary" key="flattenedProperties">
                <string key="-1.CustomClassName">ViewController</string>
                <string key="-1.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
                <string key="-2.CustomClassName">UIResponder</string>
                <string key="-2.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
                <string key="2.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
            </dictionary>
            <dictionary class="NSMutableDictionary" key="unlocalizedProperties"/>
            <nil key="activeLocalization"/>
            <dictionary class="NSMutableDictionary" key="localizations"/>
            <nil key="sourceID"/>
            <int key="maxID">3</int>
        </object>
        <object class="IBClassDescriber" key="IBDocument.Classes">
            <array class="NSMutableArray" key="referencedPartialClassDescriptions">
                <object class="IBPartialClassDescription">
                    <string key="className">ViewController</string>
                    <string key="superclassName">UIViewController</string>
                    <object class="IBClassDescriptionSource" key="sourceIdentifier">
                        <string key="majorKey">IBProjectSource</string>
                        <string key="minorKey">./Classes/ViewController.h</string>
                    </object>
                </object>
            </array>
        </object>
        <int key="IBDocument.localizationMode">0</int>
        <string key="IBDocument.TargetRuntimeIdentifier">IBIPadFramework</string>
        <bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool>
        <int key="IBDocument.defaultPropertyAccessControl">3</int>
        <bool key="IBDocument.UseAutolayout">YES</bool>
        <string key="IBCocoaTouchPluginVersion">1856</string>
    </data>
</archive>

But there is no document found about the elements in plist.
One Solution I found is check by creating a similar XIB file and use its plist.
And try this, write this plist data with extension as .xib and load that file.
May this link help u,
here
thanks,
Naveen Shan


text:
Q: How to create an index in elasticsearch such that with every day upload of data it creates a new index alias with date and allow me to delete them PUT myindex-000001
 {
  "aliases": {
  "myindex-alias":{
  "is_write_index": true
   }
 }
}

 PUT _ilm/policy/my_policy
       {
         "policy": {
         "phases": {
         "hot": {
         "actions": {
          "rollover": {
           "max_size": "25GB"
      }
    }
  },
  "delete": {
    "min_age": "180d",
    "actions": {
      "delete": {}
    }
   }
  }
 }
}

PUT _template/my_template
    {
      "index_patterns": ["myindex-*"],
      "settings": {
       "number_of_shards": 1,
       "number_of_replicas": 1,
        "index.lifecycle.name": "my_policy",
        "index.lifecycle.rollover_alias": "myindex-alias"
      }
    }

   POST myindex-000001
    {
     "settings": {
      "number_of_shards": 1,
        "number_of_replicas": 1,
           "index.lifecycle.name": "my_policy"
            }
          }

I tried to load the data into the elasticsearch index myindex-alias from java.
I need to have separate index alias with every new upload date , Ex -
         myindex-000001
         myindex-000002
         myindex-000003 and so on..

All linked to one policy so that I can delete any alias if I want to.

A: He, the policy es very similar, just add "max_age":"1d", to your payload. See more here