text:
Q: c# Merged cells as header address epplus How do I set HeaderAddress to two cells of a clustered bar chart in EPPlus? I have the below data from my database output, where first column is as you can see merged cells.

I am looking for the following layout of the data
Please take note that the images are from a replica of the data, but generated inside Excel.
What I've tried so far is basically
ExcelChartSerie s = chart.Series.Add(axis.Address, xAxis.Address);
s.HeaderAddress = new ExcelAddress(startRow + r, GetColumnNumberByName(startColumn), startRow + 1, GetColumnNumberByName(startColumn) + 1);

where I more or less select the current row and two columns. This gives me "Address must be a row, column or single cell", but in order to get this to work, I must select multiple cells, no?

A: Epplus does not have the ability to set it.  it is not so difficult but it requires XML manipulation.  Kind of ugly but it gets the job done.  Not knowing your code I made up a quick unit test that demos.  It has to match to the right chart type so if it is not BarClustered let me know:
[TestMethod]
public void Chart_Meged_Header_Test()
{
    //Throw in some data
    var datatable = new DataTable("tblData");
    datatable.Columns.AddRange(new[]
    {
        new DataColumn("Col1", typeof (string)),
        new DataColumn("Col2", typeof (int))
    });

    for (var i = 0; i < 10; i++)
    {
        var row = datatable.NewRow();
        row[0] = $"item {(i%2 == 0 ? "A" : "B")}";
        row[1] = i * 10;
        datatable.Rows.Add(row);
    }

    //Create a test file
    var fileInfo = new FileInfo(@"c:\temp\Chart_Meged_Header_Test.xlsx");
    if (fileInfo.Exists)
        fileInfo.Delete();

    using (var pck = new ExcelPackage(fileInfo))
    {
        var workbook = pck.Workbook;
        var worksheet = workbook.Worksheets.Add("Sheet1");
        worksheet.Cells["B1"].LoadFromDataTable(datatable, true);
        worksheet.Column(4).Style.Numberformat.Format = "m/d/yyyy";

        var chart = worksheet.Drawings.AddChart("chart test", eChartType.BarClustered);
        var serie = chart.Series.Add(worksheet.Cells["C2:C11"], worksheet.Cells["B2:B11"]);
        chart.SetPosition(0, 0, 3, 0);
        chart.SetSize(120);

        //Add merged headers
        worksheet.Cells["A2"].Value = "Group 1";
        worksheet.Cells["A2:A6"].Merge = true;

        worksheet.Cells["A7"].Value = "Group 2";
        worksheet.Cells["A7:A11"].Merge = true;

        //Get reference to the worksheet xml for proper namespace
        var chartXml = chart.ChartXml;
        var nsm = new XmlNamespaceManager(chartXml.NameTable);

        var nsuri = chartXml.DocumentElement.NamespaceURI;
        nsm.AddNamespace("c", nsuri);

        //Get the Series ref and its cat
        var serNode = chartXml.SelectSingleNode("c:chartSpace/c:chart/c:plotArea/c:barChart/c:ser", nsm);
        var catNode = serNode.SelectSingleNode("c:cat", nsm);

        //Get Y axis reference to replace with multi level node
        var numRefNode = catNode.SelectSingleNode("c:numRef", nsm);
        var multiLvlStrRefNode = chartXml.CreateNode(XmlNodeType.Element, "c:multiLvlStrRef", nsuri);

        //Set the proper cell reference and replace the node
        var fNode = chartXml.CreateElement("c:f", nsuri);
        fNode.InnerXml = numRefNode.SelectSingleNode("c:f", nsm).InnerXml;
        fNode.InnerXml = fNode.InnerXml.Replace("$B$2", "$A$2");
        multiLvlStrRefNode.AppendChild(fNode);
        catNode.ReplaceChild(multiLvlStrRefNode, numRefNode);

        //Set the multi level flag
        var noMultiLvlLblNode = chartXml.CreateElement("c:noMultiLvlLbl", nsuri);
        var att = chartXml.CreateAttribute("val");
        att.Value = "0";
        noMultiLvlLblNode.Attributes.Append(att);

        var catAxNode = chartXml.SelectSingleNode("c:chartSpace/c:chart/c:plotArea/c:catAx", nsm);
        catAxNode.AppendChild(noMultiLvlLblNode);

        pck.Save();
    }
}

Gives this as the output:


text:
Q: Using Jasypt to decrypt data encrypted with 3des I am trying to decrypt some data using Jasypt. The data was not encrypted using Jasypt but using 3Des(TripleDes). To provide more info on the encrypted data, the algorithm used is DESede, encoding is UTF-8, transformation is DESede/CBC/PKCS5Padding and this is Base64 encoded.
Is it possible to decrypt this data using Jasypt?
I have checked a lot of Jasypt related topics and cannot find any clues. I get exceptions varying from org.jasypt.exceptions.EncryptionOperationNotPossibleException when I set algorithm to PBEWithMD5AndDES, to org.jasypt.exceptions.EncryptionInitializationException: java.security.spec.InvalidKeySpecException: Inappropriate key specification when I set the algorith to DESede.
Please point to the right direction...

A: I think you should install jce.
This Link may be help you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Direct3D: What does the stream number do in device->SetStreamSource? Where else is the stream number used other than in these two places: GetStreamSource and SetStreamSource?

A: Using multiple streams allows you to combine together vertex component data from different sources. This can be useful when you have different rendering methods, each of which requires different sets of vertex components. Instead of always sending the entire set of data, you can separate it into streams and only use the ones you need. See this chapter from GPU Gems 2 for an example and sample code. It can also be useful for effects such as morphing.
When calling CreateVertexDeclaration, you specify the stream number in the D3DVERTEXELEMENT9 elements to determine which stream each vertex component comes from.


text:
Q: Segmentation fault upon calling delete gdb backtrace:
#0  0x0040cea9 in free () from /lib/tls/i686/cmov/libc.so.6
#1  0x0033c741 in operator delete(void*) () from /usr/lib/libstdc++.so.6
#2  0x080654b6 in mesh::calculateMeanNormalsPerVertex (this=0x807d684)
    at /home/brent/Desktop/protCAD/src/math/mesh.cc:230
#3  0x0805638f in buildCubes (argc=4, argv=0xbffff3e4)
    at /home/brent/Desktop/protCAD/src/driver/executeCubes.cc:163
#4  main (argc=4, argv=0xbffff3e4)
    at /home/brent/Desktop/protCAD/src/driver/executeCubes.cc:297

Declaration and delete call in mesh.cc:
vector<vector<int> > faceIndicesPerVertex (vertexArray.size());
...
delete[] &faceIndicesPerVertex;    //line 230

I'm sure I have this wrong, but I've tried a few different ways of calling delete there, but none seem to compile except the above. What's the problem?

A: You don't need to delete any stack-allocated object, stack-allocated vector object included - it will be destroyed and its memory will be reclaimed when the object goes out of scope. Trying to delete a stack-allocated object leads to undefined behavior (crash in your case).

A: First of all, faceIndicesPerVertex is not an array, so you cant call delete[].
And second, faceIndicesPerVertex is a local variable. This means it's on the stack. This means you can't use delete on it.
Only use delete on objects you allocate in the heap with new.

A: You don't have to call delete[]. It's automatically allocated variable/container, it will be automatically destroyed/freed memory.
Call delete when you call new and vise versa. The same for new[] and delete[].

A: faceIndicesPerVertex is not a pointer, it was allocated on stack. You can't delete it, and you  don't have to.

A: faceIndicesPerVertex is not a pointer, so delete[] is not required.
faceIndicesPerVertex is a vector so delete[] will not even work.

A: As far as I know, delete is used only for deallocating memory from the heap. You cannot delete stack allocated memory using delete. As a general rule, delete memory only if you dynamically allocated it using new. I also had some problems with the usage of new/delete. If you follow the general rule of using new and delete in pairs, you should be fine.


text:
Q: How to migrate a recursive table? Let's say I have a table, category, which has 3 columns, id, parent_id and name.
I have several tables like this, and I want to consolidate them into one. At present, their IDs will clash (not unique across DBs) so I need to re-ID them. If I make id an auto_increment I can copy all the other columns over just fine, but then parent_id won't link up properly anymore. Is there some magical way I can get the parent_id to point to the correct new ID?
Looking for something like
INSERT INTO newtable (parent_id, name) SELECT ???, name FROM oldtable

A: How about

*

*Generate a new table with a column containing the name of the old table and old id (oldid, oldtablename) along with a new ID

*Add a new column 'newparentid'

*Update each row's newparentid to be (SELECT newid FROM newtable nt WHERE oldtablename = row.oldtablename  and nt.oldid = row.parent_id)

A: I imagine you could add an old_id column so that you'll still have the original id and you can run successive updates to the table to modify all the parent_ids to point to the new auto_inc ids. You would obviously have to kill any foreign keys requirements on the table first and reinstitute them after all the changes were made – Patrick


text:
Q: full text index + joins + linq : how to do this properly? SO really there are two parts of the question:
1) how to use CONTAINSTABLE() with bunch of inner joins?
Suppose there are two tables:
Item (ItemID, CategoryID, Name)
Category (CategoryID, ParentCategoryID, Name)

using "dumb" like search this looks like this:
create view [db].[vItem]
as
select i.*, c1.Name as SubCategory, c2.Name as Category, c3.Name as Department
from Item i
inner join category c1 on(c1.CategoryID=i.CategoryID)
inner join category c2 on(c1.ParentCategoryID=c2.CategoryID)
inner join category c3 on(c2.ParentCategoryID=c3.CategoryID)

then do:
select *
from vItem
where (Name like '%[word 1]%' or SubCategory like '%[word 1]%' or Category like '%[word 1]%' or Department like '%[word 1]%') [and ... word n]

I could drop the view and inner join 4 times on CONTAINSTABLE() but thats a) fugly b) not the same thing (each key table will need to have all the search terms in order to have any result at all)
2) How to use all of the above in query language.
Again, assuming I just use like approach - its very simple.
from i in db.VItem
where i.Name.Contains("word 1") ...

How to do this with full text search?

A: For part 1): Create your view as an indexed view
create unique clustered index vItem_ItemID
    on db.vItem(ItemID)

then create the fulltext index on the columns of that view rather than the base table.
create fulltext index on db.vItem
    (Name, SubCategory, Category, Department)
    key index vItem_ItemID

Once that's created, you can:
select v.*
    from containstable(db.vItem, *, '"word 1"') ct
        inner join db.vItem v
            on ct.[key] = v.ItemID

I'll have to leave part 2) for someone else as I have little linq experience.


text:
Q: How can I compile a program during the execution of a QT or VS2010 application? I am currently developing a small grading application (for a C++ course) that will compile students' .cpp files and compare the output to a master. I'm using QT Creator to develop the UI as well as the back-end component (including some SQLite integration), and I have struggled with finding a way to compile the files automatically and discretely.
I originally developed a small application in VS2010 that utilized the VS Command Line Compiler - it works, but only in debug mode (when the program is executed from within cmd.exe). When I moved to Release, the compile command ("cl") was not recognized. Here is a small code segment:
int main()
{
    system("vcvarsall.bat"); // To set up VS Command Prompt environment
    _putenv("INCLUDE=<my include paths>"); // Include paths for compilation
    _putenv("LIB=<my lib paths>"); // Include paths for linking
    system("cl /EHsc \"Student1.cpp"); // Compilation code
    return 0;
}

When executed in Release, both "cl" and "cl.exe" are not recognized as commands. I am executing a variant of this program as a .exe file from within the QT application, passing a file name to this function, so it needs to be in Release form. What can I do to utilize the Command Line Compiler from within this application?
Thanks!

A: I have no teaching background, but my first suggestion is to have your students provide a makefile. NMake is system for VC, so you could try that.
If you still would like to compile using your own code I would recommend SCons instead of a console application. SCons and Python are free and very easy to setup. Your example becomes:
Program(target='Student1App', source=['Student1.cpp'])

You can call scons from within a C++ application if you choose, and after the call, assuming no build errors, the executable will be available.


text:
Q: Angular2, How to set width in table each td in grid View I need to fix width in "table->thead->td" in grid view.But I am getting head
   elements from array. I don't know how to set each tr when i using from array.
This is my Table column. I need to set width each tr. Anyone Please Help
   me????
 private channelsListColumnsForOwner: Array<any> = [
{ title: 'Name', name: 'name', sort:'asc'},
{ title: 'Owner', name: 'customer.name', sort:'asc'},
{ title: 'Description', name: 'description',sort:'asc'},
{ title: 'Controlled Channel', name: 'isControlled',sort:'asc'},
{ title: 'Active', name: 'isActive',sort:'asc' },
{ title: 'Subscribers', name: 'name',sort:'asc'},
{ title: 'Action' }
];

A: // Html code

        {{p.title}}
        {{p.name}}
        {{p.sort}}


text:
Q: sql connection string from AD account in web.config Infrastructure has created an active directory account for me that has read access to the SQL 2008 database I need to query.  The web application I've created does NOT use this account to run so I can't use Identity Impersonate="true" to access my datasource.
Is there a way in my connectionstrings node to just input the AD UN/PW combination (similar to how I would a SQL user account) to connect to my sql server?
please advise,
thanks

A: What you'd normally do is set the Application Pool identity to use the Windows (AD) service account and then use "trusted connection = yes" in your connection string in the web.config
This way you avoid the username/password in the web.config and you don't even need to knows details of the service account.

A: No, you can't use user name and password in the connection string.
You may create a WindowsIdentity and impersonate it before opening the connection, that will connect using the impersonated identity, but that is extremely discouraged.
Technically you can also run the application under a 'netonly' credential (ie. it has one identity for local resources, and another identity for network resources) using runas /netonly, but this is just as bad as hard coding the impersonated context.
Having the application run under one credential and then use a different credential to connect to the database is very bad. You must either run the application under the credential created for you to connect to the database, either grant the application's credential the privileges to connect to the database. Having two separate identities doesn't make any sense.


text:
Q: How can I use localized assets with angular localize I would like to use Angular localize (@angular/localize) in one of my Angular projects. Translating texts into different languages was straightforward with the help of the documentation. However, I also have a few localized images, and I can't figure out how to handle those.
If I target two languages, let's say English (en) and German (de), then I have one image per language, for example my-image_en.png and my-image_de.png. The first should show up on the English site, and the second on the German site.
When building my project, a separate folder is generated per language:
- /dist
    - /my-site
        - /en
            - /assets
                - my-image.png
            - index.html
            - ...
        - /de
            - /assets
                - my-image.png
            - index.html
            - ...

each of which has its own assets folder. It seems logical that there is a way to get my-image_en.png in dist/my-site/en/assets and my-image_de.png in dist/my-site/de/assets, but I can't find anything about that in the documentation, nor when I search for that on the internet.
Does anyone know if this can be achieved with Angular localize? Or is this something I need to configure in the angular.json file?


text:
Q: How can I convert this Ajax query to http client request in Angular 8? I have a request in ajax, like this:
  var data = {
    REQUEST: 'GetFeatureInfo',
    SERVICE: 'WMS',
    VERSION: '1.1.1',
    LAYERS: layerName,
    STYLES: '',
    FORMAT: 'image/png',
    INFO_FORMAT:'application/json',
    BGCOLOR: '0xFFFFFF',
    TRANSPARENT: 'TRUE',
    SRS: 'EPSG:' + mapSRID,
    BBOX: xmin + "," + ymin + "," + xmax + "," + ymax,
    WIDTH: map.width,
    HEIGHT: map.height,
    QUERY_LAYERS: layerName,
    X: screenPoint.x.toFixed(0),
    Y: screenPoint.y.toFixed(0)
  };
  $.ajax({
    type: 'GET',
    url: url,
    data: data,
    dataType: "application/json",
    complete: function (data) {
      callBack(data);
    }
  });
}

I want to convert to angular by using http client get method. How can I do that.
My solution but reponse: ok: false
  getInfo() {
    const params = {
      SERVICE: 'WMS',
      VERSION: '1.1.1',
      ...
    };

    this.http.get<any>('http://localhost:8080/geoserver/topp/wms', params).subscribe(data => {
      console.log(data);
    });
  }

The response:
status: 200
statusText: "OK"
url: "http://localhost:8080/geoserver/topp/wms?SERVICE=WMS&VERSION=1.1.1&EQUEST=GetFeatureInfo&FORMAT=image/png&TRANSPARENT=true&QUERY_LAYERS=topp:states&LAYERS=topp:states&exceptions=application/vnd.ogc.se_inimage&INFO_FORMAT=text/html&FEATURE_COUNT=50&X=50&Y=50&SRS=EPSG:4326&STYLES=&WIDTH=101&HEIGHT=101&BBOX=-113.8623046875,42.4072265625,-104.9853515625,51.2841796875"
ok: false
To more clear, I'm want to convert URL get request to http client get method request in Angular 8:
http://localhost:8080/geoserver/wms?service=wms&version=1.1.1&request=GetCapabilities

A: Inject HttpClient to in your service.
this.http.post(url , data).subscribe(response => {
 console.log(response);
}) //post request if you have to send data

this.http.get(url).subscribe(response => {
 console.log(response);
})//get if you want data

Ajax internally append data you send with the request to the url string. So in order to do that using angular, you need to use HttpParams
let params = new HttpParams().set("paramName",paramValue).set("paramName2", paramValue2); //Create new HttpParams

this.http.get(url, {headers: headers, params: params});

A: In your data you have EQUEST instead of REQUEST


text:
Q: Apache hive query syntax Error while compiling statement: FAILED: ParseException line 32:1 cannot recognize input near '(' 'select' 'count' in expression specification
select  bid,pid,cdate,chour ,'n' in_out,count(hc) as total
from
(
select a.mac,a.cdate,a.chour,
(select count(1) from bengo.n_hour_count_1 b
where a.mac=b.mac and a.cdate=b.cdate and a.chour=b.chour+1) as hc
from  bengo.n_hour_count_1 a
having hc=0
) g
GROUP BY cdate,chour;


text:
Q: AWS sdk version 2, create ec2 instance I might have missed it, but i cant figure out how to create ec2 instance in ruby via the version 2 of the aws sdk.. anyone?
cant find any solution in http://docs.aws.amazon.com/sdkforruby/api/Aws.html

A: Grab a client with
ec2 = Aws::EC2::Client.new(
  region: region_name,
  credentials: credentials
)

, then launch instances with ec2.run_instances.See documentation below.
http://docs.aws.amazon.com/sdkforruby/api/Aws/EC2/Client.html#run_instances-instance_method

A: There are sdk gems for rby. To install the sdk-2 gem you need to add
gem 'aws-sdk', '~> 2'`

In your Gemfile and install it with bundle install command. After that you can refer this docs for the rest: http://docs.aws.amazon.com/sdkforruby/api/index.html
And examples right there:
# resource constructors
ec2 = Aws::EC2::Resource.new(region:'us-west-2', credentials: credentials)

# client constructors
ec2 = Aws::EC2::Client.new(region:'us-west-2', credentials: credentials)

The configuration examples are there as well.


text:
Q: Is 'low speed' finally proving its merit? Technically, you should expect the term low speed, not slow speed (which is obviously illogical).
However, it seems the two phrases co-existed as long as one can look back: with low speed fighting a desperate battle to prove its merit.
It is only recently that English users seem to have seriously recognized the difference as this nGram shows.

How did this obvious error survive and even now continue to assert itself? Or is it that  from the language point of view, there is an argument that both the phrases are correct, grammatically, especially, semantically?

[Edit-1] Some backgrounder on slow and speed
slow /slō/
Adjective: Moving or operating, or designed to do so, only at a low speed.
Adverb: At a slow pace; slowly.
Verb: Reduce one's speed or the speed of a vehicle or process.
If slow = low speed
then slow speed  = ?

A: Low speed is licensed by the UP/DOWN metaphor cluster, which, like all metaphors,
allows us to symbolically project some feature or percept of the human body (in this case,
our built-in gravitational perception)  to other judgementally differential
binary concepts, like GOOD/BAD, FAST/SLOW, MALE/FEMALE, and the like. E.g:

*

*UP is MORE (DOWN is LESS):

*
*

*The stockmarket's moving up/crashing.

*UP is HAPPY (DOWN is SAD):

*
*

*He's depressed. feeling up/down

*UP is POWERFUL (DOWN is WEAK):

*
*

*upper/lower classes; superior/subordinate

*UP is ACTIVE (DOWN is PASSIVE - NB: Not grammatical Passive):

*
*

*The computer is up/down again. Rise to the occasion. up for some handball

*UP is BETTER (DOWN is WORSE):

*
*

*fall down on the midterm; rise/fall in performance; upwardly-mobile

*UP is ABSTRACT (DOWN is CONCRETE):

*
*

*head in the clouds; feet on the ground; higher mathematics; down-to-earth solution
As for the presenting question, viz. "Is 'low speed' finally proving its merit?"   ...
Sorry. Since The Academy isn't in session this year, I can't really answer that question as posed. The presuppositions required to make sense of it are fairly interesting, though.

A: You didn't ask:

Why did 'low speed' become dominant over 'slow speed' when it did?

I'm not one to let that stop me from answering the wrong question.  I think the answer is that "low speed" was dragged along in the wake of "high speed", so to speak.   Since the antonym of "high" is "low", it became the more obvious word to use, especially when used in contrast.  See this nGram.  It suggests a related question, which may shed light on the original:

Why is "slow speed" used, but "fast speed" not?

It might be as simple as ease of pronunciation - "fast speed" doesn't exactly roll off the tongue.

A: If you look up this definition of the word speed, you will see that the first meaning attributed to the word is the rate at which someone or something moves or is able to move. So, it is perfectly logical to talk about both slow and fast speed, as the word is neutral in this sense and can be modified with these two adjectives.
I wouldn't call it an error, therefore. Both uses of slow speed and low speed are grammatical.

A: Such constructions are exceedingly common in English. You might want to examine your assumption that this is an "obvious error" or "obviously illogical".

*

*Short stature

*Narrow width

*Short length

*Slow acceleration

*Shallow depth

*Low altitude
Some people consider "slow speed" an oxymoron - but as is the case with most oxymora, the meaning is crystal clear. In language it's successful communication of meaning that matters, not logical correctness. Are you claiming that you don't understand what is being said, that its meaning is not clear? Or are you saying that redundancy shouldn't be used in language? That's incorrect, languages use redundancy all over place. Or do you just not like the construction? That's certainly your prerogative, you can speak that way if you like, but it's not generally correct at least according to other speakers' evidence.

A: Simply put: low speed is the more correct one.
English is based on conventional uses. If the majority of English speakers use a certain phrase that is incorrect, over time people get used to it and is then incorporated into the English standard.
"Slow speed" is redundant because slow implies speed, whilst "speed" is the noun being modified.
The same repetitive redundant phrase goes to the famous "The reason is because..." (redundancy intended)

A: If we are talking about the rate at which something moves or travels, we can say "low/high speed".  On the other hand,  some senses of "speed"  may refer to "velocity", "rapidity, quickness", swiftness", "fastness", where the usage of adjective "slow" is needed. E.g:

Slow speed of light.

I think we can question languages as "sensible".  Otherwise,
you can not explain the sentence "The sun rises in the east and sets in the west."  which is completely illogical as well as  unreal.

A: One may say "a fast speeding car". And one can travel "faster than the speed of light". So, "fast" and "speed" do collocate. As has been discussed, speed simply indicates the rate of change resulting in a movement that may be relatively "fast" or "slow". Of course, one also says "a high speed chase". But here I'm inclined to surmise that "high" is used for effect, and not because the the noun "speed" requires it. In other words, the use of "high", "low", "fast" or "slow" is optional, depending on the intent of the author. One is therefore per se not "more correct" or "accurate" than the other. To paraphrase Einstein "it's all relative".
English it a tool of expression as much as it is a tool of communication. Thus, it must offer individuals latitude to articulate their thoughts in a manner they deem fitting. The only restriction is that these thoughts need to be comprehensible to others, if the purpose of communication is to be served.
This is why we have standards within which there is a rich vocabulary from which one can select. I'm advocating here that one simply respect that fact and conclude that slow speed can be no more correct than fast, high, or low speed.


text:
Q: How to calculate inverse in chainlink tasks? Hey I am trying to calculate inverse of a value that I got from an API call. I have my tasks like these.
Tasks
parse        [type="jsonparse" path="quotes,USDEUR" data="$(fetch)"]
inverse      [type="divide" input="1" divisor="$(parse)" precision="5"]
multiply     [type="multiply" input="$(inverse)" times=1000000000000000000]

But I am getting the response like this.
Response
parse jsonparse
1.022015
path: quotes,USDEUR
data: $(fetch)
inverse divide
"1"
input: 1
divisor: $(parse)
precision: 5
multiply multiply
"1000000000000000000"
input: $(inverse)
times: 1000000000000000000
What I need it to get inverse of the value getting from parse task. But when I do this I am just getting it as 1.


text:
Q: Facebook on Android exits immediately when sharing with it from my app When I share some URL (as text) from my app with Facebook, the Facebook new post activity appears and exits immediately and my app re-appears. The user has no chance to submit it, or even review and finish it.
This is (apparently) not a crash, there is no notification about Facebook app crashing. When shared with some other app (e.g. Gmail), it works fine.
Unfortunately this only happens on some devices. All devices where I tested it have the same version of the Facebook app. It's not related to Android version (tested on two 4.4 devices, one of them is OK and one is not).
This is what I'm doing in my app:
String textToShare = "http://lovelikeorhate.eu/question/LOVE/3";
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textToShare);
sendIntent.putExtra("com.facebook.platform.extra.APPLICATION_ID", getString(R.string.facebook_app_id));
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));

Any ideas what might be wrong? The URL is applinks enabled, could it be related?

A: The app needs to be in production mode on Facebook. This is the same problem:
ClassNotFoundException on opening facebook share icon in android


text:
Q: Is multitasking a feature of the microprocessor or operating system only? I am not sure if there is a certain hardware requirement on the CPU for multitasking? would it possible to do multitasking on 8086 chip?

A: Yes and no. There are several kinds of multitasking methods and each one requires a different degree of hardware support.
The 8086 chip is capable of multitasking but only a type of multitasking called cooperative multitasking (Early version of windows, ie, 3.0 used this). How it works is every program on the system must yield control back to the operating system every so often. The operating system in turn passes control onto the next program, which then must yield control back to the operating system after some time.
There are some obvious drawbacks, what if a program never yields control back to the operating system? Then the entire system hangs and there is no way to terminate that bad program.
The type of multitasking used today is called pre-emptive multitasking. It works by interrupting each program and passing control onto another one. Programs do not need to be aware of the multitasking at all, they can be written to assume that they are the only program running on the computer, so the actual multitasking element is transparent to them. This kind of multitasking needs hardware support in the form of what is called virtual memory. The operating system needs to be able to separate the addresses spaces of each program so that each program is not directly aware of each other. Then hardware interrupt timers are used to interrupt each program so that the operating system can move from one task to the next.
Different architectures have different methods of actually doing the task switching. It's possible to do it all entirely in software with just the support of virtual memory and hardware timers, however some architectures support constructs to simplify this process, such as x86 which has the Load Task Register. This isn't strictly necessary however to implement multitasking and most operating systems that I am aware of do their own task switching.
For more information on pre-emptive multitasking and how it works in the x86 architecture, I recommend this article: http://wiki.osdev.org/Multitasking_Systems
EDIT:
The MP/M-86 operating system used what can be considered a preemptive multitasking model on the 8086 by using a hardware timer to interrupt processes and move onto the next one, so the 8086 is capable of a form or preemption; however many of the same issues raised above are still a concern. For example, each process has access to other processes memory spaces. There is also nothing keeping a process from hijacking the system by disabling the hardware timer interrupt. In order to have a robust multitasking environment a large degree of hardware support is necessary.


text:
Q: MFC customise - add new toolbar? In an MFC app, when customising toolbars at runtime, is there an option for users to create their own new toolbars?
I have recently moved my app to the new MFC controls in VS2010.  I was previously using the BCG version of this functionality, which pre-dates VS2008.  (Microsoft bought the BCG stuff and wrapped it in to VS, as of VS2008).  Anyway, I noticed that the Microsoft MFC version does not seem to allow the functionality for users to add their own toolbars under the toolbar customisation.  Users can customise the icons on the toolbars, but the button to add their own new toolbars doesn't seem to be there.
Is there some way to enable this option in my code, so that users can create their own new toolbars?

A: It is also in the new MFC classes
When I create a new MFC program with the wizard in VS-2010 you can choose this feature on the page "User Interface Features". Select "Use a menu bar and toolbar. There are two further settings "User-defined toolbars and images" and "Personal menu behavior". You have to select the first.
Look into the created code...
HTH
PS: Also the new BCG classes are completely compatible with MFC 2010 and later.


text:
Q: inserting a foreign key in child table it showing null everytime I am inserting a foreign key in a child table using a @OnetoMany relationship between parent and medicine. One parent has many medicines and it shows me null.
I have done many searches for my problem and I have tried every possible solution, but it's not working.
Parent Class
@Entity
@Table(name = "patient_domain")
public class Patient implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)

@Column(name = "p_id")
private Integer p_id;

@Column(name = "doctor_name")
private String doctor_name;

@Column(name="name")
private String name;

@Column(name="hospital_clinic")
private String hospital_clinic;

@Column(name="date")
private Date date;

@OneToMany(mappedBy = "patient", cascade = CascadeType.ALL)
private List<Medicine> medicines;

Patient Bean class
package com.gamification.beans;

import com.gamification.entities.Medicine;

import java.util.Date;
import java.util.List;

public class PatientBean {

private Integer p_id;
private String name;
private String doctor_name;
private Date date;

private List<Medicine> medicines;

public List<Medicine> getMedicines() {
    return medicines;
}

public void setMedicines(List<Medicine> medicines) {
    this.medicines = medicines;
}

public Integer getP_id() {
    return p_id;
}

public void setP_id(Integer p_id) {
    this.p_id = p_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDoctor_name() {
    return doctor_name;
}

public void setDoctor_name(String doctor_name) {
    this.doctor_name = doctor_name;
}

public String getHospital_clinic() {
    return hospital_clinic;
}

public void setHospital_clinic(String hospital_clinic) {
    this.hospital_clinic = hospital_clinic;
}

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

private String hospital_clinic;

}

Medicine Class
@Entity
@Table(name = "medicine_kit")
public class Medicine implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "med_id")
private Integer med_id;

@Column(name="med_name")
private String med_name;
@Column(name="med_type")
private String med_type;
@Column(name="med_quantity")
private String med_quantity;

@JsonIgnore
@ManyToOne
@JoinColumn(name = "patient_domain_p_id", nullable = false,
referencedColumnName = "p_id")
private Patient patient;

MedicineBean
public class MedicineBean {

private Integer med_id;
private  String med_name;
private  String med_type;
private  String med_quantity;

private Integer patientid;

public Integer getPatientid() {
    return patientid;
}

public void setPatientid(Integer patientid) {
    this.patientid = patientid;
}

public Integer getMed_id() {
    return med_id;
}

public void setMed_id(Integer med_id) {
    this.med_id = med_id;
}

public String getMed_name() {
    return med_name;
}

public void setMed_name(String med_name) {
    this.med_name = med_name;
}

public String getMed_type() {
    return med_type;
}

public void setMed_type(String med_type) {
    this.med_type = med_type;
}

public String getMed_quantity() {
    return med_quantity;
}

public void setMed_quantity(String med_quantity) {
    this.med_quantity = med_quantity;
}
}

PatientController
@RequestMapping(method = {RequestMethod.POST})
public ResponseEntity<ApiResponse> createOrUpdateUser(@RequestBody PatientBean patientBean) throws Exception {

    ApiResponse status = new ApiResponse();
    status.setStatus(false);
    status.setMessage("please select record");
    try {
        if(patientBean != null) {

            Patient patient = new Patient();

            List<Medicine> listmedicine=new ArrayList<Medicine>();
            status.setStatus(true);
            if(patientBean.getP_id() != null) {
                patient.setP_id(patientBean.getP_id());
                status.setMessage("Successfully record updated");
            } else {
                status.setMessage("Successfully record created");
            }

            patient.setName(patientBean.getName());
            patient.setDoctor_name(patientBean.getDoctor_name());
            patient.setHospital_clinic(patientBean.getHospital_clinic());
            patient.setDate(CommonUtil.getCurrentTimestamp());

            if(patient.getMedicines().size()>0)
            {
                for (int i=0;i<patient.getMedicines().size();i++)
                {
                    Medicine medicine=new Medicine();
                    medicine.setMed_name(patientBean.getMedicines().get(i).getMed_name());
                    medicine.setMed_quantity(patientBean.getMedicines().get(i).getMed_quantity());
                    medicine.setMed_type(patientBean.getMedicines().get(i).getMed_type());
                    medicine.setPatient(patient);
                    listmedicine.add(medicine);

                }
            }
            patient.setMedicines(listmedicine);
            status.getResponseList().add(patient);
            patienServiceImp.createPatient(patient);
        }

        return new ResponseEntity<ApiResponse>(status, HttpStatus.OK);
    } catch (Exception e) {
        status.setStatus(false);
        status.setMessage("Something went wrong on server");
        MyPrint.println(e.getMessage());
        return new ResponseEntity<ApiResponse>(status, HttpStatus.OK);
    }
}

A: solved, I got the mistake that i didn't set the medicine in the patient,
"patient.setMedicines(patientBean.getMedicines());" just add this one in my code and my code is working properly.


text:
Q: Difference between getExternalFilesDir and getExternalStorageDirectory() I understand that ExternalFiles is to be used on API 8 and up and getExternalStorageDirectory is for 7 and down. However I am a little confused between the use. For example I wanted to check that a folder that exists and previously you would use something like:
File ChildFolder = new File(Environment.getExternalStorageDirectory() + "/ParentFolder/Child");

However every example I see says to use getExternalFilesDir (null), File.ext. Since I am above API 8 I want to use this method but how do I just check for a folder? I will check for a files existence at another point but for now just want to see if the folders exist??

A: First of all, we need to understand what is difference between Internal Storage, External Storage (aka primary external storage), and Secondary External Storage?
Internal Storage: is storage that is not accessible by the user, except via installed apps (or by rooting their device). Example: data/data/app_packageName
Primary External Storage: In built shared storage which is "accessible by the user by plugging in a USB cable and mounting it as a drive on a host computer". Example: When we say Nexus 5 32 GB.
Secondary External Storage: Removable storage. Example: SD Card.
getExternalFilesDir (String type)

It returns the path to files folder inside Android/data/data/your_package/ on primary external storage. Which is inbuilt storage.
Environment.getExternalStorageDirectory()

It will return the path of the secondary external storage directory

A: ! IMPORTANT UPDATE ! for whoever comes across this question.
As this is a somewhat old question just wanted to provide some additional information. Since KitKat even apps that have WRITE_EXTERNAL_STORAGE permission are only allowed to write to Android/data/data/your_package/ on external storage, a.k.a getExternalFilesDir()
If you will try to write to getExternalStorageDirectory() + "/somefolder/anotherfolder/" you will get a SecurityException on most devices

A: getExternalFilesDir()

It returns the path to files folder inside Android/data/data/your_package/ on your SD card. It is used to store any required files for your app (e.g. images downloaded from web or cache files). Once the app is uninstalled, any data stored in this folder is gone too.
getExternalStorageDirectory()

It returns the root path to your SD card (e.g mnt/sdcard/). If you save data on this path and uninstall the app, that data won't be lost.

A: !! IMPORTANT !!
Environment.getExternalStorageDirectory() is deprecated and Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT, should be used instead.

This method was deprecated in API level 29.
To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.

https://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()
Also beginning from Android.M developers need to ask for permissions at run time.
See more details in documentation here and this question
Environment.getExternalStorageDirectory() deprecated in API level 29 java


text:
Q: Inner join to create new column for view returns wrong values I have a table with countries and regions that I would like to join on another table containing countries and population. All of that should be part of a view. The expected result when I run the query isolated is this:
SELECT d.country, c.region, d.population
FROM data d
INNER JOIN country_region c ON c.country = d.country

Result:
Country    Region          Population
France     Europe          70
Germany    Europe          80
Japan      Asia            130
Brazil     South America   200

Now when I run the same table to create my view, the inner join goes wrong and returns Europe for all countries and I can't figure out why.
CREATE VIEW data_consolidated AS
    SELECT
        d.country,
        (SELECT region c
         FROM data d
        INNER JOIN country_region c ON c.country = d.country) AS region,
        d.population
    FROM
        data d

Result:
Country   Region   Population
France    Europe   70
Germany   Europe   80
Japan     Europe   130
Brazil    Europe   200

My source tables:
country_region
country   region
France    Europe
Germany   Germany
Japan     Asia
Brazil    South America

data
country   population
France    70
Germany   80
Japan     130
Brazil    200

A: Your sub query needs to be correlated with the outer reference
CREATE VIEW data_consolidated AS
    SELECT
        d.country,
        (SELECT region from country_region c where c.country = d.country) AS region,
        d.population
    FROM
        data d


text:
Q: Wait for Cmd process to end -java Process p= Runtime.getRuntime().exec("cmd.exe /c cd \""+path+"\" & start cmd.exe /k \"mvn clean install\" & wait");
int i = p.waitFor();
print(p);

A: Okay just solved it..
Process p= Runtime.getRuntime().exec("cmd.exe /c cd \""+path+"\" & start /wait cmd.exe /k \"mvn clean install\"");
worked


text:
Q: Maximum Likelihood estimation with a "dependent parameter"? Suppose we have a likelihood function
$$L(\theta | X) = f(X; \alpha, \beta, \gamma(\beta))$$
So that the third parameter, $\gamma$, depends on $\beta$ in such a way that they cannot be separated. For example, suppose
$$\gamma (\beta) = \int_0^1 g(s) e^{\beta s} ds$$
for some unknown function $g(s)$. Since we cannot reasonably estimate $g(s)$, we instead wish to replace the integral with a single parameter to estimate. Unfortunately, due to the integral's dependence on $\beta$, we cannot derive maximum likelihood estimates.
I have two questions:

*

*Is there any well known procedure for over coming a situation like this?

*What would happen if we just "ignore" $\gamma$'s dependence on $\beta$? So that we instead consider the function
$$f(X; \alpha, \beta, \gamma)$$
and derive maximum likelihood estimates from that? Would they still be consistent? Can anything "good" be said about this situation?

A: To deal with maximum likelihood estimation, you must formulate your problem in such a way that there is a clear range of allowable values for the unknown parameters.  In your problem you need to formulate an allowable range of values for the parameter $\gamma$ for each possible value of the dependent parameter $\beta$.  To do this you will need to consider what is the allowable range of functions $g$.
For example, suppose you have some independent function $g \in \mathcal{G}$ where the range of this function does not depend on the parameters in your problem.  You can then define $\mathcal{Y} (\beta) \equiv \{ \gamma(\beta) | g \in \mathcal{G} \}$ for each allowable value of $\beta$ and you have the partially-maximised likelihood:
$$\bar{L}(\alpha, \beta) \equiv \max_{g \in \mathcal{G}} L(\alpha, \beta, g) = \max_{\gamma \in \mathcal{Y}(\beta)} L(\alpha, \beta, \gamma).$$
This tells you that maximising the likelihood function over the set of allowable functions $g$ is the same as maximising it over the corresponding set of allowable parameters $\gamma$.  The latter requires you to specify the range of $\gamma$, and the partially-maximised likelihood then depends on $\beta$ through its direct appearance in the likelihood function, and also through its effect on the allowable range of $\gamma$.

In your problem, you have not been clear about the range of allowable functions $g$ (I am assuming this is some real function).  If you impose no constraint on this, you will have $\mathcal{Y} (\beta) = \mathbb{R}$ for all $\beta$, which gives $\bar{L}(\alpha, \beta) = \max_{\gamma \in \mathbb{R}} L(\alpha, \beta, \gamma)$.  In this case, there is no problem of parametric dependence and so this is an ordinary maximum-likelihood problem.

A: Part 1
Can you model $g(s)$ as a polynomial? If so, I believe you could turn $\gamma(\beta)$ into a closed form expression by analytically computing the integral. In general, if you can find some approximation of $g(s)$ that makes the integral analytically solvable, then you're back to ordinary maximum likelihood (without a $\gamma$ at all).
Let's say you don't know much about g(s). But you must know something! So put a Gaussian Process prior on it with mean function F(s). Use a tool like stan, sample the function during an MCMC draw and perform numerical integration within the loop. You can see me trying this here (see line 96). Now it's slow, but it is a way to estimate and incorporate uncertainty in $g(s)$.
If you have a complex nonlinear expression for $g(s)$ but don't want to go the bayesian route, you could incorporate something like the trapezoidal rule in your maximum likelihood routine, but it too will be slow!
Part 2
In order to even speak of dependence between parameters, you have to adopt a bayesian viewpoint, since the classical viewpoint has all parameters as fixed unknown quantities. If you take the classical interpretation, then I think you're okay just estimating $\gamma$ as a constant. In fact, why not use the estimates of $\beta$ and $\gamma$ to gain insight into $g(s)$?


text:
Q: .htaccess rewriterule to create subdomains I want to create subdomains, so that I can use the address test.mydomain.com.
After searching the web, and a lot of trial, I got this in my .htacces file:
<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} ^([^.]+)\.mydomain\.com(:80)?$
    RewriteCond %{DOCUMENT_ROOT}/subdomains/%1/$1 -f [OR]
    RewriteCond %{DOCUMENT_ROOT}/subdomains/%1/$1 -d
    RewriteRule (.*) /subdomains/%1/$1 [L]
</IfModule>

If I write http: //test.mydomain.com/folder/ in my browser everything is fine.
But if I write http: //test.mydomain.com/folder (without ending slash), it gets redirected to http: //test.mydomain.dk/subdomains/test/folder/, and this is the address shown in the browser (which I don't want)
My question is:
How do I prevent the redirect?I want to only see http: //test.mydomain.com/folder in the browser. Regardless of the ending slash.
My web files is like this:
.htaccess
index.php (page for mydomain.com)
\subdomains
    \test
        \hello
         index.php (page for test.mydomain.com/hello)

Thanks.
(sorry about the spaces in the url's. It won't let my post with links)

A: got it to work now:
<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine on

    # If requested URI does not end in "/"
    RewriteCond $1 !/$
    # add a trailing slash
    RewriteRule ^(.+)$ /$1/ [R=301,L]

    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} ^([^.]+)\.mydomain\.com(:80)?$
    RewriteCond %{DOCUMENT_ROOT}/subdomains/%1/%{REQUEST_URI} -d [OR]
    RewriteCond %{DOCUMENT_ROOT}/subdomains/%1/%{REQUEST_URI} -f
    RewriteRule (.*) /subdomains/%1/$1 [L]
</IfModule>


text:
Q: Trigger alarm when input values equals to current time I want to create multiple alarm clocks and trigger any of the alarm if at any time the value of that alarm (hour and minute) equals the current time (hour and minute). I generates the alarm from user inputs, where the user input the set time (hour and minute) that they want the alarm to trigger, and any time the user input matches the current time, the alarm should be triggered.
The problem here is that, the alarm doesn't ring. The set time will pass and the alarm will refuse to ring.
Here is my code.
CSS
#ring {display:none;}
li {list-style-type: none; border: solid gray 1px; padding:10px; margin: 3px;}

HTML

Ring!!!!!!!!!

<input type="text" placeholder="hour" id="hour">
<input type="text" placeholder="minute" id="minute">
<button onclick="addAlarm()">Set alarm</button>

JAVASCRIPT
function startTime(alarmHour, alarmMinute) {
  var today = new Date();
  var currentHour = today.getHours();
  var currentMinute = today.getMinutes();
  var currentSecond = today.getSeconds();
  document.getElementById('txt').innerHTML =
  currentHour + ":" + currentMinute + ":" + currentSecond;
  var t = setTimeout(startTime, 500);

  if(currentHour == alarmHour && currentMinute == alarmMinute) {
  document.getElementById("ring").style.display = "block"
  }

};

var list = document.getElementById("list");
var alHour = document.getElementById("hour");
var alMinute = document.getElementById("minute");

function newAlarm(hour, minute){
    startTime(hour, minute)
    theAlarm = `<li><span>${hour}:</span><span>${minute}</span></li>`;

    var position = "afterbegin";
    list.insertAdjacentHTML(position, theAlarm);

  }

  function addAlarm(){
   var hour = parseInt(alHour.value);
   var minute = parseInt(alMinute.value);
    if (hour, minute) {
      newAlarm(hour, minute);
      alHour.value ="";
      alMinute.value ="";
    }
  };

A: Um I dont get your question to much but here I fixed the code according to what you said

var alarmhour;
var alarmminute;

setInterval(function() {
  var today = new Date();
  var currentHour = today.getHours();
  var currentMinute = today.getMinutes();
  var currentSecond = today.getSeconds();
  document.getElementById('txt').innerHTML =
    currentHour + ":" + currentMinute + ":" + currentSecond;
  if (currentHour == alarmhour && currentMinute == alarmminute) {
    document.getElementById("ring").style.display = "block";
  }

}, 500)

var list = document.getElementById("list");
var alHour = document.getElementById("hour");
var alMinute = document.getElementById("minute");

function newAlarm(hour, minute) {
  alarmhour = hour;
  alarmminute = minute;
  theAlarm = `<li><span>${hour}:</span><span>${minute}</span></li>`;

  var position = "afterbegin";
  list.insertAdjacentHTML(position, theAlarm);

}

function addAlarm() {
  var hour = parseInt(alHour.value);
  var minute = parseInt(alMinute.value);
  if (hour, minute) {
    newAlarm(hour, minute);
    alHour.value = "";
    alMinute.value = "";
  }
};
#ring {
  display: none;
}

li {
  list-style-type: none;
  border: solid gray 1px;
  padding: 10px;
  margin: 3px;
}

Ring!!!!!!!!!

  <input type="text" placeholder="hour" id="hour">
  <input type="text" placeholder="minute" id="minute">
  <button onclick="addAlarm()">Set alarm</button>

Click the run snippet above to see the code running


text:
Q: Is this the correct way to consume an API with React Native, Expo, and Reeact Native Paper? I am new to React Native and I am trying to create an application with it.
The problem is when I try to display the data in the application.
I am trying to consume a REST API to be able to display the data but it is not showing me anything.
Besides this it does not show me what the error is so I am confused.
I think it's like I'm consuming the API but I can't find the error.
This would be my code:
import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useState, useContext  }  from 'react';
import { StyleSheet, Text,  View, FlatList, Image} from 'react-native';
const MORE_ICON = Platform.OS === 'ios' ? 'dots-horizontal' : 'dots-vertical';
import { Appbar } from 'react-native-paper';
import { Platform } from 'react-native';
import { Searchbar } from 'react-native-paper';
import { Avatar, Button, Card, Title, Paragraph } from 'react-native-paper';
import { render } from 'react-dom';
const API_ENDPOINT = 'https://localhost:5001/api/Medicines/';

export default function App ()  {
  const [searchQuery, setSearchQuery] = React.useState('');
  const onChangeSearch = query => setSearchQuery(query);

  const [data, setData] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch(API_ENDPOINT)
      .then(response => response.json())
      .then(results => {
        setData(results);
      })
      .catch(err => {
        setError(err);
      });
  }, []);

  return (

        <View >
        <Appbar.Header>
          <Appbar.Content title=" Medicine" />
        </Appbar.Header>
        <Searchbar
          placeholder="Search"
          onChangeText={onChangeSearch}
          value={searchQuery}
        />
        <FlatList
          data={data}
          keyExtractor={item => item.id}
          renderItem={({ item }) => (
            <Card>
              <Card.Content>
                <Title>{`${item.name.id}`}</Title>
                <Paragraph></Paragraph>
              </Card.Content>
              <Card.Cover  />
              <Card.Actions>
                <Button>info</Button>
              </Card.Actions>
            </Card>
          )}
        />
      </View>
  )
}

UPDATE
Add two if conditions, each returning a JSX for two different scenarios. First, when the data is fetched, a loading indicator is displayed. Second, when there is an error, an error message is displayed.
But it shows me the scenario of the error "Error fetching data... Check your network connection!"
export default function App() {
  // state variables defined

  // fetch data using useEffect

  if (isLoading) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" color="#5500dc" />
      </View>
    );
  }

  if (error) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text style={{ fontSize: 18}}>
          Error fetching data... Check your network connection!
        </Text>
      </View>
    );
  }
  // ...
}


text:
Q: Set encoding in aptana 3 I have just downloaded Aptana 3.2.2 (standalone version) for the latest Mac OS X. I cannot find out how to set the encoding (preferable UTF-8) for my specific html-document. In Aptana 2 and in Visual Studio this is an easy catch, but I have now scanned all the menues in Aptana 3.2.2 without success.

A: Assuming that version for linux is similar as for Mac OS X, try right click on the specific file in the App Explorer and then go Properties (or try Alt + Enter while you edit file you want to change encoding). On the bottom of tab Resources you have "Text file encoding" where you can adjust this setting.
Also if you want to set encoding for whole project go Project -> Properties from the top menu which will let you change it for a bunch of files.


text:
Q: How do I connect to Oracle Exadata from Python? I have tried connecting exadata from python using cx_Oracle, but faced issue stating
cx_Oracle.DatabaseError: DPI - 1047: Cannot locate a 64bit Oracle client library.
I am trying to install a 64bit cx_Oracle, but I need to know can I connect from python to exadata.

A: Follow the cx_Oracle Linux installation instructions.  The piece you are missing is access to Oracle Client libraries.  As noted in the other answer, using Instant Client is the way to go.  You'll need the "Basic" or "Basic Light" package for Linux x86-64.  If you don't know your character set requirement, then use "Basic".  You can use the latest 19c version.  This will let you connect to Oracle DB 11.2 and newer.
If you have root access (?) you may find the RPM packages easier.  If you want to use ZIP files, unzip the package, set your LD_LIBRARY_PATH environment variable to the directory, and run Python.
In your cx_Oracle scripts you use the same database credentials and connection string that you would use in SQL*Plus.

A: Welcome to Stack Overflow!
For the record, Oracle Exadata is a platform consisting of hardware and software designed for extreme Oracle Database performance. cx_Oracle is the Python client library to operate on an Oracle Database - hence you want to connect to an Oracle Database utilizing the Python programming language.
cx_Oracle depends on OCI (Oracle Call Interface). You need to download and install Oracle Client Library on your workstation before you can do import cx_Oracle from within Python.
You will find the Oracle Client Library here
Best of luck!


text:
Q: Not able to select value - error "Select only works on  elements, not on " I am trying to retrieve all possible year, model and make from [https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx]
from selenium import webdriver
import time
from selenium.webdriver.support.ui import Select
from bs4 import BeautifulSoup

driver = webdriver.Chrome()
driver.get("https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx")
# Switch to new window opened
driver.switch_to.window(driver.window_handles[-1])
# Close the new window
driver.close()
# Switch back to original browser (first window)
driver.switch_to.window(driver.window_handles[0])

el = driver.find_element_by_css_selector("div#fldYear a.sbToggle")
el.click()
select = Select(el)
select.select_by_visible_text("2016")

However if I try to select year 2016. It is giving error :
Select only works on <select> elements, not on <a>

A: The problem with your current approach is that you are finding the a element and trying to use it as a select element. Select class will only work with select elements.
Note that in this case, it's easier to get to the invisible select element and get the years from its options directly:
options = [option.get_attribute("innerText") for option in driver.find_elements_by_css_selector("select#ddlYear option")[1:]]
print(options)

The [1:] slice here is to skip the very first Select Year element.

Complete working code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver

driver = webdriver.Chrome("/usr/local/bin/chromedriver")
driver.get("https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx")

wait = WebDriverWait(driver, 10)
toggle = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#fldYear a.sbToggle")))
toggle.click()

options = [option.get_attribute("innerText") for option in driver.find_elements_by_css_selector("select#ddlYear option")[1:]]
print(options)

Prints:
[u'2016', u'2015', u'2014', u'2013', u'2012', u'2011', u'2010', u'2009', u'2008', u'2007', u'2006', u'2005', u'2004', u'2003', u'2002', u'2001', u'2000', u'1999', u'1998', u'1997', u'1996', u'1995', u'1994', u'1993', u'1992', u'1991', u'1990', u'1989', u'1988', u'1987', u'1986', u'1985', u'1984', u'1983', u'1982', u'1981', u'1980', u'1979', u'1978', u'1977', u'1976', u'1975', u'1974', u'1973', u'1972', u'1971', u'1970', u'1969', u'1968', u'1967', u'1966', u'1965', u'1964', u'1963', u'1962', u'1961', u'1960', u'1959', u'1958', u'1957', u'1956', u'1955']

A: You don't actually need selenium and automate any visual interactions to get the year+make+model data from the page and can approach the problem with requests only making appropriate GET requests:
# -*- coding: utf-8 -*-
from collections import defaultdict
from pprint import pprint

import requests

year = 2016
d = defaultdict(lambda: defaultdict(list))
with requests.Session() as session:
    session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'}
    session.get("https://www.osram-americas.com/en-us/applications/automotive-lighting-systems/Pages/lrgmain.aspx")

    while True:
        response = session.get("https://www.osram-americas.com/_Layouts/Sylvania.Web.LRGHandler/LRGHandler.ashx",
                               params={"rt": "fetchmake", "year": str(year)})

        data = response.json()
        if not data:  # break if no makes in a year
            break

        for make in data:
            response = session.get("https://www.osram-americas.com/_Layouts/Sylvania.Web.LRGHandler/LRGHandler.ashx",
                                   params={"rt": "fetchmodel", "year": str(year), "make": make["Id"]})

            for model in response.json():
                d[year][make["Value"]].append(model["Value"])

        year -= 1

pprint(dict(d))


text:
Q: How can i unify classes that have same purpose but different input and output to one interface I need to unify few classes that have same purposes but and use same method but with different parameters and results.
It probably sound odd to you so let me explain.
I have multiple classes that are connecting to multiple rest/web services to grab data from them. For this example lets say that all of those rest are weather forecast services. Each do same thing. Return forecast for some area, but all of them are doing it on theirs own way. For each service I have class that implement gathering data from it and map to my object :
public class AForecast
{
    public AForecastResult GetForecast (AForecastRequest request)
    {
         // Grab Forecast
    }
}

public class BForecast
{
    public BForecastResult GetForecast (BForecastRequest request)
    {
         // Grab Forecast
    }
}

I'm calling those classes, grab forecast data and then map it into my own object that I work with and this is fine. My problem is that right now I have 13 forecast services. Many of them are using similar method to map forecast result into my own object. Next problem is also that right now probably only I know how can I add new forecast into system. I want to unify that to be able add some interface into Forecast service implementation, and also some base forecast mapper.
I created Interface, but since i Have no idea how forecast result and request will look like it is very generic :
public interface IForecast<out TResult, in TRequest>
{
    TResult GetForecast(TReqiest request)
}

For each forecast I created separate interface that will implement IForecast
public interface IAForecast : IForecast<AForecastResult, AForecastRequest>
{
}

And my AForecast implementation started look like this :
public class AForecast : IAForecast
{
    public AForecastResult GetForecast (AForecastRequest request)
    {
         // Grab Forecast
    }
}

Thanks to that I have Forecast services that have it own interface that have common base interface.
Problem is when I want to use it in base class which will be able to call each forecast service and map objects :
public abstract ForecastBase
{
    private readonly ?ForecastService _service;
    protected ForecastBase(?ForecastService service)
    {
        _service = service;
    }

    public MapedObject GetForecast(DateTime date, string zip)
    {
        var request = GetRequest(date,zip);
        var forecastServiceResponse = _service.GetForecast(request);
        return Map(forecastServiceResponse);
    }

    protected abstract MapedObject Map(?Response response);
    protected abstract ?Request GetRequest(DateTime date, string zip);
}

Oh this was long. Now final question how can I implement ForeCast base class ? Base on my architecture how can I know what type will be ?ForecastService, ?Request and ?Response. I wish i can make mapper like that :
public class AMap : ForecastBase

And know that in that case ?ForecastService will be IAForecast,  ?Request will beAForecastRequest and ?Response will be AForecastResponse ?
In case you need more explanation feel free to ask.

A: I think what you need is the keyword where (not only but it's going to play a very important role here).
I defined the interfaces for the request and response like this:
public interface IForecastRequest
{

}

public interface IForecastResult
{

}

Then we can go on to defining the interface for the Forecast itself:
public interface IForecast<out TForecastResult, in TForecastRequest>
    where TForecastResult : IForecastResult where TForecastRequest : IForecastRequest
{
    TForecastResult GetForecast(TForecastRequest request);
}

What happens here is the following. Additionally to your solution, we restrain the generic types to implement our interfaces for request and response. We can then add the generic method to get the ForecastResult. By the way GetForecast also doesn't seem like a great name. Better would be GetResult or GetForecastResult otherwise you'd expect a different return-type.
Now we can implement the BaseForecast. I hope I understood correctly what this is supposed to do. Because you called it ForecastBase, I wasn't sure if this was supposed to do the same thing as IForecast. Maybe a better name would be a good idea here. I implemented it like this:
public abstract class BaseForecast<TForecastResult, TForecastRequest>
    where TForecastResult : IForecastResult where TForecastRequest : IForecastRequest
{
    private readonly IForecast<TForecastResult, TForecastRequest> _service;
    protected BaseForecast(IForecast<TForecastResult, TForecastRequest> service)
    {
        _service = service;
    }

    public MappedObject GetForecast(DateTime date, string zip)
    {
        TForecastRequest request = GetRequest(date, zip);
        TForecastResult forecastServiceResponse = _service.GetForecast(request);
        return Map(forecastServiceResponse);
    }

    protected abstract MappedObject Map(TForecastResult response);
    protected abstract TForecastRequest GetRequest(DateTime date, string zip);
}

Here we also have to add the wheres since we'll have to call the generic methods of the IForecast interface with the same constraints. You can see that in the constructor we provide an instance of an implementation of IForecast which will be our service. This service uses the two generic types we also have in the definiton of this baseclass. The GetForecast-method can now use the generic method of IForecast and the own generic method (GetRequest) to do get the MappedObject (which I don't know what it is). The types all align and you get handy intelisense and compiletime-typechecking for IForecastRequest and IForecastResult.
Please let me know if I understand the purpose of the ForecastBase correctly or not.
I hope this helps. I'm happy to try and answer any questions you might have on this.
Edit:

I wish i can make mapper like that..

The way you show there doesn't use any generic-type parameters. As far as I understand your intent, you will not be able to do this without specifying what result and request you want to use.
My way of creating an implementation for this is the following:
// implement request
public class SomeForecastRequest : IForecastRequest
{

}

// implement result
public class SomeForecastResult : IForecastResult
{

}

// implement forecast itself
public class SomeForecast : IForecast<SomeForecastResult, SomeForecastRequest>
{
    public SomeForecastResult GetForecast(SomeForecastRequest request)
    {
        // return the result you got from wherever
    }
}

public class SomeMapper : BaseForecast<SomeForecastResult, SomeForecastRequest>
{
    public SomeMapper(IForecast<SomeForecastResult, SomeForecastRequest> service) : base(service)
    {

    }

    protected override SomeForecastRequest GetRequest(DateTime date, string zip)
    {
        // return a request from wherever
    }

    protected override MappedObject Map(SomeForecastResult response)
    {
        // map the response and return it
    }
}

Edit 2:
I just read your comment which reads the following:

.. They are not related to each other. And those object don't have own interfaces, and I don't wrapped it in own interface

If you want to keep it this way, there is no way you can create a base-class for you mapper. The mapper need to know that the AForecast has a method called GetForecast. If it doesn't how is it going to call it. You're going to be in compiler-error land if you try this. You need to tell the compiler "this class can handle any class if it has the GetForecast-method" otherwise it will refuse to try and call GetForecast. The way to tell this to the compiler is by saying "dude look I got this awesome interface which has the GetForecast-method. I'm only going to allow the caller to use a class which implements this very interface so you can be sure the GetForecast-method exists. Alright?". This is why you use the where keyword and I thank you for your question because this is a very good (but not too easy) example on how to use it.
Edit 3:
By the way there is nothing stopping you from using classes instead of interfaces for IForecastRequest and IForecastResult (of course you would change the name but everything else could stay the same). I don't know what your request and response object is supposed to do/store so I don't know if using classes over interfaces is the right call for you here.
I just wanted to throw out there that this would be possible too.
I'd love to hear some feedback from you :)


text:
Q: Unrecognized option "form_login" under "security.firewalls.main" I'm using Symfony 3.0.4 and FOSUserBundle 2.0.
When I try to configure my security like the symfony doc:
security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        in_memory:
            memory: ~
        fos_userbundle:
            id: fos_user.user_provider.username

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
            logout:       true
            anonymous:    true

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, role: ROLE_ADMIN }

I have an error :
InvalidConfigurationException in ArrayNode.php line 317:
Unrecognized option "form_login" under "security.firewalls.main"

What is the problem ? form_login just seems to be an option...
Thanks

A: Trash but I have just removed the vendor/symfony folder and run a composer update.
Now it's working.


text:
Q: setting custom permissions for the file and inheriting ownership from pattern folder in JS I need to set custom permission and inherit ownership from parent directory after writing to file in JS. I'm using to shelljs to run the commands.
I'm running the following to get the owner and group of the parent directory:
const ownerGroup = shelljs.exec('ls -la ../ | grep -e "`basename $(pwd)`$"  | awk \'{print $3, $4}\'').split(' ');
The commands to set the permissions and ownership are as follows:
const owner = ownerGroup[0];
const group = ownerGroup[1];
shelljs.exec(`sudo chown ${owner}:${group} ${process.env.CONFIG_FILE}`);
shelljs.exec(`sudo chmod 660 ${process.env.CONFIG_FILE}`);

The file path is in process.env.CONFIG_FILE. I run into issues with chown as is doesn't see the file path. The command is structured correctly, but the path shifts to the new line.
COMMAND ->  sudo chown yury.stanev:yury.stanev
/home/yury.stanev/menlolab/runner/config.json
chown: missing operand after 'yury.stanev:yury.stanev'
Try 'chown --help' for more information.

A: Fixed by replacing any new line character in cmd with nothing.
const cmd = `sudo chown ${owner}:${group} ${process.env.CONFIG_FILE}`.replace('\n', '');


text:
Q: Using numpy to extract data from CSV file I'm working with numpy and trying to find which platform sold the most copies in NA region.
I have a CSV file holding a lot of data looking like this:
Rank,Name,Platform,Year,Genre,Publisher,NA_Sales,EU_Sales,JP_Sales,Other_Sales,Global_Sales
1,Wii Sports,Wii,2006,Sports,Nintendo,41.49,29.02,3.77,8.46,82.74
2,Super Mario Bros.,NES,1985,Platform,Nintendo,29.08,3.58,6.81,0.77,40.24
3,Mario Kart Wii,Wii,2008,Racing,Nintendo,15.85,12.88,3.79,3.31,35.82
4,Wii Sports Resort,Wii,2009,Sports,Nintendo,15.75,11.01,3.28,2.96,33
5,Pokemon Red/Pokemon Blue,GB,1996,Role-Playing,Nintendo,11.27,8.89,10.22,1,31.37
6,Tetris,GB,1989,Puzzle,Nintendo,23.2,2.26,4.22,0.58,30.26
7,New Super Mario Bros.,DS,2006,Platform,Nintendo,11.38,9.23,6.5,2.9,30.01
8,Wii Play,Wii,2006,Misc,Nintendo,14.03,9.2,2.93,2.85,29.02
9,New Super Mario Bros. Wii,Wii,2009,Platform,Nintendo,14.59,7.06,4.7,2.26,28.62
10,Duck Hunt,NES,1984,Shooter,Nintendo,26.93,0.63,0.28,0.47,28.31
11,Nintendogs,DS,2005,Simulation,Nintendo,9.07,11,1.93,2.75,24.76

I would like to print the platform with the most sales and the amount sold in the NA region. How can I do this?

A: With pandas this is fairly straight forward.
Code:
# read csv data into a dataframe
df = pd.read_csv(data, skipinitialspace=True)

# roll up by NA Sales
platform_roll_up = df.groupby('Platform')['NA_Sales'].sum()

# find row with max sales
idx_max = platform_roll_up.idxmax()

# show platform and sales for max
print(idx_max, platform_roll_up[idx_max])

Results:
Wii 101.71

Test Data:
data = StringIO(u"""
    Rank,Name,Platform,Year,Genre,Publisher,NA_Sales,EU_Sales,JP_Sales,Other_Sales,Global_Sales
    1,Wii Sports,Wii,2006,Sports,Nintendo,41.49,29.02,3.77,8.46,82.74
    2,Super Mario Bros.,NES,1985,Platform,Nintendo,29.08,3.58,6.81,0.77,40.24
    3,Mario Kart Wii,Wii,2008,Racing,Nintendo,15.85,12.88,3.79,3.31,35.82
    4,Wii Sports Resort,Wii,2009,Sports,Nintendo,15.75,11.01,3.28,2.96,33
    5,Pokemon Red/Pokemon Blue,GB,1996,Role-Playing,Nintendo,11.27,8.89,10.22,1,31.37
    6,Tetris,GB,1989,Puzzle,Nintendo,23.2,2.26,4.22,0.58,30.26
    7,New Super Mario Bros.,DS,2006,Platform,Nintendo,11.38,9.23,6.5,2.9,30.01
    8,Wii Play,Wii,2006,Misc,Nintendo,14.03,9.2,2.93,2.85,29.02
    9,New Super Mario Bros. Wii,Wii,2009,Platform,Nintendo,14.59,7.06,4.7,2.26,28.62
    10,Duck Hunt,NES,1984,Shooter,Nintendo,26.93,0.63,0.28,0.47,28.31
    11,Nintendogs,DS,2005,Simulation,Nintendo,9.07,11,1.93,2.75,24.76
""")

A: Loading this with genfromtxt is straight forward:
In [280]: data=np.genfromtxt('stack42602390.csv',delimiter=',',names=True, dtype=None)

In [281]: data
Out[281]:
array([ ( 1, b'Wii Sports', b'Wii', 2006, b'Sports', b'Nintendo',  41.49,  29.02,   3.77,  8.46,  82.74),
       ( 2, b'Super Mario Bros.', b'NES', 1985, b'Platform', b'Nintendo',  29.08,   3.58,   6.81,  0.77,  40.24),
       ( 3, b'Mario Kart Wii', b'Wii', 2008, b'Racing', b'Nintendo',  15.85,  12.88,   3.79,  3.31,  35.82),
....
       (11, b'Nintendogs', b'DS', 2005, b'Simulation', b'Nintendo',   9.07,  11.  ,   1.93,  2.75,  24.76)],
      dtype=[('Rank', '<i4'), ('Name', 'S25'), ('Platform', 'S3'), ('Year', '<i4'), ('Genre', 'S12'), ('Publisher', 'S8'), ('NA_Sales', '<f8'), ('EU_Sales', '<f8'), ('JP_Sales', '<f8'), ('Other_Sales', '<f8'), ('Global_Sales', '<f8')])

The b'string' is just the Python3 way of showing bytestrings, the default string format from genfromtxt.  They won't show in Py2.
The result is a structured array, with different field names and types.  It is not a 2d array with rows and columns.
The NA_Sales data:
In [282]: data['NA_Sales']
Out[282]:
array([ 41.49,  29.08,  15.85,  15.75,  11.27,  23.2 ,  11.38,  14.03,
        14.59,  26.93,   9.07])

And the maximum of these:
In [283]: np.argmax(data['NA_Sales'])
Out[283]: 0

and the corresponding record:
In [284]: data[0]
Out[284]: (1, b'Wii Sports', b'Wii', 2006, b'Sports', b'Nintendo',  41.49,  29.02,  3.77,  8.46,  82.74)

To make the most use of this array you'll have to read up on structured arrays.


text:
Q: How to group by name of key name in object and sum its value in php I have some data in mongoDB and i want to group and sum it in object key - value:
{
    '_id': '1',
    'value': {
        A: 1,
        B: 2,
        C: 3
    }
},
{
    '_id': '2',
    'value': {
        B: 2,
        C: 3
    }
}

I need to group by keys name and sum the value of each key - that value. For the example above the result would be:
{
    '_id': 'A',
    'total': 1
},
{
    '_id': 'B',
    'total': 4
},
{
    '_id': 'C',
    'total': 6
}

A: Query

*

*if those fields(A,B,C) are unknown, we have to make it so the schema is stable, so we can group by a common field, so object to array is used

*unwind to make the array members separate documents

*group and sum the values

*if your fields are unknown its not good idea, its best the schema to be known, even if some fields can be missing, but not knowing the schema causes many problems while querying
Playmongo
aggregate(
[{"$set": {"value": {"$objectToArray": "$value"}}},
 {"$unwind": "$value"},
 {"$group": {"_id": "$value.k", "count": {"$sum": "$value.v"}}}])

A: Here's how to do this with PHP, I'm not sure if there's a more efficient way to do it on the DB level. But this does the trick, you might need to wrap your json keys with a quotation first ("A": instead of A:)
<?php

$json_string = '
[{
    "_id": "1",
    "value": {
        "A": 1,
        "B": 2,
        "C": 3
    }
},
{
    "_id": "2",
    "value": {
        "B": 2,
        "C": 3
    }
}]';

function groupByKeys($json_string) {
    // convert json_string to an array
    $json_array = json_decode($json_string, true );
    $result = array();
    foreach ($json_array as $key => $value) {
        foreach ($value['value'] as $key2 => $value2) {
            if (isset($result[$key2])) {
                $result[$key2] += $value2;
            } else {
                $result[$key2] = $value2;
            }
        }
    }
    return $result;
}

echo json_encode(groupByKeys($json_string));


text:
Q: Max heap size reduced from java 6 to java 7? Currently we are encountering an problem, our java application can run smoothly with JRE6, but for JRE7, it will report "Could not create the Java virtual machine" sometimes and failed to start program. we have "-Xmx1024m" option in the launch command line.
after searching in google, people suggest check the max heap size that can be requested in PC. then I tried below ones.
for JRE6,
C:\Users\joey>java -Xmx1214m -version
java version "1.6.0_45"
Java(TM) SE Runtime Environment (build 1.6.0_45-b06)
Java HotSpot(TM) Client VM (build 20.45-b01, mixed mode)

C:\Users\joey>java -Xmx1215m -version
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

for JRE7,
D:\Program Files\Java\jre7\bin>java.exe -Xmx930m -version
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) Client VM (build 24.51-b03, mixed mode)

D:\Program Files\Java\jre7\bin>java.exe -Xmx931m -version
Error occurred during initialization of VM
Could not reserve enough space for object heap
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

And when i close most processes in PC and free memory to 2.5 GB, for JRE7, it will succeed with 1094m, like below.
D:\Program Files\Java\jre7\bin>java.exe -Xmx1094m -version
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) Client VM (build 24.51-b03, mixed mode)

D:\Program Files\Java\jre7\bin>java.exe -Xmx1095m -version
Error occurred during initialization of VM
Could not reserve enough space for object heap
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

It seems that the max heap size that JVM can request is related with system available memory size, does someone know the exact relationship?
Is there some way to enable tracing logs of JRE when creating JVM?
Thank you!
Regards,
Joey

A: I faced the same issue on various Windows OS flavous (Win7, Win2008R2) while having enough free RAM (3-5G), when switching from jre6_20 to jre7_51 (both 32 bit VMs)
Using vm args -Xmx1300m and -XX:MaxPermSize=256m on java 6 the VM is able to start. However, with java7 I had to lower down startup max memory (xmx with 100m or permgen with 100m) in order to be able to start VM.
The interesting part is this: if I restarted my box, the jvm 7 started with original vm args (-Xmx1300m and -XX:MaxPermSize=256m) so I suspect the root cause might be the OS with JVM combination.
I know that on Windows OSes - 32 bit VMs expect to have a single large chunk of memory, but  cannot use the maximum process memory size will range from 1.4G to 1.6G (because of additional constraints)
Any troubleshooting pointers? Oracle does not provide any information in java7 release notes (or I could not spot those)

A: I have a similar problem Windows 7 64bit, no JAVA_HOME set nor in PATH
This fails
"C:\Program Files (x86)\Java\jdk1.7.0_51\bin\java.exe" -Xms32m -Xmx1024m -XX:MaxPermSize=256m -version
Error occurred during initialization of VM
Could not reserve enough space for object heap
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

This works
"C:\Program Files (x86)\Java\jdk1.7.0_51\bin\java.exe" -Xms32m -Xmx512m -XX:MaxPermSize=256m -version
This also works (I can recompile or not, doesn't make a difference
"C:\Program Files (x86)\Java\jdk1.6.0_45\bin\java.exe" -Xms32m -Xmx1024m -XX:MaxPermSize=256m -version
I tried turning off windows DEP, didnt make a difference
http://windows.microsoft.com/en-us/windows-vista/data-execution-prevention-frequently-asked-questions
I twiddled with the Virtual Memory settings , changed from allowing Windows to Manage
http://windows.microsoft.com/en-us/windows/change-virtual-memory-size#1TC=windows-7
I upped the Virual Memory in windows and it allowed it to work, sometimes...(with xmx1024)
Nothing else is consuming a lot of resources (memory, etc, I did have oracle database running locally, but shut it down)
"C:\Program Files (x86)\Java\jdk1.7.0_51\bin\java.exe" -Xms32m -Xmx1024m -XX:MaxPermSize=256m -version
Error occurred during initialization of VM
Could not reserve enough space for object heap
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
This works
"C:\Program Files (x86)\Java\jdk1.7.0_51\bin\java.exe" -Xms32m -Xmx900m -XX:MaxPermSize=256m -version
This fails
U:>"C:\Program Files (x86)\Java\jdk1.7.0_51\bin\java.exe" -Xms32m -Xmx2024m -XX
:MaxPermSize=256m -version
Error occurred during initialization of VM
Could not reserve enough space for object heap
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
New version , works even with letting Windows Managage the Virtual Memory and DEP turned on
"C:\Program Files (x86)\Java\jdk1.7.0_65\bin\java.exe" -Xms32m -Xmx1024m -XX:MaxPermSize=256m -version


text:
Q: Batch Script To Extract Lines Between Specific Words and re-format the output file I have a "test.txt" file in the format of:
xdfdfdf
ydffddf
zddfdfd
blah ...
WordA
12
23
45
...
32
12
65
xdfdfdf
ydffddf
zddfdfd
blah ...
WordA
54
76
67
...
68
31
85
xdfdfdf
ydffddf
zddfdfd
blah ...
WordA
89
65
45
...
32
51
75
xdfdfdf
ydffddf
zddfdfd
blah ...
....

I want to extract only the numbers below each "wordA", re-format data in a row with a 2 skip format and make an output file (like "Output.txt"). It must be noted that the No of lines under each "wordA" with numerical data is fixed (for example 18 lines).
The results should be in this format:
12 45 ... 32 65
54 67 ... 68 85
89 45 ... 32 75
....

Could anybody help me through? I found the FindRepl.bat, however, I cannot employ what I want. I prefer sth simple and brief.
I have little knowledge of batch script programming and also try writing a nested loops for it, but it does not work.
@echo off
setlocal enabledelayedexpansion

SET InFile=Test2.txt
SET OutFile=Output.txt
IF EXIST %OutFile% del /F %OutFile%

FOR /f "delims=:" %%a IN ('findstr /n "wordA" "%InFile%"') DO (
   SET /a first=%%a + 1
   SET /a last=%%a + 18
   SET i=0
   SET ROW=!first!

   FOR /f "skip=!first! delims=" %%b IN (%InFile%) DO (
      if !first! LEQ !last! set Data[!i!]=%%a
      echo %%b
   )
)

endlocal

A: @echo off
setlocal EnableDelayedExpansion

SET InFile=Test2.txt
SET OutFile=Output.txt

set "i="
(for /F "delims=" %%a in (%InFile%) do (
   if defined i (
      set /A i+=1, odd=i%%2
      if !odd! equ 1 set "line=!line! %%a"
      if !i! equ 18 (
         echo !line:~1!
         set "i="
      )
   ) else if "%%a" equ "WordA" (
      set i=0
      set "line="
   )
)) > %OutFile%


text:
Q: Websocket on Tomcat 7.0.39 on openshift I've just successfully installed Apache Tomcat 7.0.39 on my openshift account (tomcat-ngoanhtuanthesis.rhcloud.com/). I know that tomcat 7.0.39 has supported Websocket. In my local computer, I can run my web socket aplication properly, but I cannot run it in the openshift server. However, my web service application can run very well. I've searched over the Internet for the whole week but I couldn't find any solution. Can anyone help me? Thank you in advance!
Note: here is my Web service:
tomcat-ngoanhtuanthesis.rhcloud.com/TrueTrafficServerAlpha2/
And here are some websocket examples integrated in Tomcat 7.0.39. These examples cannot run even though they are very simple.
http://tomcat-ngoanhtuanthesis.rhcloud.com/examples/websocket/

A: Did you read this? https://www.openshift.com/blogs/paas-websockets
WebSockects are currently under staging on openshift, and are available on alternative ports.

How to access Preview WebSockets Support?
You will need to connect to
  specific ports, as the main routing layer is still Apache based and
  does not support WebSockets.
So, for plain WebSockets ws:// you will use port 8000 and for secured
  connections wss:// port 8443. Here's an example:

http://app-lovingwebsockets.rhcloud.com/  <= your current HTTP URL
http://app-lovingwebsockets.rhcloud.com:8000/ <= WebSockets enables HTTP URL
https://app-lovingwebsockets.rhcloud.com/  <= your current HTTPs URL
https://app-lovingwebsockets.rhcloud.com:8443/ <= WebSockets enables HTTPs URL

So, just open your samples here, and they will just work (hopefully):
https://tomcat-ngoanhtuanthesis.rhcloud.com:8443/examples/websocket/


text:
Q: android - Transparent Navigation Bar but not Status Bar I am not sure if it is possible but I am trying to make the Navigation Bar transparent without making the Status Bar transparent. The reason for the later is I have a Toolbar that would otherwise draw behind the status bar.
Right now I am using a fakeStatusBar Layout that displays before the status bar so everything looks good to the user:
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        Window window = getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        //now the status bar is transparent too, which we have to fix

        //first we get status bar height
        int statusBarHeight = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }

        //then we get the full width
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int screenWidth = size.x;

        //then we set that height to the fake item in the layout
        LinearLayout fakeStatusBar = findViewById(R.id.fakeStatusBar);
        ViewGroup.LayoutParams params = fakeStatusBar.getLayoutParams();
        params.height = statusBarHeight;
        params.width = screenWidth;
        fakeStatusBar.setLayoutParams(params);

The only problem is when going to multitasking, the thumbnail does not look good because the toolbar is not where it should be.

A: Not exactly what I wanted but I found a workaround using Translucent Navigation Bar. The final code looks something like this:
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){

        //set navigation bar translucent
        Window window = getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        //now the status bar is translucent too, which we have to fix

        //first we get status bar height
        int statusBarHeight = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }

        //then set it as top padding for the main layout
        ConstraintLayout mainLayout = (ConstraintLayout) findViewById(R.id.mainLayout);
        mainLayout.setPadding(0,statusBarHeight,0,0);
    }

Where top padding is added to the main layout of the activity.
If anyone knows how to do something similar with transparent navigation bar, perfect, but otherwise I am happy with my solution.


text:
Q: SQL - Ordering with part of string Sorry for repost. But I need. I have 8 length string and my query;
select distinct Siparisler.IsEmriNo, MakinelerVeParcalar.Ozellik, DurumBilgisi.ID
from Siparisler,
     MakinelerVeParcalar,
     DurumBilgisi
where DurumBilgisi.ID = MakinelerVeParcalar.ID
  and Siparisler.IsEmriNo = MakinelerVeParcalar.IsEmriNo

and my IsEmriNo list;
MR18U001
MR18U002
MR18V001
MR19U003
MR19V002
MR19V001
OC19U002
OC18V005
OC18U007
SB18U010
SB18V005
SB19U028

And I want
MR19U003
MR19V002
MR19V001
SB19U028
OC19U002
MR18U002
MR18U001
MR18V001
SB18U010
SB18V005
OC18U007
OC18V005

First ordering:
3rd and 4th character (Descending 19,18,17 ...)
Second ordering:
1st and 2nd character (Ascending MR,SB,OC ... -> specific for me)
Third ordering:
Last 3 character (Descending 030,029,028 ... 001)
Not duplicate with my old post.
Is it possible?

A: The following order by will work in your scenario:
order by substring(IsEmriNo, 3, 2) desc,
         CASE WHEN IsEmriNo LIKE '%MR%' THEN 0
              WHEN IsEmriNo LIKE '%SB%' THEN 1
              WHEN IsEmriNo LIKE '%OC%' THEN 2
             END,
         right(IsEmriNo, 3) desc


text:
Q: Pokemon Go Verifying Wrong Email I changed my Pokemon Go email, but I think I might have accedently typed the wrong email now it's asking me to verify when I go on the game and it won't let me check the email I typed or let me change it and I can't verify it. Please help me!

A: I had the same problem, I just happened to write the email account for my friend's account. If you haven't pressed the "vertify" button on the app but just closed it, you can go in on the webbrowser and sign out of your account on google, then open the app again and sign up with google. Then you can just sign in and it worked for me. So that can definitely be an opportunity if you messed up like I did. :)

A: I am in the same boat, I've emailed tech support but I don't expect a reply anytime soon with the amount of work they must have at the mo!
You can check if you did enter the wrong email by trying to sign up again - it will tell you if your email address is already associated to an account.
I take it you've checked your junk folders?
As far as I can work out there is no way to change the email address associated with the account without logging in first - which of course you can't do without verifying >.<
Hopefully they will get back to a tech support email aventually because I had made good progress on PokemonGo already, in the meantime I've started again from scratch using a Google account, hopefully can trade over the Pokemon at some point in the future!


text:
Q: Header customization failed I'm trying to add a Authorization header in my ajax request but I can't get to it.

import Ember from 'ember'

AppsRoute = Ember.Route.extend
  model: (params) ->
    return Ember.RSVP.hash
      count: $.getJSON window.Cockpit.API_URL + "apps/count/" + params.year
      accumulation: $.getJSON window.Cockpit.API_URL + "apps/accumulation/" + params.year

  setupController: (controller, model, queryParams) ->
    controller.set 'model', model.count
    controller.set 'accumulation', model.accumulation
    controller.set 'param', queryParams.params.apps.year

export default AppsRoute

I extended the RESTAdapter class like that :

import DS from 'ember-data'

AppAdapter = DS.RESTAdapter.extend
  headers:
    'Authorization': 'Basic XXX'

export default AppAdapter

But my header is not present in the request.
Can anyone help me ?
Thanks,
Gabriel

A: Problem solved, I have not declared my models.


text:
Q: JSDoc typedef methods in VS Code I have an issue when trying to document javascript methods,
I tried this:

I really don't think I should be setting a property for getMother() but rather a method.
Yet I don't know if it's even supported (I'm using VS Code).
So the given example might work, but it doesn't add parenthesis when autocompleting and just isn't clean because we are seeing it as a property.
I spent a few hours searching for a solution and failed.
I hope someone knows the answer, feel free to ask for more details.

A: You can try something like this:
// @ts-check

/*
 * @typedef {{
 * age: number,
 * getMother(arg1: string, arg2: string): HTMLCat
 * } & HTMLElement} HTMLCat
 */

/*
 * @type {HTMLCat}
 */
var cat;

cat.getMother('a', 'b').age

I'm not sure what AdditionalCat is doing exactly since it's just an object, which would likely correlate with the key/value index I added, so I left it out. But this syntax might be a bit easier to reason about.
You can find more examples here: https://medium.com/better-programming/type-checking-in-vscode-without-typescript-eba92161cd08


text:
Q: Multiple windows in eclipse window builder I am using Google Window Builder for eclipse to create the UI aspect of my program. I need to create a preferences window so that the user can change different settings for the program. I want the user to be able to press the 'preferences' button in the menu to bring up a separate window. The problem I am having is that I do not know how to create or add components to this separate window visually through Window Builder. Is there a way I can create a jpanel that is not a child of the main jframe program through Window Builder?

A: Right click on the package where you want the file for the new window to be stored. Go "New -> Other" and select "WindowBuilder -> Swing Designer -> JDialog". Write in a name for the class of the new Window. That will bring up an editor, select "Design" tab at the bottom of the window. Now you can customize this new window.
To open this window from your main JFrame you'll need do this:
MyNewWindowClass newWindow = new MyNewWindowClass();
newWindow.setVisible(true);


text:
Q: Необходим совет для выполнения задачи Нашел вот такое задание на должность Junior Android:
Сделать 2 экрана:
1-й экран принимает номер телефона с форматированием его по маске ввода номера.
После валидации номера, переход на 2-ой экран.
2-ой экран - вводится смс код 4-х значный.
На обоих экранах присутствует навигационный бар.
На экране смс кода стоит 60 секундный таймер, по завершению которого вместо текста отсчёта появляется кликабельная текстовая кнопка (например, далее).
Дизайн можете взять с любого топового приложения по вашему вкусу.
Роутинг можно сделать либо на фрагменты либо на view.
Желательно без xml (научим).

Собственно вопросы:

*

*Номер телефона с форматированием его по маске ввода номера. Первая идея просто в какой нибудь EditText закидыват номер и проверять на его длину. Но что делать с кодами разных стран (которые имеют разную длину?)

*На обоих экранах присутствует навигационный бар. Что под ним имеется ввиду? Navigation Bottom Bar?

*Роутинг можно сделать либо на фрагменты либо на view. что понимается под этим словом? На чем верстать (2 Activity, или 1 Activity + 2 Fragment?)

*Желательно без xml (научим). Это как я понял не использовать макет в Layout, а писать его из кода?