text:
Q: Accessing stack objects outside a function If I have a function that creates a STL object on the stack and adds them to the stack. For example say I make std::pair on the stack and add them to a std::queue that is made on the heap. Now if I pass the queue outside the function, can a different function that takes the queue as a parameter access the std::pair objects.

A: Depends on a few factors you don't mention.
The first thing to check is whether you're copying the object into the queue, or copying a pointer to the object into the queue. Here's examples of each.
std::queue<A> copyQueue;
std::queue<A*> pointerQueue;

void addCopy(A a) {
  copyQueue.add(a);
}

void addPointer(A a) {
  pointerQueue.add(&a);
}

If it's storing copies of the objects, then anything with access to the queue can access that object without issue. If it's storing pointers, it depends on whether that stackframe has been reclaimed. If the stackframe is untouched, accessing that memory will be fine. Otherwise, the value will be garbage.
Legal example:
Function A adds a pointer to a stack allocated object to std::queue Q, and then passes Q to function B. Since function A has not yet returned, function B can access the object in Q without issue.
Garbage example:
Function A adds a pointer to a stack allocated object to std::queue Q, and then returns Q to its calling function B. Since function A has returned, function B will receive garbage if it tries to access the object in Q.

A: When you push an object (std::pair in your case) in a std::queue it is copied from local scope into the queue. Therefore when the local object goes out of scope and is deleted, its copy in the queue is still valid until the queue itself gets deleted.
As a side note prefer emplace over push as it will construct the std::pair in place in the queue instead of copying.

A: Yes, because when you "add" the object from the stack to object from the heap you will do a copy of the information that resides on stack to the "heap".


text:
Q: Access property of parent struct in a nested Codable struct when decoding the child When using a decoder in a nested Codable struct, is there any way to access a property of a parent struct?
The only way I can think of that might work (haven't tested yet) is to use a manual decoder in the parent struct too, set the property in the userInfo dictionary, and then access userInfo in the child struct. But that would result in a lot of boilerplate code. I'm hoping there's a simpler solution.
struct Item: Decodable, Identifiable {
    let id: String
    let title: String
    let images: Images

    struct Images: Decodable {
        struct Image: Decodable, Identifiable {
            let id: String
            let width: Int
            let height: Int

            init(from decoder: Decoder) throws {
                let container = try decoder.container(keyedBy: CodingKeys.self)
                width = try container.decode(Int.self, forKey: .width)
                height = try container.decode(Int.self, forKey: .height)

                // How do I get `parent.parent.id` (`Item#id`) here?
                id = "\(parent.parent.id)\(width)\(height)"
            }
        }

        let original: Image
        let small: Image
        // …
    }
}

In the above example, the item ID coming from the server is only defined in the top-level properties in the JSON, but I need them in the children too, so I can also make them Identifiable.

A: I managed it using Itai Ferber's suggestion as mentioned by @New Dev in the following way:

*

*Create a new reference type whose only purpose is to contain a
mutable value that can be passed between parent and child.

*Assign an instance of that type to the JSONDecoder's userInfo dictionary.

*Retrieve that instance when decoding the parent and assign to it the id that you're interested in passing.

*Whilst decoding the child, retrieve that id from the instance stored in the userInfo earlier.

I've modified your example above as follows:
struct Item: Decodable, Identifiable {

    enum CodingKeys: String, CodingKey {
        case id
        case title
        case images
    }

    let id: String
    let title: String
    let images: Images

    struct Images: Decodable {
        struct Image: Decodable, Identifiable {
            let id: String
            let width: Int
            let height: Int

            init(from decoder: Decoder) throws {
                let container = try decoder.container(keyedBy: CodingKeys.self)
                width = try container.decode(Int.self, forKey: .width)
                height = try container.decode(Int.self, forKey: .height)

                if let referenceTypeUsedOnlyToContainAChangeableIdentifier = decoder.userInfo[.referenceTypeUsedOnlyToContainAChangeableIdentifier] as? ReferenceTypeUsedOnlyToContainAChangeableIdentifier {
                    self.id = referenceTypeUsedOnlyToContainAChangeableIdentifier.changeableIdentifier
                } else {
                    self.id = "something went wrong"
                }
            }
        }

        let original: Image
        let small: Image
        // …

        init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            id = try container.decode(String.self, forKey: .id)
            if let referenceTypeUsedOnlyToContainAChangeableIdentifier = decoder.userInfo[.referenceTypeUsedOnlyToContainAChangeableIdentifier] as? ReferenceTypeUsedOnlyToContainAChangeableIdentifier {
               referenceTypeUsedOnlyToContainAChangeableIdentifier.changeableIdentifier = id
            }
        }
    }
}

// Use this reference type to just store an id that's retrieved later.
class ReferenceTypeUsedOnlyToContainAChangeableIdentifier {
    var changeableIdentifier: String?
}

// Convenience extension.
extension CodingUserInfoKey {
    static let referenceTypeUsedOnlyToContainAChangeableIdentifier = CodingUserInfoKey(rawValue: "\(ReferenceTypeUsedOnlyToContainAChangeableIdentifier.self)")!
}

let decoder = JSONDecoder()
// Assign the reference type here to be used later during the decoding process first to assign the id in `Item` and then
// later to retrieve that value in `Images`
decoder.userInfo[.referenceTypeUsedOnlyToContainAChangeableIdentifier] = ReferenceTypeUsedOnlyToContainAChangeableIdentifier()

redpajama_set_name: RedPajamaStackExchange


text:
Q: When two CCMenuItem overlaps each other, is it possible to prioritise one over the other? I have 2 CCMenuItems A and B
A is a screen-wide transparent button
and B is an actual button that is set to visible when A is touched
Currently, when I'm touching B, A responds with it's selector method and basically B does not respond because the touch is 'taken' by A's selector.
I need B to be responding even though A is a screen-wide button so- Is it possible to prioritise B's selector when it is pushed?
To summarize, I'm toggling B's visibility via A and would like to be able to use B when it is visible.
Is this possible? How can it be done?

A: for me worked adding one menu in one layer and another menu in other layer

A: I)
Yes, You can prioritize your CCMenuItems by setting Z-Order.
First button that gets touch is the button with lowest Z-Order.
II)
And if you want to prioritize your CCMenus, you need to setTouchPriority(..) them.
The less priority you give, the earlier your CCMenu will handle the touch. (CCMenu's default value is -128 ).

A: Either you can set the buttons yourButton.isEnabled to NO or you can just move the A-button off the scene when you don't want it to take input.

A: It's possible to use an additional CCMenu with a higher z-order for the button B.


text:
Q: SensorEvent.timestamp date conversion issue I'm trying to convert event timestamp in a date, my code:
Calendar c = Calendar.getInstance();
c.setTimeInMillis(event.timestamp/1000000);//time in ms (timestamp is in ns)
System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(c.getTime()));

How come I get 1970-01-02?

A: I assume that you are using SensorEvent.timestamp. The documentation fails to mention that this is the awake time in nanoseconds since the last boot (comparable to SystemClock.uptimeMillis()), not time since Unix epoch. In short, it appears your device has been awake for less than two days.
Also, Calendar.getTime() returns a Date object and there is a Date constructor that takes milliseconds so  you can shorten your code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date(event.timestamp / 1000000)));


text:
Q: python-docx modify docx file normal text type to header I have a docx file of the following format:
-------------
header 1
-------------
Text
Text

-------------
header 2
-------------
Text2
text2

-------------
header 3
-------------
Text3
text3

-------------
header 4
-------------
Text4
text4

...

I would like to use the docx / python-docx library to modify the docx file so that every (plain text) header + number is converted to Word "Header" format, so that I can create a table of contents of all the headers. The file contains around 1000 headers so it is very big.
Is this possible with the docx library?

A: I actually figured it out in a bit different way: I rolled back to my attempt in creating the .docx file (including its headers) from scratch, because I couldn't find a way to modify the existing file (or at least, its headers).
Here is how I created the .docx file from a number of .txt files which have a heading at the beginning of every file:
# Find all the txt files in the dataset folder
inputs = []
for file in os.listdir('C:\\Users\\your_user_name\\your_folder'):
    if file.endswith(".txt"):
        inputs.append(os.path.join("C:\\Users\\your_user_name\\your_folder", file))

# Concatenate all .txt files in a file called my_written_file.docx and add a paragraph for every .txt file content
mydoc = Document()

mydoc.add_heading("MAIN_HEADING_NAME", 0)
mydoc.add_paragraph("\n")

for fname in inputs:
    with open(fname, encoding="utf-8", errors='ignore') as infile:
        mydoc.add_heading(str(fname[65:]), 1) # sub-heading picked from the beginning of the .txt file
        mydoc.add_paragraph("\n")
        mydoc.add_paragraph(infile.read())
        mydoc.add_paragraph("\n")
mydoc.add_paragraph("\n\n\n----------END OF FILE----------")
mydoc.save("C:\\Users\\your_user_name\\your_folder\\my_written_file.docx")


text:
Q: Prove: every subspace of finite codimension is dense in $L^p$ with $p \in (0,1)$ $X$: vector space, $N$ is subspace of $X$, the codimension of $N$ in $X$ is, by definition, the dimension of the quotient space $X/N$. Suppose $0<p<1$ and prove that every subspace of finite codimension is den in $L^p$ (Problem 1.11,p.39 in Functional analysis)(Rudin). Thanks in advance.

A: Suppose not, so that there is a non-dense subspace $N$ of $L^p$ of finite codimension. The closure $\bar N$ is a proper closed subspace, also of finite codimension and then $X/\bar N$ is a finite dimensional vector space of positive dimension, so there exist a non-zero linear function $\phi:X/\bar N\to\mathbb R$ and it is automatically continuous. The composition of $\phi$ with the projection map $L^p\to L^p/\bar N$ is a non-zero continuous linear map $L^p\to\mathbb R$.
This is absurd, for there are no such things.


text:
Q: How to handle the react native ble plx [BleError: Operation was rejected]? I have problem with react native ble plx.
I try to print the image screenshot from component using react native viewshot and then i convert those file to string base64 after that i try to print to my bluetooth third party devices. but it doesnt work. i follow documentation and try to find solution by googling and experiment but still. im stuck.
async print(text: string) {
    if (!connectedDevice) return;
    const file = await RNFS.readFile(text, 'base64').then((res) => {
      return res;
    });

bleManager
  .writeCharacteristicWithResponseForDevice(
    connectedDevice?.id,
    SerialServiceUUID,
    SerialCharacteristicUUID,
    file,
  )
  .then((resp) => {
    console.log('WRITE resp = ', resp);
  })
  .catch((err) => {
    console.log('WRITE err = ', err);
  });}


text:
Q: Could not load the "" image referenced from a nib - can it be due to image="imageView:" I've tried various tips for identifying the source of this error in my code. But so far unsuccessful. It happens when i load a new ViewController, so I assume it has something to do with the assets that I use.
I can't find any errors with any of the images.. any tips on what I can do to solve this?
The error I get is
2017-11-25 14:44:12.824454+0100 Shoota[56975:18283319] [framework] CUICatalog: Invalid asset name supplied: ''
2017-11-25 14:44:12.824640+0100 Shoota[56975:18283319] Could not load the "" image referenced from a nib in the bundle with identifier "Ctech.Shoota"
2017-11-25 14:44:12.843855+0100 Shoota[56975:18283319] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x7f8e5260ee90> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key birdView.'

I've looked at the source code of the Main.storyboard and for the relevant ViewController. I found these image references... Can this be the source of error?
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" image="imageView:4hW-wf-T7e:image" translatesAutoresizingMaskIntoConstraints="NO" id="4hW-wf-T7e">
   <rect key="frame" x="0.0" y="140" width="349" height="1"/>
      <constraints>
          <constraint firstAttribute="height" constant="1" id="m11-ek-CKC"/>
      </constraints>
</imageView>


text:
Q: How Can I call startActivityForResult() from activity and get data inside Fragment? I want to choose contact via Intent. But what I want to do is there is button on Activity through I will startActivityOnResult() and want to get that contact inside the fragment available on the same activity. Is there any way I can do this?
NOTE : I am using ActivityResultLauncher<Intent> because startActivityOnResult() is deprecated.
I have tried to send data through the interface but My mentor didn't think it is the right way to do so and I can't think any other way I can do that


text:
Q: Getting Conversion failed when converting date and/or time from character string just trying to do a COUNT(*) This is a quickie:
I'm confused. This is my SQL:
select COUNT(*) as rowCnt
from fy2015View

It's VERY SIMPLE and yet, DOESN'T WORK!
This is the ERROR I get:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

NO MATTER WHAT I DO, it will not work.
But, if I do that same call on another table, I get the number of rows back.
Now, this fy2015View is just that: A VIEW.
Does that have anything to do with it?
Is there something I needed to do during the creation of the view or something I "shouldn't" have done?
I can't have a long discussion to keep in compliance with Stacks rules... so please a quick answer would be best.

A: As I mentioned in my comment above, the issue lies in the view's definition.
Without knowing how that view is defined, we can't give you a simple answer, and the reason why COUNT(*) fails, is because the number of records of a view that runs into execution errors is undefined.
I created a sample sqlfiddle to show why this would occur.


text:
Q: How to remove strings with numbers and special characters using regular expression Remove strings with numbers and special characters using regular expression.Here is my code
  var string = "[Account0].&[1]+[Account1].&[2]+[Account2].&[3]+[Account3].&[4]";
    var numbers = string.match(/(\d+)/gi);
    alert(numbers.join(','));

here output is : 0,1,1,2,2,3,3,4
But i want the following output  1,2,3,4
Can any one please help me.
Thanks,

A: Seemd what you want is [\d+], use exec like this,
var myRe = /\[(\d+)\]/gi;

var myArray, numbers = [];

while ((myArray = myRe.exec(string)) !== null) {
    numbers.push(myArray[1]);
}

http://jsfiddle.net/xE265/

A: You can do:
string = "[Account0].&[1]+[Account1].&[2]+[Account2].&[3]+[Account3].&[4]";
repl = string.replace(/.*?\[(\d+)\][^\[]*/g, function($0, $1) { return $1 });
//=> "1234"

A: I guess the simplest solution in this case would be:
\[(\d+)\]

simply saying that you only want the digits enclosed by brackets.
Regards


text:
Q: close the loop in .htaccess for redirecting all subfolders to root I am trying to redirect all subfolders to the root page using .htaccess. i.e. I'd like to redirect example.com/audio, example.com/video, example.com/images to example.com using below settings: However, I'd like to make it independent from the domain name. Hence, you don't see 'example.com' in my .htaccess setting.
RewriteEngine On
RewriteRule  ^([^/]+)(.*)$  / [R]

When I test it, my browser gives me "redirected you too many times error message" error message. I have checked the apache logs and it shows that the request has been redirected so many times. I assume when htaccess redirects us to the root the above lines in .htaccess get run again and therefore it makes a loop. Is there any way I can force htaccess to redirect only those URL with subdirectory ?

A: You can try this rule:
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^.+$ / [R=301]

With this rule, everything will be redirected to the root except the root itself.


text:
Q: pendrive recovery that damaged while installing linux I tried to intall linux mint in my hp v165w pendrive.After I partition the device,I clicked on the "next" to install linux.in progress bar after 80% completion the progress stops and cancelled.after that  the pendrive is not showing in any pcs or laptops. I tried to open it in linux os as well in windows os also. but the problem is same.please tell me how to repair the pendrive again.
thank you

A: In Windows, go to Disk Management (Right-click on My Computer and then on Manage) on any computer whilst the pen drive is plugged in and check if it shows up in there.
If not, go to the Device Manager from the Control Panel, right-click on the Disk Drives node and select Scan for Hardware Changes if the device isn't in the listing. After clicking on Scan for Hardware Changes, if the USB device appears, it should also appear in Disk Management. You should then be able to format the pen driver from Disk Management.


text:
Q: Created Blazor server side project with SSL, how do I switch to non-SSL? I created a new Blazor server-side project with SSL but I experience some trouble and would like to fall back to non-SSL version. This is the error message that i get in the browser console:
Failed to load resource: net::ERR_CERT_AUTHORITY_INVALID
I also cannot connec to my database, which worked fine with all my other projects. I'd like to eliminate a possible relationship between the SSL setting and the errors.
I removed the app.UseHttpsRedirection(); statement in Program.cs but the errors remain. Is there anything else I can do? I'm on VS 2022 with .Net 6 RC2. In vs 2019 there was a flag which I could set in the project properties but I can't find that in 2022.

A: I found the SSL option in the menu. They have changed it from VS 2019 to 2022 and it was hard to discover it.


text:
Q: Ranges in for loop off by 1? I'm working through the book automating the boring stuff with python and came across this code he wrote to find phone numbers within a document.
The format of phone numbers is (12 characters): 123-456-7890
Why does the code check if length of text is 12? but doesn't python count from 0 and so it'll look for a length of 13?
Similarly,
he wants to check if the first three digits are numbers but he uses a range(0, 3). Doesn't this check the first 4 digits including a hyphen which is not a number?
Thanks for the help.
def isPhoneNumber(text):
    if len(text) != 12:
        return False
    for i in range(0, 3):
        if not text[i].isdecimal():
            return False
    if text[3] != '-':
        return False
    for i in range(4, 7):
        if not text[i].isdecimal():
            return False
    if text[7] != '-':
        return False
    for i in range(8, 12):
        if not text[i].isdecimal():
           return False
    return True

A: len() returns the actual length of the string. Think of it, a string with length 0 ("") also exists.
The last value of range(start, end) is end-1. The number 2 is in the range of 1-3 and the number 3 in the range of 3-5. Inclusive bottom and exclusive upper bound.

A: It's best to separate the concepts of indexes (the positions of objects in a list) and length (how many there are). Here's the doc of len(s) in Python.
range(start, stop) in Python includes the start and excludes the stop parameter. In mathematical notation, [start, stop). Therefore range(0,3) will check 0, 1, 2.

A: The len function returns the number of objects in a list.
i.e.
>>> len([1, 2, 3])
3

range(0, 3) produces 0, 1, 2 and hence only checks the first three numbers.
>>> for i in range(0, 3):
...     print(i)
...
0
1
2

A: You're getting list indexing, the len function, and the range function confused.
List indexing starts at 0 and increases for each element. The 13th element in a list is at index 12, and would be accessed with text[12].
The len function, on the other hand, returns the actual length of the list. The length of a 2-element is, of course, 2, and that's what len would return. In your example, the text is 13 characters long. len returns 13, but the last index of the text would be at text[12].
The range function is inclusive of the starting value and exclusive of the ending value. In your example of range(0, 3), it checks the items at locations 0, 1, and 2, not 0, 1, 2, and 3. If you want to check the first four numbers, use range(0, 4) instead, which will check the elements at list indexes 0, 1, 2, and 3, which are also the first, second, third, and fourth elements in the string.


text:
Q: How to fix one letter typos? I found some questions and answers where one of the relevant words
contains a typo. (In my case the user wrote 'QlickView' instead of 'Qlikview'.)
I would like to change (edit) these questions and answers, so that the search finds them. But it is not possible to save one letter changes.
Should I flag these questions and answers or is there a better way to improve?

A: You don't. Leave those to people with 2k+ rep.
The suggested edit system is intended for substantial edits only. If you cannot find more things to fix, leave the typo be.


text:
Q: Python,как сделать перечисление массива,если это определенный элемент списка Есть код и условная переменная SomeString ,которая принимает 2 значения.
Как сделать,что если SomeString принимает Apple,то перечислит элементы нужного списка?
Apl = []
Melon = []
Apl.append('Зеленый')
Apl.append('Кислый')
Melon.append('Большой')
Melon.append('Сладкий')
SomeArr = { 'Apple': Apl, 'Melon': Melon }

A: Проверьте оператором in, что такой ключ есть в словаре и выведите значение по ключу:
apls = ['Зеленый', 'Кислый']
melons = ['Большой', 'Сладкий']
my_dict = { 'Apple': Apl, 'Melon': Melon }

some_string = input()
if some_string in my_dict:
    print(my_dict[some_string])


text:
Q: Google Drive API change current user's permission from writer to reader I'm trying to transfer ownership of a file to someone else and change my own permission to read only. What is the correct way to use permission api?  I have tried both patch and update and neither seems to work.
The way I did it:

*

*Getting permissionId from getIdForEmail

*In the patch body I have {'role': 'reader'} as body but I keep getting 400 error.

Permission 'delete' does work but I need the user to retain reader permission.
Also, is 'me' a valid permissionId?

A: I was able to achieve this using the following method:

*

*While still owning the file, make sure writersCanShare is true (otherwise you'll transfer ownership, become a writer and be unable to change permissions after that).

*Retrieve the current permissions of the file with permissions.list(). You can note the permissionId for yourself here.

*If the desired new owner already has rights to the file, perform a permissions.patch() to make them an owner. If they don't already have explicit rights to the file, perform a permissions.insert() to make them the owner.

*Now as a writer you can perform a permissions.patch() using your permissionId and setting the role to reader.

*Note that after this, calls to permissions.list() will only return the file owner, because readers like yourself can't see the full file permissions.
'me' does not seem to work as a permissionId.


text:
Q: No repository for "ENTITY" found in "XXX" Connection [TypeORM] I have Settings Module with attendance_record_options subservice.
I am calling routes in settingsController , from there I am calling settingsService which contains object of AttendanceRecordOptionsService (interacts with AttendanceRecordOptionsRepository and saves data in Postgress Database)
Folder Structure :

SettingsModule
Module({
  imports: [],
  controllers: [SettingsController],
  providers: [
    {
      provide: getRepositoryToken(AttendanceRecordOptions),
      inject: [TENANT_CONNECTION],
      scope: Scope.REQUEST,
      useFactory: connection => connection.getRepository(AttendanceRecordOptions),
    },
    SettingsService,
    AttendanceRecordOptionsService,
  ],
  exports: [SettingsService],
})

This runs fine without error but when I call any route regarding AttendanceRecordOptions, It gives me error No repository for "AttendanceRecordOptions" was found. Looks like this entity is not registered in current "tenant2" connection?
when I creates an object with hardcoded values like below in Migration file and saves it, all routes start working and I can store data using routs in controller.
const attendance_record_options_repository = queryRunner.manager.getRepository(AttendanceRecordOptions)
const aro =  new AttendanceRecordOptions()
aro.name = 'name'
aro.prefix = 'pre'
aro.shortName = 'short'
aro.description = ' description'
aro.type = 'bool'
await attendance_record_options_repository.save(aro)

Why am I getting this behavior from NestJS and TypeORM ?


text: Q: Finding the span of this mapping in P2 I have managed to do 10 a&b but im stuck on part C, i understand i have to form a span using Po +P1x+P2x^2 but im not sure what to do next, i have an exam later this week and I have also looked through my notes and tried finding a similar answer online but no luck. Much help would be appreciated.


text:
Q: Perl - DBI and .pgpass I can successfully create a connection to a Postgres db using the following:
my $settings = {
    host => 'myhost',
    db => 'mydb',
    user => 'myuser',
    passwd => 'mypasswd'
};

my $connection = DBI->connect(
    'DBI:Pg:dbname=' . $settings->{'db'} . ';host=' . $settings->{'host'},
    $settings->{'user'},
    $settings->{'passwd'},
    {
        RaiseError => 1,
        ShowErrorStatement => 0,
        AutoCommit => 0
    }
) or die DBI->errstr;

But I'm left with valuable login credentials exposed (yes, I changed them) in my Perl module. Currently, I use psql to issue queries interactively. And to save on having to remember my username/password, I have placed the credentials in a file (~/.pgpass) with permissions 600. The file looks like this:
# host:port:database:user:passwd
myhost:5432:mydb:myuser:mypasswd

How can I safely use this file ("$ENV{HOME}/.pgpass") and the DBI module to hide my credentials? Can it be done? What is best practice?

A: *

*Put your login credentials in a file called ~/.pgpass as per the question above.

*To open a connection, you'll need to hard-code in the host, database and username. But that's ok, because at least you don't need to code in the password field. This field stays hidden in your ~/.pgpass file.

*Make sure to set the connection instance's password field to undef.
Here's what worked for me:
my $settings = {
    host => 'myhost',
    db => 'mydb',
    user => 'myuser'
};

my $connection = DBI->connect(
    'DBI:Pg:dbname=' . $settings->{'db'} . ';host=' . $settings->{'host'},
    $settings->{'user'},
    undef,
    {
        RaiseError => 1,
        ShowErrorStatement => 0,
        AutoCommit => 0
    }
) or die DBI->errstr;

The connections establishes successfully because for some reason, unknown to me at least, the instance searches the ~/.pgpass file when attempting the connection. I knew there was some magic with this file, I was just unsure about what to do with it. Doc link:
http://search.cpan.org/dist/DBI/DBI.pm#data_string_diff
Notice how a search for "pgpass" on that page does not return? And I refuse to read all of it. Well, one day maybe..

A: YES! There IS a better way.
Change between test & live servers easily.

*

*keep passwords in ~/.pgpass (for psql & pg_dump)

*other config info in ~/.pg_service.conf (or /etc/pg_service.conf)

e.g:
#!/usr/bin/perl -T
use strict;
use warnings;
use DBI;

my $dbh = DBI->connect
(
    #"dbi:Pg:service=live",
    "dbi:Pg:service=test",
    undef,
    undef,
    {
        AutoCommit => 0,
        RaiseError => 1,
        PrintError => 0
    }
) or die DBI->errstr;

~/.pg_service.conf:
# http://www.postgresql.org/docs/9.2/static/libpq-pgservice.html
# /usr/local/share/postgresql/pg_service.conf.sample
# http://search.cpan.org/dist/DBD-Pg/Pg.pm
#

[test]
dbname=hotapp_test
user=hotusr_test
# localhost, no TCP nonsense needed:
host=/tmp

[live]
dbname=hotapp_live
user=hotusr_live
host=pgsql-server.example.org

~/.pgpass:
# http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html
# hostname:port:database:username:password
localhost:5432:hotapp_test:hotusr_test:kq[O2Px7=g1
pgsql-server.example.org:5432:hotapp_live:hotusr_live:Unm£a7D(H

A: open(my $fh, '<', "$ENV{HOME}/.pgpass") or die $!;

my $settings;
while (<>) {
   chomp;
   next if /^\s*(?:#.*)?\z/s;
   @{$settings}{qw( host port database user passwd )} = split /:/;
}

die "No settings" if !$settings;

Any user capable of running the script would still be able to see the creds.


text:
Q: Discord.py bot not sending messages in a discord server but sends messages in DM's I have a discord.py bot that when the command is sent through DM, it works. When the command is ran through a server, nothing happens. There is no errors or tracebacks. Here is my code so far.
import discord
from discord.ext import commands

bot = discord.Bot()

TOKEN = "MyToken"

bot = commands.Bot(command_prefix="$")

@bot.command()
async def test(ctx, arg):
    await ctx.send(arg)

bot.run(TOKEN)

I don't know whats happening. I gave it the right permissions but it still wont do anything.

A: So, I don't know for sure if this is the issue, but try this:
I have my bot set as:
bot = commands.Bot(command_prefix= '$', description="<desc>")

Rather than yours which is BOTH of these:
bot = discord.Bot()

&
bot = commands.Bot(command_prefix="$")

I think it's only detecting the first value you've given your bot.


text:
Q: Finding an Input Value in a List The question from my homework is:

Write python statements that create a list which holds ten integers, and fill each slot with a different random value from 1-50. Display those values on the screen, and then get an integer from the user, search through the array, if the item exists in the list, then give the index number where it is located. If the value is not in the array, display a single message saying so.

So obviously I'm not asking the whole question on what to do it but I have tried many things and I still couldn't solve the problem that is occurring.
import random

random_list = random.sample(range(1, 50), 10)

print("Your generated random list: ", random_list)

entered_num = int(input("Value to find: "))

for a in random_list:
    if a == entered_num:
        print(a, "is in index", random_list.index(a))
    if a != entered_num:
        print(entered_num, "is not in the list.")

The output:

Your generated random list:  [12, 34, 24, 47, 36, 49, 16, 5, 13, 1]
Value to find: 24
24 is not in the list.
24 is not in the list.
24 is in index 2
24 is not in the list.
24 is not in the list.
24 is not in the list.
24 is not in the list.
24 is not in the list.
24 is not in the list.
24 is not in the list.

So the problem is I don't understand why it prints out "24 is not in the list." 9 times with also one "24 is in index 2" (maybe its happening because of the random.sample generation I really don't know). I am lost here right now, I would love some help. I know this might be a stupid and an easy question for you but I'm still a beginner student in Python, although I am ready for all sort of criticism.
Note: I am using Wing Personal 7.2

A: You were almost there, the only thing is first of all the for loop is going over each element in the list and since you have the condition a != which prints every time the answer was not equal to a. and even after getting the answer you were still inside the loop and therefore you needed to break from it.
import random

random_list = random.sample(range(1, 50), 10)

print("Your generated random list: ", random_list)

entered_num = int(input("Value to find: "))

for a in random_list:
    if a == entered_num:
        print(a, "is in index", random_list.index(a))
        break
else:
        print(entered_num, "is not in the list.")

A: The code is as follows:
import random

random_list = random.sample(range(1, 50), 10)

print("Your generated random list: ", random_list)

entered_num = int(input("Value to find: "))

if entered_num in random_list:
    print(entered_num, "is in the list, index:", random_list.index(entered_num))
else:
    print(entered_num, "is not in the list")

The thing being, in your case, you print everytime you make a comparison. But, you have to only print when you find it :)


text:
Q: Docker: Import table.sql to mydatabase I want to import a table.sql to a created database inside mysql container.
This is the Dockerfile looks like
 FROM eccube/mysql51
 Maintainer Marouane baini <username@email.com>
 LABEL version="1.0"
 LABEL description="DB FOR TOMCAT SERVER"
 RUN mkdir /root/mysql
 COPY mytable.sql /root/mysql/

To run the container:
docker run --name=mysql-host  -e MYSQL_ROOT_PASSWORD=root -d mysql-host

Then:
docker exec -i mysql-host mysql -uroot -proot mydatabase < table.sql

I got this result :
ERROR 1146 (42S02) at line 1: Table 'mydatabase.table' doesn't exist

How I can resolve this, is by creating an empty table named table inside t mydatabase ?

A: Since data can't be inserted into a non-existing table, your script should start with a CREATE TABLE command.


text:
Q: How to export a MongoDB database to JSON? It is possible to export a mongodb database to json on windows?
I've already searched and the only thing that I find is to export collections. Is that the only way?

A: Here's an example for a collection
mongoexport --collection=mycollection --db=mydb --out=myoutput.json

Use mongodump for the whole database
mongodump -d mydb -o output.json


text:
Q: Finding the zero-state response I understand the zero state response can be found by finding the homogeneous and particular solution. I am analyzing this circuit.

My input is $$Vin(t) = e^(-2t) * u(t)$$
I set the Vout to 0. So for the homogeneous equation I have $$0 = \frac{-4}{i} * \frac{dv(t)}{dt} + v(t), t< 0$$
And for the particular solution I have $$1 = \frac{-4}{i} * \frac{dv(t)}{dt} + v(t), t > 0$$ However, given all this, how do I proceed? Also, is there a simpler way of doing this for more complicated circuits? For instance, if the resistor and capacitor positions were switched or if I had a really complicated transfer function.

A: \$i=C\dfrac{dv_o}{dt}\$, and Ohm's Law gives: \$v_i - v_o=RC\dfrac{dv_o}{dt}\$
This can be solved by the integrating factor method, and zero state means zero initial conditions, therefore take \$v_o(0)=0\$
For higher order (>2) circuits you'll need the Laplace Transform.


text:
Q: Can't parse date with zone information using SimpleDateFormat I have
format: dd-MM-yyyy'T'HH:mm:sszzz
locale: en_US
date: 01-02-2016T10:00:00+01:00
zoneId: Europe/Warsaw
and I call:
new SimpleDateFormat(format, locale).parse(date).toInstant().atZone(zoneId)
and I get Unparseable date: "01-02-2016T10:00:00+01:00"
Is there any option to use SimpleDateFormat or do I need to change it to something else?

A: To match "01-02-2016T10:00:00+01:00", your format string should be "dd-MM-yyyy'T'HH:mm:ssXXX".  You have zzz where you should have XXX.  See the javadoc.
Also, this is quite a strange format to use.  Usually, when one sees the T separator between date and time parts, it indicates the ISO8601 format (or an ISO8601-based format such as RFC3339).  However, in that format, the date is in year-month-day order.  You have day-month-year order.  This contradiction will surely cause confusion at some point.  I highly recommend changing the source of this data to either use the correct ordering, or replace the T with a space, and place a space before the tz offset as well.
In other words, your data should look like:
"01-02-2016 10:00:00 +01:00"  // Human-readable, but locale-specfic

or
"2016-02-01T10:00:00+01:00"   // ISO8601 / RFC3339 compliant

NOT
"01-02-2016T10:00:00+01:00"   // Nonsense


text:
Q: Strange Spring behavior on Jetty when spring.jar is in WEB-INF/lib/ instead of classpath I'm running Eclipse with the run-jetty-run plugin to launch my J2EE web apps. My project uses Spring, and the spring configuration uses things like HttpInvokerProxy and properties placeholder.

*

*When the spring jars are on the classpath (I mean configured in the "classpath" tab of the "run configuration") and external (not in WEB-INF/lib), everything works fine.

*But when I place spring.jar (or all spring jars) in the WEB-INF/lib/ directory (+referenced in the classpath), the trouble starts. I tried with both values of Jetty's parentLoaderPriority:

*

*when parentLoaderPriority is true, I get a complaint of Xerces saying it can't validate the spring.xml's XSD (so I guess Jetty's embedded different version of xerces conflicting with mine)

*when parentLoaderPriority is false, the property placeholder doesn't work anymore and (I tried replacing with the direct values) Spring also fails to convert the HttpInvokerProxy into the correct interface, like some classes are missing

*Finally, when I leave all my jars in WEB-INF/lib and remove the matching classpath entries, it can't find the classes: I get a ClassDefNotFoundException com/google/common/collect/Lists although google-collections.jar is in WEB-INF/lib and contains the class file... This with both values of parentLoaderPriority.

Method #3 works fine in Tomcat, though. So I guess this jetty launcher has some classloading configuration I'm doing wrong ?

A: It sounds like your application is using something on the 'external' classpath (I'll call it X) and passing it a reference; this works just fine because 'external' is in a parent classloader to your application.
'X' then uses the reference to do something with spring.  However, spring is on your app's classpath, but X is on the external classpath.  Spring is therefore not visible to X, hence the error.
As you discovered, putting spring into the external classpath is a valid workaround.  This should also work if spring is in both the external and web-app classpaths.
As to what 'X' is?  The most likely candidate would be commons-logging, which has a long history of screwing around with classloaders.  You might want to consider using an slf4j implementation instead (like Logback) and provide the commons-logging interface via jcl-over-slf4j
Resources:

*

*http://articles.qos.ch/classloader.html

*http://day-to-day-stuff.blogspot.com/2007/10/announcement-version-99-does-not-exist.html

*http://www.slf4j.org/manual.html

*http://logback.qos.ch/


text:
Q: Remove quota from yaml I'm ugins js-yaml to transformt this code
        let coor = `[ ${x}, ${y}, 0 ]`;

        rooms.push( {
            ...
            coordinates: coor,
            ...
        } );

I would wirte
  coordinates: [ 1, 2, 0 ]

But what I got now is the string with quotas:
"[ 7, 3, 0 ]"
This is how I write the file
fs.writeFileSync( `${id}.yml`, yaml.safeDump( rooms ), 'utf8', err => {

What kind of option should I do use?

A: You are dumping a string to YAML, that, if written as a plain scalar (i.e. without quotes) would be interpreted as a YAML sequence. To prevent that from happening, you need to have quotes around the string.
In other words: because the first character of your string ([) has special meaning in YAML, the scalar needs to be quoted.
There is no way around this when you dump a string a string as you do. You can of course dump an array in flow-style and then you'll get [ ... ] without quotes, but when dumping a string, you'll be prevented from doing something wrong.


text:
Q: Codeigniter can't fetch all data from database table I am fetching data from mysql database table in codeigniter using following code
 $result = $this->db->get("shipping");
 $data =  $result->result_array();

But returns no data.
When I apply the limit as
$this->db->get("shipping",1,30)

The code works.
But I want to fetch all result and not by limiting it.
Could anyone please let me know how do I resolve this issue.
Thanks in advance.

A: have you tried using query rather than get?
     $sql = "
        SELECT
            *
        FROM
            shipping
    ";

    $query = $this->db->query($sql);
    $data = $query->result();

A: You have not put a return
https://www.codeigniter.com/user_guide/database/results.html
// This will get every result from shipping
public function somefunction() {
  $result = $this->db->get("shipping");
  return $result->result_array();
}

Controller function
public function somecontrollerfunction() {

    $this->load->model('some_model');

    $data['shipping'] = array();

    $data['shipping'] = $this->some_model->somefunction();

    // var_dump($data['shipping']);

    $this->load->view('your_view', $data);

}


text:
Q: Not able to get value in input field based on the dropdown selection in bootstrap 3

   <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select the type

   </button>

         API

         SOCKET

<form>

      Name:
      IP Address:
      <input type="text" class="form-control" placeholder="IpAddress" id="usr" name="api">

      Network Name
      Network Name
      <input type="text" class="form-control" placeholder="Network Name" id="usr" name="socket">

</form>

in main.js file:
$(document).ready(function() {
  $(".select-div").on("change", "select", function(e) {
    //use on to delegate
    var v = $(e.target).val(),
      t = $(e.target)
        .find(":selected")
        .text(),
      p = $(e.target).closest(".select-div");
    console.log(v);
    var socketUrl = "http://localhost:8081/api/admin/connect";
    var endPointUrl = "http://localhost:8081/api/admin/endpoint";
    if (v) {
      var c = (function(t) {
        switch (t) {
          case "api":
            return endPointUrl;
          case "socket":
            return socketUrl;
        }
      })(t);
      p.find('[name="api"]').val(c);
      p.find('[name="socket"]').val("None");
    }
  });
});

So, when i select the option from the dropdown it does not populate on the input fields at all .I have tried using document.getElementById also but it is of no use .Where I am going wrong ?

A: Your select-div is not the select element so that change event not worked on it, You can do like this :

$(document).ready(function() {
  $(".dropdown-menu li a").click(function() {
    //use on to delegate
    var v = $(this).text();
    var socketUrl = "http://localhost:8081/api/admin/connect";
    var endPointUrl = "http://localhost:8081/api/admin/endpoint";
    if (v) {
      var c = '';
      switch (v) {
        case "API":
          c = endPointUrl;
          break;
        case "SOCKET":
          c = socketUrl;
          break;
      }
      $('[name="api"]').val(c);
      $('[name="socket"]').val("None");
    }
  });
});

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

   <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select the type

   </button>

         API

         SOCKET

<form>

      Name:
      IP Address:
      <input type="text" class="form-control" placeholder="IpAddress" id="usr" name="api">

      Network Name
      Network Name
      <input type="text" class="form-control" placeholder="Network Name" id="usr" name="socket">

</form>


text:
Q: How to split and join message for crypto?

The encrypt and decrypt althorithm often come with a "base-number" value, such as Caesar (N = 26), Elgamal(N is prime). And if a message value is greater than N, we must split it.
A simple example:
E(m) = m + 1 = c (mod 1009) => D(c) = c - 1 = m (mod 1009)

with
m = `"buazyhv"` = `546999123` (base-26 to base-10)

To avoid loss data (with modulo), I split to block of 3 digit:
M = (546)(999)(123) = m1m2m3

Now, encrypt each block
546 -> E -> 547
999 -> E -> 1000
123 -> E -> 124

Then we join it:
C = `5471000124` = "rsmetls"

For decryption, we do the same:
5 -> D -> 4
471 -> D -> 470
000 -> D -> 999
124 -> D -> 123

And we have the decypt message M = 4470999123 = "omhwyat". So, my split and join message approach is not correct.
With another encrypt function like ElGamal (like c = 980*m (mod 1009))
139 -> 980 * 139 = 5 (mod 1009) -> 005 (fill to 3 digit)
696 -> 980 * 696 = 1005 (mod 1009) -> 1005

So, if we found m[i] == "005", we can't predict that it previous encrypt block is "005" or "1005".
How can we encode/decode the ciphertext correctly in Java?

A: A solution would be:
After encryption:

*

*Split message to block of 3 (digit);

*fill up to 4 digit of encrypted block.

Before decryption:

*

*Split encrypted message to block of 4;

*fill up to 3 digit of decrypted block.

But with this solution, it can gain a unnecessary '0' digit in the encrypted message if all encrypted block have only 3 digits...

A: The problem with these basic ciphers is that they are not defined to handle lots of (binary) data. Modern ciphers simply store binary, and they are combined with modes of operation and padding modes to  handle data of almost arbitrary length. Furthermore, asymmetric ciphers are almost always used in a hybrid cryptosystem, which let them handle arbitrary sizes data as well.
A Caesar cipher is a shift cipher that is defined on an alphabet. The simples and historically correct method of applying it is by specifying the ciphertext within the same alphabet. You should not represent it using numbers at all.
For ElGamal it is possible to use any method of encoding a set of numbers, as long as the method is able to distinguish the numbers. Using left padded numbers as suggested is just one way. It is also possible to encode them as fixed sized binary (this is what e.g. RSA uses, see the PKCS#1 specifications).
As text, probably the easiest way is to simply use a separator character and possibly white space for readability. Then you can simply use String.split(",\\s*") to retrieve the numbers. To make life easier, you can use AbstractCollection.toString() for lists, or Arrays.toString(int[]) for arrays (beware of the extra brackets). This is probably best for the toy ciphers as described here.
Example encoding/decoding:
public class ToyCiphertextCodec {
    private ToyCiphertextCodec() {
        // nothin' to do here
    }

    public static ToyCiphertextCodec getInstance() {
        return new ToyCiphertextCodec();
    }

    public String encode(int[] ciphertext) {
        // this is relatively lazy, probably better off creating the
        // encoding yourself if you are using this "in the field"
        return Arrays.toString(ciphertext);
    }

    public int[] decode(String encodedCiphertext) {
        if (!encodedCiphertext.startsWith("[") || !encodedCiphertext.endsWith("]")) {
            throw new IllegalArgumentException("Ciphertext encoding invalid");
        }
        String encodedCiphertextWithoutBrackets = encodedCiphertext.substring(1, encodedCiphertext.length() - 1);
        String[] numbers = encodedCiphertextWithoutBrackets.split(", ");
        int[] intermediateResult = new int[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            intermediateResult[i] = Integer.parseInt(numbers[i]);
        }
        return intermediateResult;
    }

    public static void main(String[] args) {
        ToyCiphertextCodec t = ToyCiphertextCodec.getInstance();

        int[] ciphertext = { 1, 2, 3 };
        String encodedCiphertext = t.encode(ciphertext);
        System.out.println(encodedCiphertext);

        int[] decodedCiphertext = t.decode(encodedCiphertext);
        System.out.println(Arrays.equals(ciphertext, decodedCiphertext));
    }
}

and just for fun:
import java.util.Arrays;

public class ToyCiphertextCodecWithModulus {
    private final int sizeOfNumbers;
    private final String staticallySizedNumberFormat;

    private ToyCiphertextCodecWithModulus(int sizeOfNumbers) {
        this.sizeOfNumbers = sizeOfNumbers;
        this.staticallySizedNumberFormat = "%0" + sizeOfNumbers + "d";
    }

    public static ToyCiphertextCodecWithModulus getInstanceForModulus(int n) {
        int largestNumberOfDigits = String.valueOf(n - 1).length();
        return new ToyCiphertextCodecWithModulus(largestNumberOfDigits);
    }

    public String encode(int[] ciphertext) {
        StringBuilder sb = new StringBuilder(ciphertext.length * sizeOfNumbers);
        for (int i = 0; i < ciphertext.length; i++) {
            sb.append(String.format(staticallySizedNumberFormat, ciphertext[i]));
        }
        return sb.toString();
    }

    public int[] decode(String encodedCiphertext) {
        if (encodedCiphertext.length() % sizeOfNumbers != 0) {
            throw new IllegalArgumentException("Ciphertext encoding invalid");
        }

        int numbers = encodedCiphertext.length() / sizeOfNumbers;
        int[] intermediateResult = new int[numbers];
        for (int i = 0; i < numbers; i++) {
            String number = encodedCiphertext.substring(i * sizeOfNumbers, (i + 1) * sizeOfNumbers);
            intermediateResult[i] = Integer.parseInt(number);
        }
        return intermediateResult;
    }

    public static void main(String[] args) {
        ToyCiphertextCodecWithModulus t = ToyCiphertextCodecWithModulus.getInstanceForModulus(997);

        int[] ciphertext = { 1, 2, 3 };
        String encodedCiphertext = t.encode(ciphertext);
        System.out.println(encodedCiphertext);

        int[] decodedCiphertext = t.decode(encodedCiphertext);
        System.out.println(Arrays.equals(ciphertext, decodedCiphertext));
    }
}


text:
Q: How do I use OCIServerVersion (Oracle) from a C program? FYI: This code is part of an opensource LabView LLB/library/DLL for DB access
My code segment is as follows:
#ifdef HAVE_ORACLE
    case oracle_api:
        sprintf(DriverName, "%s\nOracle ", SQL_LV_VERSION);
        retCode = OCIServerVersion (db->srvhp, db->errhp, DriverName + strlen(DriverName), BUFF_SIZE - strlen(DriverName), 0);
        checkerr(db->errhp, retCode, DriverName + strlen(DriverName));
        break;
#endif

The problem is I keep getting, "OCI_INVALID_HANDLE".
From GDB:
(gdb) print retCode
$1 = -2
(gdb) print DriverName
$2 = "sql_LV-1.10\nOracle Error - OCI_INVALID_HANDLE\n\000
(gdb) whatis db->srvhp
type = OCIServer *

And my typedef is:
/* Typedefs */
typedef struct {
    MYSQL mysql;
    MYSQL_RES *query_results;
#ifdef HAVE_ODBC
    HENV henv;
    HDBC hdbc;
    HSTMT hstmt;
#endif
#ifdef HAVE_ORACLE
    OCIEnv *envhp;
    OCIError *errhp;
    OCISession *authp;
    OCIServer *srvhp;
    OCISvcCtx *svchp;
#endif
    unsigned short int odbc_driver, db_type;
    } SQL_LV_REF;

I'd tried both the service context handle and the server context handle (which are both non-NULL).
And I've been able to use the open connection to successfully "SELECT" data in separate DLL calls.
In response to the question, what does OCIServerAttach look like?
#ifdef HAVE_ORACLE
case oracle_api:
    sprintf(EasyConnect, "%s:%d/%s", host, (port==0) ? 1521: port, db_nm);
    retCode = OCIEnvCreate((OCIEnv **) &db_ref->envhp, (ub4) OCI_DEFAULT,
                (dvoid *) 0, (dvoid * (*)(dvoid *,size_t)) 0,
                (dvoid * (*)(dvoid *, dvoid *, size_t)) 0,
                (void (*)(dvoid *, dvoid *)) 0, (size_t) 0, (dvoid **) 0);

        if (retCode != 0) {
            (void) sprintf(debug_str, "OCIEnvCreate failed with retCode = %d.\n", retCode);
            LV_str_cp(debug, debug_str); return(-1);}

        (void) OCIHandleAlloc( (dvoid *) db_ref->envhp, (dvoid **) &db_ref->errhp, OCI_HTYPE_ERROR,
                (size_t) 0, (dvoid **) 0);   /* server contexts */
        (void) OCIHandleAlloc( (dvoid *) db_ref->envhp, (dvoid **) &db_ref->srvhp, OCI_HTYPE_SERVER,
                        (size_t) 0, (dvoid **) 0);
        (void) OCIHandleAlloc( (dvoid *) db_ref->envhp, (dvoid **) &db_ref->svchp, OCI_HTYPE_SVCCTX,
                        (size_t) 0, (dvoid **) 0);
        retCode =  OCIServerAttach( db_ref->srvhp, db_ref->errhp, (text *) EasyConnect,    /* Connect to the target */
                                    strlen((const char *) EasyConnect), 0);

A: I found a work-around for the issue, namely, since queries are working, I can use:
SELECT Banner FROM v$version WHERE Banner LIKE 'Oracle%'

To obtain server information (as follows):
Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production

I still would like to see examples of how to use OCIServerRelease and OCIServerVersion. I think it's important to note that Oracle provided no help or support, they did reach out to sell a service contract though.

A: I know this is an old post but since this question/answer comes up on google search, answering it for the people who comes after me :) There is really no magic in OCI APIs- you use the same technique in almost all APIs. All you need to do to get the oracle server version is the following
sword rc;
char sver[1024];

if((rc = OCIServerVersion(_service, _error, (text*) sver, (ub4) sizeof(sver), (ub1) OCI_HTYPE_SVCCTX)) != OCI_SUCCESS)
    throw "OCIServerVersion";

std::cout<<"database version:"<<sver;

Here
OCISvcCtx *_service;
OCIError *_error;

You just need to make sure the connections are made correctly to get the server version before calling the API.


text:
Q: Python Merge columns from multiple data frames into a single dataframe I'm merging 5 files. Each file has certain column names which are same across the other files. I used this answer to perform the concat operation. There is one column which is unique in all files i.e ID. When I merge the columns I'm noticing the suffix(_x, _y) being applied to end of the column names(due to merge functionality) which are repeating. How can I merge these columns into a single column (Irrespective of null values).
eg:
Dataframe 1
ID    Name    Age    LAN_NBR
1     ABC     24     G284992

Dataframe 2
ID    Name    Street     City     State    TYPE
2     John    Wacker     Chicago  IL       HUB

Dataframe 3
ID    CLOSE_DATE    TYPE
3     1/1/2021      HUB

Dataframe 4
ID    TYPE    LAN_NBR
1     HUB     G284992

Expected Output
ID    Name    Age    LAN_NBR    Street     City     State    TYPE    CLOSE_DATE
1     ABC     24     G284992                                 HUB
2     John                      Wacker     Chicago  IL       HUB
3                                                            HUB     1/1/2021

Code
obj1=pd.read_excel("file1.xlsx")
obj2=pd.read_excel("file2.xlsx")
obj3=pd.read_excel("file3.xlsx")
obj4=pd.read_excel("file4.xlsx")
obj5=pd.read_excel("file5.xlsx")

obj1_ID=pd.DataFrame(obj1["ID"])
obj2_ID=pd.DataFrame(obj2["ID"])
obj3_ID=pd.DataFrame(obj3["ID"])
obj4_ID=pd.DataFrame(obj4["ID"])
obj5_ID=pd.DataFrame(obj5["ID"])

concat_pd=[obj1_ID,obj2_ID,obj3_ID,obj4_ID,obj5_ID]
obj_final=pd.concat(concat_pd).fillna('')

obj_final.obj_final.drop_duplicates(subset='ID',keep='first')

merge1=pd.merge(left=obj_final, right=obj1, on="ID", how="left")
merge1=pd.merge(left=obj_final, right=obj2, on="ID", how="left")
merge1=pd.merge(left=obj_final, right=obj3, on="ID", how="left")
merge1=pd.merge(left=obj_final, right=obj4, on="ID", how="left")
merge1=pd.merge(left=obj_final, right=obj5, on="ID", how="left")

A: Option 1: concat and drop_duplicates:
(pd.concat( (df1, df2, df3, df4), sort=False)
   .groupby('ID')
   .bfill()
   .drop_duplicates('ID')
   .reset_index(drop=True)
)

Output:
   ID  Name   Age  LAN_NBR  Street     City State TYPE CLOSE_DATE
0   1   ABC  24.0  G284992     NaN      NaN   NaN  HUB        NaN
1   2  John   NaN      NaN  Wacker  Chicago    IL  HUB        NaN
2   3   NaN   NaN      NaN     NaN      NaN   NaN  HUB   1/1/2021

Option 2: use combine_first as @ansev suggested:
ret_df = pd.DataFrame()

for d in (df1, df2, df3, df4):
    ret_df = ret_df.combine_first(d.set_index('ID') )

ret_df = ret_df.reset_index()

Output:
   ID   Age CLOSE_DATE     City  LAN_NBR  Name State  Street TYPE
0   1  24.0        NaN      NaN  G284992   ABC   NaN     NaN  HUB
1   2   NaN        NaN  Chicago      NaN  John    IL  Wacker  HUB
2   3   NaN   1/1/2021      NaN      NaN   NaN   NaN     NaN  HUB

A: you can use concat and than groupby with first to keep the first non null value available if any per ID.
print (pd.concat([df1, df2, df3, df4]).groupby('ID').first())
    Name   Age  LAN_NBR  Street     City State TYPE CLOSE_DATE
ID
1    ABC  24.0  G284992     NaN      NaN   NaN  HUB        NaN
2   John   NaN      NaN  Wacker  Chicago    IL  HUB        NaN
3    NaN   NaN      NaN     NaN      NaN   NaN  HUB   1/1/2021


text:
Q: how to select and diaplay data from jquery date and time picker I am using a j query date and time picker and cannot seem to display the selected data never mind save to a db. I am using php with mysql and am not sure how to get the information. this is the j query date and time picker and the suggested j query to get the date from the picker:

and my html

Book An Appointment

Date: <input type="text" id="date_picker">

I firstly want to display the returned value to make sure its working before I try and input to db but i cant even get this to work. Any ideas?

A: here is a couple of examples for the jquery datetime picker . datepicker1 datepicker2

A: If you are using jquery datepicker you can load it using the following:
First load necessary javascript and css files for datepicker and then call the datepicker function on the element. (Make sure you include latest jquery)

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

Date: <input type="text" id="datepicker">

A: Here is a better view of the current code:

Book An Appointment

Date: <input type="text" id="date_picker">


text:
Q: Unable to get notification data,body when app is in background or closed in React-native-firebase android Im using react-native-firebase in my app for cloud messanging + notification. it get all body and data when app is in use but it cant get anything when app is closed or in background ....
I tried Headless JS but thats also not working
when i click on notification and when it open's the app its shows this {"google.priority":"high"}
thnaks in advance....
this is my android mainfest
<application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:allowBackup="false"
      android:theme="@style/AppTheme"
      android:largeHeap="true">
      <meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/ic_stat_ic_notification" />
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <!---firebase -->
      <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
    <intent-filter>
      <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
  </service>
  <!-- <meta-data
    android:name="com.google.firebase.messaging.default_notification_channel_id"
    android:value="@string/default_notification_channel_id"/> -->
   <service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
  <!---firebase end-->
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

this is my componentdidmount() function
 async componentDidMount() {
      this.getValueLocally();
      requestCameraLOCATION()

        const notificationOpen: NotificationOpen = await firebase.notifications().getInitialNotification();
        if (notificationOpen) {
            const action = notificationOpen.action;
            const notification: Notification = notificationOpen.notification;
            var seen = [];
            alert(JSON.stringify(notification.data, function(key, val) {
                if (val != null && typeof val == "object") {
                    if (seen.indexOf(val) >= 0) {
                        return;
                    }
                    seen.push(val);
                }
                return val;
            }));
        }
        const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)
                .setDescription('My apps test channel');
// Create the channel
        firebase.notifications().android.createChannel(channel);
        this.notificationDisplayedListener = firebase.notifications().onNotificationDisplayed((notification: Notification) => {
            // Process your notification as required
            // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
        });
        this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
            // Process your notification as required
            notification
                .android.setChannelId('test-channel')
                .android.setSmallIcon('ic_launcher');
            firebase.notifications()
                .displayNotification(notification);

        });
        this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
            // Get the action triggered by the notification being opened
            const action = notificationOpen.action;
            // Get information about the notification that was opened
            const notification: Notification = notificationOpen.notification;
            var seen = [];
            alert(JSON.stringify(notification.data, function(key, val) {
                if (val != null && typeof val == "object") {
                    if (seen.indexOf(val) >= 0) {
                        return;
                    }
                    seen.push(val);
                }
                return val;
            }));
            firebase.notifications().removeDeliveredNotification(notification.notificationId);

        });
    }

              async checkPermission() {
                firebase.messaging().hasPermission()
                .then(enabled => {
                  if (enabled) {
                    this.getToken();
                  } else {
                    this.requestPermission();
                  }
                });}

                  async getToken() {
                    let fcmToken = await AsyncStorage.getItem('fcmToken');
                    if (!fcmToken) {
                      fcmToken = await firebase.messaging().getToken();
                      if (fcmToken) {
                        // user has a device token
                        await AsyncStorage.setItem('fcmToken', fcmToken);
                      }
                    }
                  }
                  async requestPermission() {
                    firebase.messaging().requestPermission()
                    .then(() => {
                      this.getToken();
                    })
                    .catch(error => {
                      console.warn(error);
                    });
                  }

and this is my bgMessaging.js
import firebase from 'react-native-firebase';
import type { RemoteMessage } from 'react-native-firebase';
import type { Notification,NotificationOpen} from 'react-native-firebase';

export default async (message: RemoteMessage) => {

    const newNotification = new firebase.notifications.Notification()
            .android.setChannelId(message.data.channelId)
            .setNotificationId(message.messageId)
            .setTitle(message.data.title)
            .setBody(message.data.body)
            .setSound("default")
            .setData(message.Data)
            .android.setAutoCancel(true)
            .android.setSmallIcon('ic_notification')
            .android.setCategory(firebase.notifications.Android.Category.Alarm)

    // Build a channel
    const channelId = new firebase.notifications.Android.Channel(message.data.channelId, channelName, firebase.notifications.Android.Importance.Max);

    // Create the channel
    firebase.notifications().android.createChannel(channelId);
    firebase.notifications().displayNotification(newNotification)

    return Promise.resolve();

}

A: there are two types of messages:
notification + data messages that will be handled by the FCM while in the background (so your code will not have access to the notification), and will call onNotification while in the foreground,
data-only messages will call headlessjs while in the background/closed and will call onMessage while in the foreground.
note: if you remove the title and body, your message will be categorized as the second one. also, data is optional in the first category.
to recap:
for data-only messages:

*

*App in foreground : onMessage triggered

*App in background/App closed : Background Handler (HeadlessJS)
for notification + data messages:

*

*App in foreground : onNotification triggered

*App in background/App closed : onNotificationOpened triggered if the notification is tapped
for more information and for iOS read the official docs for data-only messages  and notification+data messages

A: It seems that RN firebase did not support this functionality on Android.
Please refer below:
https://rnfirebase.io/docs/v5.x.x/notifications/receiving-notifications#4)-Listen-for-a-Notification-being-opened

On Android, unfortunately there is no way to access the title and body of an opened remote notification. You can use the data part of the remote notification to supply this information if it's required.


text:
Q: Concatenating two lists in an Array, Separated by a Period Here's what I'm trying to do:
Say I have an array:
import numpy as np
a = ([['jon','jan','tom','sam'] , ['Jan', 'Feb', 'Mar', 'Apr'] , ['Red',
'Blu', 'Gre', 'Yel']]);
np.transpose(a);

What I want to do is concatenate columns 1 and 3 in a new 4x1 array, b, so that I get the following output:
   b = ['jon.Red'
         'jan.Blu'
         'tom.Gre'
         'sam.Yel']

What's the best method in python to take columns 1 and 3 and join them, separating the two strings using a period?
Thanks for the help.

A: This will work:
b = ['{}.{}'.format(x, y) for x, _, y in zip(*a)]

String formatting, list comprehension, zip and argument unpacking are used here and concepts worth reading up on.
On a side note, Python does not require semi-colons and the outer parentheses in a = ([...]) are superfluous.

A: You can simply use list comprehension and zip:
>>> [e0 + '.' + e1 for (e0, e1) in zip(a[0], a[2])]
['jon.Red', 'jan.Blu', 'tom.Gre', 'sam.Yel']

A: Also, you can do something like this:
a = ([['jon','jan','tom','sam'] , ['Jan', 'Feb', 'Mar', 'Apr'] , ['Red',
'Blu', 'Gre', 'Yel']])

final = [".".join(k) for k in zip(a[0], a[-1])]
print(final)

Output:
['jon.Red', 'jan.Blu', 'tom.Gre', 'sam.Yel']


text:
Q: Azure Search - return only certain number of words from a field We have a database that stores news stories from many websites.  The entire text of each article is stored in one field of unstructured data as nvarcharmax.  Our clients query on a person's name to see if they appear anywhere in any of our articles.  But in order for us to be compliant with requirements in our industry, as well as not infringe on any copyrights, we're only allowed to return the 25 words which surround that person's name that was queried on.  Along with that we give the client the URL of the article and they can take it from there.
Is this something that can be accomplished in Azure Search?  The ability to only display a subset of words from the field which is being queried on?

A: You can use the hit highlighting feature in Azure Search. Please see highlight= parameter in https://learn.microsoft.com/en-us/rest/api/searchservice/search-documents.
Azure Search returns up to five text fragments, which are usually sentences, that contains the search hits per field. It currently does not allow you to configure the size of the window/fragment so you can't get a specific number of words surrounding the search terms.


text:
Q: SQLite storing, retrieving and comparing a DATETIME field I am really stuck trying to compare dates in SQLite queries in Objective C. Here's what I'm doing:
Storing the date:
This document tells me to use the dateformat specified below, but it doesn't seem right. I tried using yyyy-MM-dd hh:mm:ss without success too though.
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-DD HH:MM:SS"];
NSString *dateString=[dateFormat stringFromDate:today];

NSString *query = [NSString stringWithFormat: @"INSERT INTO user (edited) VALUES (\"%@\")", dateString];

Comparing the date
I am using a timestamp for this, which I convert to a datetime string
long stamp = [sessie integerForKey:@"stamp"];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-DD HH:MM:SS"];
NSString *dateString = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:stamp]];

sqlite3_stmt *result = [db selectQuery:[NSString stringWithFormat:@"SELECT * FROM user WHERE edited > '%@'", dateString]];

The timestamp is simply generated using [[NSDate date] timeIntervalSince1970]. The problem is that the query won't give the correct results, and I don't even know if the date is stored correctly in the first place. Any help would be greatly appreciated!

A: A couple of observations:

*

*For your date string, you do definitely do not want to use YYYY-MM-DD HH:MM:SS. That will not generate a valid date string. Using yyyy-MM-dd hh:mm:ss is much closer, but not quite right, either (since you'll use 12-hour hh). Use yyyy-MM-dd HH:mm:ss instead.

*This date format, though, does not capture time zone, so, if you store date strings in your SQLite database, you should use UTC (GMT) as discussed in the SQLite Date And Time Functions documentation.
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
formatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSString *dateString = [formatter stringFromDate:today];

As shown above, you probably want to also specify the locale so that the format of the dates will not change depending upon the localization settings of the device.

*Note that you might consider using timeIntervalSince1970 to store the date as a REAL value in your database (as opposed to a TEXT). This can be a little more efficient and automatically addresses the UTC issue.


text:
Q: ¿Por qué en algunas computadoras no se ejecutan mis comandos de JAVA? Estoy usando NETBEANS IDE 8.0.1 y para mi proyecto final de preparatoria decidí crear una aplicación (en java) acerca de las herramientas de Windows, algo bastante sencillo, pero tengo un problema, y es que, apesar de que tengo la misma ruta para todas las aplicaciones, en algunas computadoras no abre o simplemente no ejecuta el programa, digamos, tengo 4 herramientas principales (Desfragmentador de disco, liberador de espacio, restaurar sistema y administrador de dispositivo), en mi computadora con Windows 10 se ejecutan TODAS correctamente, pero en la de un amigo para hacer una prueba solo se ejecutan 2 que es liberador de espacio y administrador de dispositivos, en resumen el problema está en que en algunas computadoras ejecuta todas las herramientas y en otras computadoras solo ejecuta algunas mi código es el siguiente:
public static void ADMINDISP(){
        try
        {
        Runtime.getRuntime().exec("powershell.exe Start-Process 'C:\\Windows\\System32\\devmgmt.msc' -verb RunAs");
        }
        catch (Exception ex)
        {
        JOptionPane.showMessageDialog(null, ex);
        System.out.println(ex);
        }
    }

En donde está señalada la ruta es lo mismo para todos, sólo cambia obviamente la ruta del archivo que ejecuta esa herramienta, sin embargo no entiendo por qué a algunos no les ejecuta, si hubiera otra manera de que forzara a abrir la aplicación o algo, al final llamo así para que ejecute dentro de mi botón
incluso tengo el JOptionPane donde le mostraría al usuario donde está el error al ejecutar el programa pero aún así no muestra nada, lo he probado personalmente en una pc donde falla y nada...
private void ADMINDISPActionPerformed(java.awt.event.ActionEvent evt) {
        ADMINDISP();
    }

Dejo el link más actualizado de mi programa por si lo necesitan probar, me haría mucha utilidad saber cuál es mi error, gracias.
https://mega.nz/#!lgpgEACR!uX1n3zPepcQavDj3UXJCeThdKv27FY1PfDhsmZKSXNo

A: buenos dias. Lo mas probable es que tus variables de entorno JAVAPATH o PATH, no estén apuntando correctamente al directorio correcto donde reside tu instalación de java.


text:
Q: Help interpreting DBCC CHECKDB output related to Torn Pages I've been asked to look at a SQL 2005 database that is reporting 'torn page' errors.
I can look up the MsgIDs and so on, but I just need a few pointers interpreting the DBCC CHECKDB output in a more general sense.
In this sample:
Msg 8909, Level 16, State 1, Line 1
Table error: Object ID 0, index ID -1, partition ID 0, alloc unit ID 8795506764168298496 (type Unknown), page ID (1:106887) contains an incorrect page ID in its page header. The PageId in the page header = (1041:-523272204).
Msg 8939, Level 16, State 98, Line 1
Table error: Object ID 0, index ID -1, partition ID 0, alloc unit ID 8971733407675449344 (type Unknown), page (0:0). Test (IS_OFF (BUF_IOERR, pBUF->bstat)) failed. Values are 62916617 and -4.
CHECKDB found 0 allocation errors and 37 consistency errors not associated with any single object.
... apparently the errors are not related to any single object (note that ObjectID and IndexID dont have proper values). What does that mean exactly? If its not a single object then what is it?
In this sample:
Msg 8939, Level 16, State 98, Line 1
Table error: Object ID 69575286, index ID 1, partition ID 286034662653952, alloc unit ID 286034662653952 (type In-row data), page (1:207727). Test (IS_OFF (BUF_IOERR, pBUF->bstat)) failed. Values are 62916617 and -1.
Msg 8964, Level 16, State 1, Line 1
Table error: Object ID 69575286, index ID 1, partition ID 286034662653952, alloc unit ID 71780678747160576 (type LOB data). The off-row data node at page (1:443), slot 26, text ID 1509706039296 is not referenced.
... is it referring to pages that contain data, or pages that contain indexes? It mentions off-row data but it also gives and Index ID. What do Index ID values 0 and 1 signify?
This is to help out a charity, by the way, so any help greatly appreciated. Thanks.
PS: I'm not on site yet, just looking through the dbcc logs they sent me, so I can't do any tinkering yet.
Edit: Its SQL 2005 v 9.0.3042
Edit: Lets say, you know, hypothetically, that restoring backups might not be an option because the torn pages have been in the database for a couple of months, due to a third party not putting the maintenance plans back in place after a server switch, or some such scenario. Hence assume that investigating the errors and trying to fix them or isolate them is the only course of action.

A: Paul Randall has pretty much every answer you'll ever need.
However, in practice, you should be thinking "restore" already...

A: I speak from experience here...
There error means that your database is damaged.
I would restore the latest backup you have that doesn't have this error, and use it.
You can run DBCC to repair the damage, but there's a fair chance you'll lose data.  I don't recommend doing this though, because the 'restore/repair' might seem to work but doesn't.


text:
Q: How to show multiple feature info on a map click of multiple layers displayed using geoserver

var element = document.getElementById('popup');
var popup = new ol.Overlay({
          element: element,
          positioning: 'bottom-center',

          stopEvent: false
      });
      map.addOverlay(popup);
var Source_ATM =
        new ol.source.TileWMS({
        url: 'http://localhost:8080/geoserver/BMC/wms',
        params: {
            'LAYERS': 'BMC:atm',
            'VERSION': '1.1.0',
            'FORMAT': 'image/png',
            'TILED': true
        },
        id:"atm",
        serverType:'geoserver'
        });

    var Layer_ATM = new ol.layer.Tile({
        source: Source_ATM,

    });

    Layer_ATM.setVisible(false);

    //block_boundary Layer
    var Source_BlockBoundary =
        new ol.source.TileWMS({
        url: 'http://localhost:8080/geoserver/BMC/wms?',
        params: {
            'LAYERS': 'BMC:block_boundary',
            'VERSION': '1.1.0',
            'FORMAT': 'image/png',
            'TILED': true
        },
        id:"block_boundary",
        serverType:'geoserver'
    });

    var Layer_block_boundary = new ol.layer.Tile({
        source: Source_BlockBoundary,

    });

    Layer_block_boundary.setVisible(false);
    function featureinfoFun() {

                  map.on('singleclick', function (evt) {

                      var view = map.getView();
                      var viewResolution = view.getResolution();

                      var source = Layer_block_boundary.getSource();
                      //var source2=Layer_test.getSource();

                      var url = source.getGetFeatureInfoUrl(
                        evt.coordinate, viewResolution, view.getProjection(),
                        { 'INFO_FORMAT': 'text/html', 'FEATURE_COUNT': 50 });

                      if (url) {
                          var coordinate = evt.coordinate;
                          popup.setPosition(coordinate);
                          $(element).popover("destroy");
                          $(element).popover({
                              'placement': 'top',
                              'html': true,
                              'content': ''

                          });

                          $(element).popover('show');
                          $(element).css('display', 'block');
                          //$(element).popup.classList.toggle('show');
                          //$(element).popup.close();
                      }
                  });
            }

    .ol-popup {
            position: absolute;
            background-color: white;
            -webkit-filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
            filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
            padding: 15px;
            border-radius: 10px;
            border: 1px solid #cccccc;
            bottom: 12px;
            left: -50px;
            min-width: 280px;
          }
          .ol-popup:after, .ol-popup:before {
            top: 100%;
            border: solid transparent;
            content: " ";
            height: 0;
            width: 0;
            position: absolute;
            pointer-events: none;
          }
          .ol-popup:after {
            border-top-color: white;
            border-width: 10px;
            left: 48px;
            margin-left: -10px;
          }
          .ol-popup:before {
            border-top-color: #cccccc;
            border-width: 11px;
            left: 48px;
            margin-left: -11px;
          }
          .ol-popup-closer {
            text-decoration: none;
            position: absolute;
            top: 2px;
            right: 8px;
          }
          .ol-popup-closer:after {
            content: "✖";
          }

This is my code. Please help me to display feature information of both of the layers. please help me with code. I want to show multiple layers and when i click on a layer and another layer it will display the attribute information coming from geoserver for both of the layers

A: To show information from both layers you either need to make two getFeatureInfo requests (one for each layer). Or, you can combine the two layers in the request by setting the LAYERS & QUERY_LAYERS parameters to be a comma separated list of layer names (if you are specifying styles then you will also need to add both style names to the STYLES parameter).
The easiest way to do this is to add LAYERS & QUERY_LAYERS to the param block when calling getFeatureInfoUrl


text:
Q: Azure RM Template. Pass complex value to 3rd level nested template I have a parent template with 2 levels of nested templates, azuredeploy.json->vmReferenceTemplate.json->datadiskreference.json When I'm passing the required value from 2nd level to 3rd it deploys fine, but it doesn't work when passing the exact same value from 1st level to 3rd level nested template. I would like to numDataDisks value from azuredeploy.json to datadiskreference.json I have a very complex template and in order for it to work I must pass the value from 1st level. Here is striped down version that works.
azuredeploy.json:
{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "parameters": {
    ,,,
    "numberOfVMs": {
      "type": "int",
      "defaultValue": 8,
    },
    "numberOfDataDisks": {
      "type": "array",
      "defaultValue": [
        2,
        1,
        3,
        1,
        1,
        1,
        1,
        1
      ]
    },
    ...
  },
  "resources": [
    {
      "name": "[concat(parameters('vmName'), copyIndex(1),'-','reference')]",
      "type": "Microsoft.Resources/deployments",
      "apiVersion": "2016-09-01",
      "copy": {
        "name": "vmReferenceTemplateLoop",
        "count": "[parameters('numberOfVMs')]"
      },
      "properties": {
        "mode": "Incremental",
        "templateLink": {
          "uri": "[concat(parameters('_artifactsLocation'), '/', variables('vmReferenceTemplateTemplateFolder'), '/', variables('vmReferenceTemplateTemplateFileName'), parameters('_artifactsLocationSasToken'))]",
          "contentVersion": "1.0.0.0"
        },
        "parameters": {
          "numDataDisks": {
            "value": "[parameters('numberOfVMs')]"
          }
        }
      }
    }
  ],
...

vmReferenceTemplate.json:
{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "parameters": {
    ...
    "numberOfVMs": {
      "type": "int",
      "defaultValue": 2
    },
    "numberOfDataDisks": {
      "type": "array",
      "defaultValue": [
        2,
        1,
        3,
        1,
        1,
        1,
        1,
        1
      ]
    },
    ...
  },
  "resources":
    {
      "apiVersion": "2016-09-01",
      "name": "[parameters('dataDisksReferenceTemplateName')]",
      "type": "Microsoft.Resources/deployments",
      "copy": {
        "name": "dataDiskReferenceLoop",
        "count": "[parameters('copyNestedReference')]"
      },
      "properties": {
        "mode": "Incremental",
        "templateLink": {
          "uri": "[variables('dataDiskReferenceTemplateUri')]",
          "contentVersion": "1.0.0.0"
        },
        "parameters": {
          "vmName": {
            "value": "[parameters('dataDisksVMnameReference')]"
          },
          "storageAccountName": {
            "value": "[variables('var_storageAccountName')]"
          },
          "numDataDisks": {
            "value": "[parameters('numberOfDataDisks')[copyIndex()]]"
          },
          "sizeOfEachDataDiskInGB": {
            "value": "[variables('sizeOfEachDataDiskInGB')]"
          }
        }
      }
    }
  ],
  ...

And this is how I'm trying to pass values from 1st level to 3rd level, but it fails with the error "Deployment template validation failed: 'The provided value for the template parameter 'numDataDisks' at line '36' and column '22' is not valid.'."
azuredeploy.json
{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "parameters": {
    ,,,
    "numberOfVMs": {
      "type": "int",
      "defaultValue": 8,
    },
    "numberOfDataDisks": {
      "type": "array",
      "defaultValue": [
        2,
        1,
        3,
        1,
        1,
        1,
        1,
        1
      ]
    },
    ...
  },
  "resources": [
    {
      "name": "[concat(parameters('vmName'), copyIndex(1),'-','reference')]",
      "type": "Microsoft.Resources/deployments",
      "apiVersion": "2016-09-01",
      "copy": {
        "name": "vmReferenceTemplateLoop",
        "count": "[parameters('numberOfVMs')]"
      },
      "properties": {
        "mode": "Incremental",
        "templateLink": {
          "uri": "[concat(parameters('_artifactsLocation'), '/', variables('vmReferenceTemplateTemplateFolder'), '/', variables('vmReferenceTemplateTemplateFileName'), parameters('_artifactsLocationSasToken'))]",
          "contentVersion": "1.0.0.0"
        },
        "parameters": {
          "numDataDisks": {
            "value": "[parameters('numberOfDataDisks')[copyIndex()]]"
          }
        }
      }
    }
  ]
...

vmReferenceTemplate.json:
{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "parameters": {
    ,,,
    "numberOfVMs": {
      "type": "int",
      "defaultValue": 2,
    },
    "numberOfDataDisks": {
      "type": "array",
      "defaultValue": [
        2,
        1,
        3,
        1,
        1,
        1,
        1,
        1
      ]
    },
    ...
  },
  "resources": [
    {
      "apiVersion": "2016-09-01",
      "name": "[parameters('dataDisksReferenceTemplateName')]",
      "type": "Microsoft.Resources/deployments",
      "copy": {
        "name": "dataDiskReferenceLoop",
        "count": "[parameters('copyNestedReference')]"
      },
      "properties": {
        "mode": "Incremental",
        "templateLink": {
          "uri": "[variables('dataDiskReferenceTemplateUri')]",
          "contentVersion": "1.0.0.0"
        },
        "parameters": {
          "vmName": {
            "value": "[parameters('dataDisksVMnameReference')]"
          },
          "storageAccountName": {
            "value": "[variables('var_storageAccountName')]"
          },
          "numDataDisks": {
            "value": "[parameters('numDataDisks')]"
          },
          "sizeOfEachDataDiskInGB": {
            "value": "[variables('sizeOfEachDataDiskInGB')]"
          }
        }
      }
    }
  ]
...

A: Here we go, folks, just like I said in the comments, lets do a magic trick! Lets create a template with 2 nested templates, but pass output of 1 nested template to the other one!
"resources": [
    {
        ...
        "dependsOn": [
            "datadiskcopy" << DEPENDS ON ANOTHER TEMPLATE COPY LOOP !!!
        ],
        ...
            "parameters": {
                "adminPassword": {
                    "reference": {
                        "keyVault": {
                            "id": "/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.KeyVault/vaults/xxx"
                        },
                        "secretName": "[concat('secret', copyindex(1))]"
                    } << KEYVAULT REFERENCE YOU NEED !!
                },
                "diskObject": {
                    "value": "[reference(concat('nested-datadisk-', copyIndex())).outputs.result.value]" << REFERENCE ANOTHER NESTED DEPLOYMENT OUTPUT !!
                }
            }
        }
    },
    {
        "apiVersion": "2016-09-01",
        "name": "[concat('nested-datadisk-', copyIndex())]",
        "type": "Microsoft.Resources/deployments",
        "copy": {
            "name": "datadiskcopy",
            "count": "[parameters('LoopCount')]"
        },
        "properties": {
            "mode": "Incremental",
            "templateLink": {
                "uri": "https://raw.githubusercontent.com/4c74356b41/armotron/master/ml-vm-ml-dd-kv-nst-dd",
                "contentVersion": "1.0.0.0"
            },
            "parameters": {
                "numDataDisks": {
                    "value": "[parameters('numberOfDataDisksPerVM')[copyIndex()]]"
                }
            }
        }
    }

I will update links shortly, as I decided to rename my templates a bit, but you can take a look at armotron repo on my github for samples already.
This is using managed disks for simplicity, but you can use unmanaged ( going to be hardcore, thou )
PS. You might again run into caching issue, copy the data not from the RAW link. just tested this thing, works for me, you can extend it further.

A: While this doesn't answer your question directly, it might cast some light on better solutions. We went several rounds with ARM-templates for provisioning our Azure infrastructure, including nested templates as you're doing now. We ended up ditching nested templates for the following reasons:

*

*They ended up providing little value in terms of reuse. Each time we wanted to reuse a shared template, it almost always needed some adjustments to the specific scenario in question. That meant bump the version number, make adjustments and make the new version available on public Internet while also having the old versions available.

*The lack of constructs for conditionals (yes you can hack them in, but it makes the template unclear) made it even more difficult to achieve reusable templates.

Our ARM-templates are currently like this: Each Resource Group has its own git-repository in our Github account, and each resource in the resource group has its own template. A repository for a resource group looks for instance like this:
my_group
├── cloud-config.yaml
├── deploy.ps1
├── deploy.sh
└── resources
    ├── load_balancer.json
    ├── nsg.json
    ├── storage_account.json
    └── virtual_machine.json

Having separate templates for each resource makes maintenance much easier. The deploy.sh file is at the moment just  a series of az group deployment create-commands that deploys all the files, the same with the powershell script. We no longer need to have our ARM-templates on public Internet without authentication. You'll also notice that since this ARM-template is only meant for one reason group, we no longer need parameter files, parameters are handled along with the rest of the code.
I believe this setup provides much more flexibility than one giant ARM-template depending on nested templates. We can manage everything we want in isolation (like cloud-config.yaml) and later use scripts to generate ARM-templates for deployment. We are currently experimenting with creating a git-tag for every deployment and then use git to figure out which files have changed since last deployment.


text:
Q: Why I am getting NULL value while parsing JSON I am trying to parse a json file to extract certain fields using Java. However, I am getting null values for certain fields (tags) for example, country, site_type, replies_count, participants_count etc. I tried to use .toString() after json object but I still keep getting NULL values.
Can anyone please help me to fix the code? As sample of json is as follows:
{
"posts": [
{
  "thread": {
    "uuid": "5cf0a3152a01d082500a46b358e984610ce87c9c",
    "url": "https://www.cnn.com/videos/cnnmoney/2018/05/27/active-shooter-video-game-backlash.hln",
    "site_full": "www.cnn.com",
    "site": "cnn.com",
    "site_section": "http://feeds.feedburner.com/cnn/wYAn",
    "site_categories": [
      "media"
    ],
    "section_title": "CNN.com - RSS Channel - HP Hero",
    "title": "New 'school shooter' game stirs outrage",
    "title_full": "New 'school shooter' game stirs outrage",
    "published": "2018-05-27T15:15:00.000+03:00",
    "replies_count": 0,
    "participants_count": 0,
    "site_type": "news",
    "country": "US",
    "spam_score": 0.0,
    "main_image": "https://cdn.cnn.com/cnnnext/dam/assets/180527080429-video-game-active-shooter-super-tease.jpg",
    "performance_score": 3,
    "domain_rank": 81,
    "social": {
      "facebook": {
        "likes": 399,
        "comments": 0,
        "shares": 399
      },
      "gplus": {
        "shares": 0
      },
      "pinterest": {
        "shares": 2
      },
      "linkedin": {
        "shares": 0
      },
      "stumbledupon": {
        "shares": 0
      },
      "vk": {
        "shares": 0
      }
    }
  },
  "uuid": "5cf0a3152a01d082500a46b358e984610ce87c9c",
  "url": "https://www.cnn.com/videos/cnnmoney/2018/05/27/active-shooter-video-game-backlash.hln",
  "ord_in_thread": 0,
  "author": "",
  "published": "2018-05-27T15:15:00.000+03:00",
  "title": "New 'school shooter' game stirs outrage",
  "text": "MUST WATCH New 'active shooter' video game sparks backlash Thousands of people have petitioned to stop the release of a new video game which takes on the point of view of a school gunman.",
  "highlightText": "",
  "highlightTitle": "",
  "language": "english",
  "external_links": [],
  "entities": {
    "persons": [],
    "organizations": [],
    "locations": []
  },
  "rating": null,
  "crawled": "2018-05-27T16:05:21.021+03:00"
}
],
"total_count": "122"

    }
And here is my code (I am using json.simple.* API to parse json):
import java.io.FileReader;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JSONRetriever {

public static void main(String[] args) {
    JSONParser jsonParser = new JSONParser();
    Object object;

    try {

        object = jsonParser.parse(new FileReader("C:\\sample.json"));
        JSONObject jsonObject = (JSONObject) object;

        JSONArray posts = (JSONArray) jsonObject.get("posts");

        Iterator itr = posts.iterator();

        while (itr.hasNext()) {

            Object slide = itr.next();
            JSONObject jsonObject2 = (JSONObject) slide;
            JSONObject thread = (JSONObject) jsonObject2.get("thread");

            String uuid = (String) thread.get("uuid");
            String url = (String) thread.get("url");
            String site_full = (String) thread.get("site_full");
            String site = (String) thread.get("site");
            String site_section = (String) thread.get("site_section");

            String section_title = (String) jsonObject2.get("section_title");
            String title = (String) jsonObject2.get("title");
            String title_full = (String) jsonObject2.get("title_full");
            String published = (String) jsonObject2.get("published");
            String replies_count = (String) jsonObject2.get("replies_count");
            String participants_count = (String) jsonObject2.get("participants_count");
            String site_type = (String) jsonObject2.get("site_type");
            String country = (String) jsonObject2.get("country");
            String spam_score = (String) jsonObject2.get("spam_score");

            JSONObject social = (JSONObject) jsonObject2.get("social");
            System.out.println("section_title: " + section_title);
            System.out.println("title: " + title);
            System.out.println("title_full: " + title_full);
            System.out.println("published: " + published);
            System.out.println("replies_count: " + replies_count);
            System.out.println("participants_count: " + participants_count);
            System.out.println("site_type: " + site_type);
            System.out.println("country: " + country);
            System.out.println("spam_score: " + spam_score);

            System.out.println("uuid: " + uuid);
            System.out.println("url: " + url);
        }

    }catch(Exception e)
    {
        e.printStackTrace();
    }

}
}

A: Your fields are located in your "thread" object, not "jsonObject2", for example use:
 String country = (String) thread.get("country");