text:
Q: How to turn off Sublime Text's auto_match_enabled for a specific set of delimiters in specific sorts of documents? My question is related to this question about turning off parenthesis matching in Sublime Text 2.
Sublime Text 2/3 has the setting "auto_match_enabled", which automatically pairs delimiters ([ ],{ }," ", etc.). Most of the time this is a great feature. When writing certain documents, however, it gets in the way.
For instance, in LaTeX the double quotes are used (almost?) exclusively to add in umlauts. So, e.g., n\"aive gets compiled as näive. In this situation the automatic insertion of the matching double quote is not helpful -- it adds a keystroke to delete it. Given this, I would like to turn off auto matching only for double quotes and only in files with a .tex extension. Unfortunately, the global setting seems like an all-or-nothing deal -- there is no obvious (to me) way to restrict its scope.
How do I turn off auto matching for a single type of delimiter in a given context? More specifically, how do I turn off auto matching for double quotes in files with a .tex extension?

A: I'm afraid I don't have a solution for only double quotes, but if you want to disable just for LaTeX you can create the following file:
(This is for Sublime Text 3 - I believe it's similar for Sublime Text 2 though)
%APPDATA%\Sublime Text 3\Packages\LaTeX\LaTeX.sublime-settings
You may need to create the folder structure, and you can add any LaTeX specific settings here, in your case:
{
    "auto_match_enabled": false,
}

As I said and as I think you know, this will apply to all matching, I don't have an answer for only double quotes I'm afraid, but hopefully this will help with the LaTeX specific side.

A: Similar to Jonno's answer above, you can modify the keymap settings for a given package in the same way:
Create a Default.sublime-keymap file in the LaTeX directory (create folders if needed):
Windows:
%APPDATA%\Sublime Text 3\Packages\LaTeX\Default.sublime-keymap

macOS:
~/Library/Application Support/Sublime Text 3/Packages/LaTeX/Default.sublime-keymap

Linux:
~/.config/sublime-text-3/Packages/LaTeX/Default.sublime-keymap

You can then copy & paste the default keymap (Preferences -> Key Bindings - Default) settings for double quotes into this new file. Then I modified the actions of those key bindings to no longer insert quoted pairs. This is the result of my changes:
[
    // changed snippet arg contents from `"\"$0\""` to `"\""` to prevent inserting paired quotes
    { "keys": ["\""], "command": "insert_snippet", "args": {"contents": "\""}, "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
            { "key": "following_text", "operator": "regex_contains", "operand": "^(?:\t| |\\)|]|\\}|>|$)", "match_all": true },
            { "key": "preceding_text", "operator": "not_regex_contains", "operand": "[\"a-zA-Z0-9_]$", "match_all": true },
            { "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.double - punctuation.definition.string.end", "match_all": true }
        ]
    },
    // changed the command and args from `move` to the same command/args as above to prevent skipping auto-inserted quotes
    { "keys": ["\""], "command": "insert_snippet", "args": {"contents": "\""}, "context":
        [
            { "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
            { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true },
            { "key": "following_text", "operator": "regex_contains", "operand": "^\"", "match_all": true },
            { "key": "selector", "operator": "not_equal", "operand": "punctuation.definition.string.begin", "match_all": true },
            { "key": "eol_selector", "operator": "not_equal", "operand": "string.quoted.double - punctuation.definition.string.end", "match_all": true },
        ]
    }
]

Notes:

*

*I did not change the backspace operator (seen in the default keymap) when surrounded by quotes. I'm not exactly sure how to fix or if the behavior is incorrect or not

*Your default keybindings may be different than mine, feel free to make the same changes I described in comments above

*I imagine you can remove the entire context section and it work, but I did not try that out myself.


text:
Q: Make condition to set the colour of polyline on google maps API I've been make polyline on google Maps. But I wanna set the polyline into 3 colours. I have conditions to set it, but don't know how to place it. this is the code
    var polylinePlanCoordinates  = [];
     var polyline_data = <?php echo json_encode($data); ?>;
     for (var i=0;i< polyline_data.length;i++ ){
      polylinePlanCoordinates.push(new google.maps.LatLng(polyline_data[i]['latitude'], polyline_data[i]['longitude']));
    }

    var path= new google.maps.Polyline({
      path: polylinePlanCoordinates,
     geodesic: true,
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 5
     });

     path.setMap(map);
}

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

and the condition is
if(polyline_data[i]['kon_jem']>0 && polyline_data[i]['kon_jem']<3){
strokeColor: '#ffffff';
}
else if (polyline_data[i]['kon_jem']>3 && polyline_data[i]['kon_jem']<9){
strokeColor: '#000000';
}
else if (polyline_data[i]['kon_jem']>9){
strokeColor: '#fff000';
}

A: You need to process through your array creating individual polylines for each set of two points in your data, assign each segment the color associated with one of its endpoints.
// only go to length - 1 or you will overrun the array
for (var i = 0; i < polyline_data.length - 1; i++) {
  // for each segment of two points
  var polylinePlanCoordinates = [];
  polylinePlanCoordinates.push(new google.maps.LatLng(polyline_data[i]['latitude'], polyline_data[i]['longitude']));
  polylinePlanCoordinates.push(new google.maps.LatLng(polyline_data[i + 1]['latitude'], polyline_data[i + 1]['longitude']));

  // create a polyline
  var path = new google.maps.Polyline({
    path: polylinePlanCoordinates,
    geodesic: true,
    strokeOpacity: 1.0,
    strokeWeight: 5
  });
  // set the color of the segment based on the lowest index point
  if (polyline_data[i]['kon_jem'] > 0 && polyline_data[i]['kon_jem'] < 3) {
    path.setOptions({
      strokeColor: '#ffffff'
    });
  } else if (polyline_data[i]['kon_jem'] > 3 && polyline_data[i]['kon_jem'] < 9) {
    path.setOptions({
      strokeColor: '#000000'
    });
  } else if (polyline_data[i]['kon_jem'] > 9) {
    path.setOptions({
      strokeColor: '#fff000'
    });
  }
  path.setMap(map);
}

proof of concept fiddle

code snippet:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < polyline_data.length - 1; i++) {
    // for each segment of two points
    var polylinePlanCoordinates = [];
    polylinePlanCoordinates.push(new google.maps.LatLng(polyline_data[i]['latitude'], polyline_data[i]['longitude']));
    polylinePlanCoordinates.push(new google.maps.LatLng(polyline_data[i + 1]['latitude'], polyline_data[i + 1]['longitude']));

    // create a polyline
    var path = new google.maps.Polyline({
      path: polylinePlanCoordinates,
      geodesic: true,
      strokeOpacity: 1.0,
      strokeWeight: 5
    });
    bounds.extend(path.getPath().getAt(0));
    bounds.extend(path.getPath().getAt(1));

    if (polyline_data[i]['kon_jem'] > 0 && polyline_data[i]['kon_jem'] < 3) {
      path.setOptions({
        strokeColor: '#ffffff'
      });
    } else if (polyline_data[i]['kon_jem'] > 3 && polyline_data[i]['kon_jem'] < 9) {
      path.setOptions({
        strokeColor: '#000000'
      });
    } else if (polyline_data[i]['kon_jem'] > 9) {
      path.setOptions({
        strokeColor: '#fff000'
      });
    }
    path.setMap(map);

  }
  map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
var polyline_data = [
  {latitude: 0, longitude: 0, kon_jem: 0},
  {latitude: 0.1, longitude: 0.2, kon_jem: 1},
  {latitude: 0.2, longitude: 0.1, kon_jem: 2},
  {latitude: 0.3, longitude: 0.2, kon_jem: 3},
  {latitude: 0.4, longitude: 0.1, kon_jem: 4},
  {latitude: 0.5, longitude: 0.2, kon_jem: 5},
  {latitude: 0.6, longitude: 0.1, kon_jem: 6},
  {latitude: 0.7, longitude: 0.2, kon_jem: 7},
  {latitude: 0.8, longitude: 0.1, kon_jem: 8},
  {latitude: 0.9, longitude: 0.3, kon_jem: 9},
  {latitude: 0.9, longitude: 0.1, kon_jem: 10},
  {latitude: 1.0, longitude: 0.1, kon_jem: 11},
  {latitude: 1.1, longitude: 0.2, kon_jem: 12},
  {latitude: 1.2, longitude: 0.1, kon_jem: 13},
  ];
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

A: You could try setOption
 if($data['kon_jem']>0 && $data['kon_jem']<3){
      path.polyline.setOptions({strokeColor:'#ffffff'});
 }
 .....

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rank df by values and sum by unique variables I have this df:
> head(orientadores)
    name    Var2 Freq rank
1  Author1    A    1    1
2  Author1    B    2    4
3  Author2    A    2    2
4  Author3    A    3    3
5  Author4    A    1    1
6  Author4    B    3    6

the rank column was calculated like this, where, if the Var2 column is equal to "B", it should store it's value doubled.
orientadores$rank <- orientadores$Freq * ifelse(orientadores$Var2=="B",2,1)

i'd like to sum the rank values by name and order them, so it would look like this:
> head(orientadores)
  name    final_rank
1 Author4 7
2 Author1 5
3 Author3 3
4 Author2 2

How to do so?
I've tried this but it wouldn't do the trick:
orientadores <- orientadores %>%
        group_by(Var1) %>% mutate(final_rank = sum(Freq2))


text:
Q: Walsh-Lebesgue type theorem in $\Bbb R^{2m}$ for $m>1$ Is someone aware of any analogue of the Walsh-Lebesgue theorem in $\mathbb{R}^{2m}$ for $m>1$ and dealing with polyharmonic polynomials?
In this post,  $\phi$ is said to be polyharmonic in $\mathbb{R}^{2m}$ if it solves $\Delta^m \phi=0$. The case $m=1$ is the "classical" harmonic case: it contains the Weistrass theorem (the one dealing with the uniform approximation of $2\pi$-periodic continuous functions by trigonometric polynomials) and it can be seen as a corollary of Runge's theorem in complex analysis.
More specifically, a more modest version of my question could be:
if $\Omega$ is a bounded domain in $\mathbb{R}^{2m}$ with smooth boundary and $\psi$ is some given polyharmonic function in $\Omega$ (say continuous in $\bar{\Omega}$), letting $Z_\psi$ be its zero set in $\bar{\Omega}$, is-it true that the set of (the restrictions of) the polyharmonic functions in $\mathbb{R}^{2m}$ (or in $\bar{\Omega}$ in some sense) are dense in $C^0(Z_\psi)$ for the uniform norm?
Unless I am wrong, using the maximum principle, the case $m=1$ of this more specific question is a corollary of the aforementioned classical Walsh-Lebesgue theorem.
Many thanks in advance for any clue about this!
NB: I found some references for analogs of Runge's theorem in higer dimensions (dealing with Cliffordian functions, but, unless I missed it, it does not clearly solve the present question).


text:
Q: Algorithm to separate sentences? Assume I have an array of words. E.g. {"I", "like", "melons","Susan", "likes", "apples"}(Only a very simple example) I want to find where I should add a period, AKA where I should separate the sentence. So the answer would be "I like melons." "Susan likes apples."
The capitalization could give some hints. But a capitalized word does not guarantee a start word(first word of the sentence). For example, abbreviations like NBA, USA, country name like America, Canada, they are capitalized but can be in the middle of a sentence.
What algorithm can be used to do the work?

A: Without building a classifier and training it on a large corpus, I think looking for a period followed by a capitalized word is the only simple approach. It is also possible to find long lists of capitalized abbreviation words like that (as well as proper nouns potentially), which could help you.
NLTK has some good tools for that, using a combination of those approaches I believe, and gets very good precision.


text:
Q: How to populate sapui5 smart table with data from a CSV file after importing? I am new to SAPUI5 and so am struggling to use sap.ui.comp.smarttable.SmartTable of sapUI5. I saw various examples but all of them make use of oData service which I don't need to use in my case.
Basically what I need to do is, import CSV file and show its data in smartTable. I am successful in showing the data in a simple table in SAP but unable to figure out how to use smarttable without any oData service in SAPUI5.
I am using XML view for view part.
Please help.

A: Not. It is not possible. As mentioned here in documentation,

The SmartTable control creates a table based on OData metadata and the configuration specified. The entitySet attribute must be specified to use the control


text:
Q: nondecreasing f prove integrable with upper and lower sums I have been given a question as such:
If $f$ is nondecreasing on $[0,1]$ use upper and lower sums to prove $f$ is Riemann Integrable.
So I know that using upper and lower sums to prove a riemann integral I have to show that the upper sum equals the lower sum and I know that
the upper sum = $\sum_{j=1}^{n} M_j(x_j-x_{j-1})$
the lower sum = $\sum_{j=1}^{n} m_j(x_j-x_{j-1})$
Where the x's are the size of the intervals and the big M is the upper height and little m is lower height. I'm just not so sure how I should go about using the fact f is non decreasing to prove the lower and upper sums equal each other.

A: If $f$ is non decreasing you can give explicit expressions in terms of $f$ for $M_i$ and $m_i$.

A: If $f$ is nondecreasing, then the lower sums would be strictly increasing and bounded above by the upper sums. Simply apply the monotone convergence theorem from there.


text:
Q: How to parse String with multiple delimeters into long I need to parse String value into Long. Problem is, that value is separated by dots, so they are once groupingSeparator and once decimalSeparator.
So 50.000 should be parsed to 50, but 5.000.000 need to be parsed to 5000.
I've tried with DecimalFormat, but i cannot set it properly, and ended up with parsing 5.000.000 into 5 since dots were treated as decimalSeparator always.

A: String number = "5.000.000";
        String substring = number.substring(0, number.lastIndexOf("."));
        System.out.println(Long.parseLong(substring.replaceAll("\\.","")));


text:
Q: Using values from two different DataRow.Columns for one DataGridView column I need to display a column called Full Name in the my datagridview, but the datasource (datatable) does not have a FullName column.  It only has FirstName and LastName columns.  I'm setting up my DataGridView like this:
        Dim column As DataGridViewColumn = New DataGridViewTextBoxColumn()
        column.DataPropertyName = "?" //Need FirstName + " " + LastName
        column.Name = "FullName"
        dgv.Columns.Add(column)

How can I set the DataPropertyName to use data from both the FirstName and LastName columns in the datatable.?
Thanks.

A: One way to do this is to use a calculated data column

*

*Add a new DataColumn called FullName.

*Set the Expression property to FirstName + ' ' + LastName

*Set the DataPropertyName to FullName


text:
Q: AU audio files for Java Apparently Java only plays .au audio files and I want to play mp3 files. I want to convert them to au and do not want to use any third party library to play mp3 directly. Can you please let me know how I can prepare my mp3 files to be able to play them in Java. (specifically I'd like to convert mp3 files to au files with a freeware software but don't know any software that is capable of doing that)

A: Is your target platform Windows only? If so you might want to investigate JMF.
Otherwise, there's a nice guide here on extending JavaSound to play MP3s using MP3 SPI.
Overall, I'm finding your question is confusing. The act of decoding a MP3 file is to convert it to raw audio. Once done there is little point in then converting it again to the AU and then using the native Java API to play it - you might as well just play it straight after it's decoded into raw audio. Furthermore, if as your question implies you don't want to use third-party libraries at all, then you'll need to write your own MP3 decoder.

A: Audacity can convert MP3 files to AU

A: With sox I believe it's as simple as:
sox input.mp3 output.au


text:
Q: Distance between a point in $3$-D and the line $x=0$ ($y$-axis) Find the the perpendicular distance (which I assume will be the shortest distance both in $3$-D and $2$-D (if not then please find both perpendicular distance and shortest distance) of the $y$-axis ($x= 0$) and the point $P(3,2,4)$.
Finding such things in $2$-D is a piece of cake. Anyone can do it really. But when I enter $3$-D things start going confusing for me. Is this a very simple question or is there a standard formula for it?

A: Hint:
If $P=(3,2,4)$ than the perpendicular distance (that is also the shorter distance) from the $y$ axis stay on the plane $y=2$ that is perpendicular to the $y$ axis and contains the point.
So it is the distance from the point $P$ and the point $Q=(0,2,0)$.
Can you find this distance from two points?


text:
Q: How can I find out how much battery my Android app consumes on user's devices? I am writing an app to evaluate the feasibility of a Bluetooth P2P network on Android.
I noticed that on a Galaxy Nexus, it uses very little battery, while on a Nexus S, it drains the battery very quickly. This is directly caused by high CPU load due to Bluetooth.
Now, I would like to collect information about how much battery drain my app causes on the devices it is installed upon. Simply logging time vs. battery level is useless since I don't know when the device is in use, and even if I logged that, I would not know if the user is playing 3D games while Torrenting over WiFi or reading an eBook on a dimmed screen.
To make the problem worse, not all battery usage caused by my app is attributed to it in the battery screen - some is listed as "Bluetooth", for example (again, device-dependent).
Is there any easy, privacy-preserving way to get useful information on non-rooted devices? The devices are not under my control. I cannot simply go look in the menu, I cannot use ADB.

A: The Android API doesn't support this currently. The only available documentation is the one describing how to use BatteryManager's broadcasts, which only supply the overall battery level and no per-application details.
I suppose that even if there are undocumented ways to emulate what the System Settings battery manager shows, they would require rooting.

A: AFAIK there is no way to do this. The closest you can get to doing this is to hook up the device to a monitoring tool like little eye labs which does draw the battery consumed by your app over time on a graph. It also supports marking key events in the app's lifetime like turning on WIFI / bluetooth etc.
There is no support for doing this remotely, but you can get the data on your own test devices.

A: This approach is quite crude, but it may help. You can use the existing BatteryManager broadcasts to track changes to the overall battery level while your app is active.
Knowing when your app is active is a separate issue. If your app consists entirely of Activities, then you can get good results by starting to track whenever any of your Activities' onResume() methods is called, and stopping tracking in onPause(). If you can have all your Activities derive from a single base Activity class, then this is quite easy. See How to detect when an Android app goes to the background and come back to the foreground for suggestions on how to track this.
If your app is more complex, and the smart stuff happens in a longer-running component like a Service, then it's much harder.
This is crude, but at least it would help you distinguish "playing 3D games" from "using my app".


text:
Q: Need to replace NoneType with empty string while converting Excel sheet to JSON file, Any idea how to implement this? I'm trying to convert an .xlsx file to JSON using a python script, however there are null spaces in the sheet and I need to convert it to empty strings. How can I implement this ? My current code is :
Edit : By null space I mean the corresponding entries in the excel sheet are empty
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter

import json

wb = load_workbook(filename='C:\\Python39\data.xlsx')
ws = wb.active

my_list = []

last_column = len(list(ws.columns))
last_row = len(list(ws.rows))

for row in range(1, last_row + 1):
    my_dict = {}
    for column in range(1, last_column + 1):
        column_letter = get_column_letter(column)
        if row > 1:
            my_dict[ws[column_letter + str(1)].value] = ws[column_letter + str(row)].value
    my_list.append(my_dict)

data = json.dumps(my_list, sort_keys=True, indent=4)
with open('C:\\Python39\data.json', 'w', encoding='utf-8') as f:
    f.write(data)

A: The error you're getting is because you passed sort_keys=True to json.dumps, but your dict contains some keys which are None.  JSON objects can only contains string keys (I think the error message here is not so helpful--I think json.dumps should explicitly check first if all the keys are strings and raise a more helpful error in this case).  For example:
>>> import json
>>> d = {'a': 1, None: 2}
>>> json.dumps(d, sort_keys=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/lib/python3.6/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.6/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
TypeError: '<' not supported between instances of 'NoneType' and 'str'

You just need a condition in your code like:
key = ws[f'{column_letter}1'].value
key = '' if key is None else key
my_dict[key] = ws[f'{column_letter}{row}'].value

A: You could do this and replace NULL_PATTERN by whatever string of charachters you want:
NULL_PATTERN = ''
for row in range(1, last_row + 1):
    my_dict = {}
    for column in range(1, last_column + 1):
        column_letter = get_column_letter(column)
        if row > 1:
            key = ws[column_letter + str(1)].value
            value = ws[column_letter + str(row)].value
            my_dict[key if key else NULL_PATTERN] = value if value else NULL_PATTERN
    my_list.append(my_dict)

A: Try this:-
import openpyxl as xl

wb = xl.load_workbook(r'C:\\Python39\data.xlsx', data_only=True)
ws = wb.active
myList = []
for r in range(2, len(list(ws.rows)) + 1):
    myDict = {}
    for c in range(1, len(list(ws.columns)) + 1):
        cl = xl.utils.get_column_letter(c)
        if (k := ws[f'{cl}1'].value):
            if not (v := ws[f'{cl}{r}'].value):
                v = ''
            myDict[k] = v
    myList.append(myDict)
print(myList)


text:
Q: Laravel - Filtering dropdown list by previous dropdown selected In my laravel project, I have 2 dropdown lists in a form : Courses and Subjects; I'd like to have my Subjects dropdown list automatically filtered by what was selected in the Courses dropdown list before.
In my Subject model the relationship is like this,
public function courses()
    {
        return $this->belongsToMany(Course::class);
    }

And in my SubjectController,
public function getSubjects(Request $request)
    {
        $html = '';
        $subjects = Subject::whereHas('courses', function ($query) use($request){
           $query->where('course_id', $request->input('course_id'));
        })->get()->pluck('name', 'id');
        foreach($subjects as $subject){
            $html .= '<option value"' . $subject->id . '">' . $subject->name . '</option>';
        }

        return response()->json(['html' => $html]);
    }

And in my web.php, I've also added this line,
Route::get('subjects/get_by_course', 'SubjectController@getSubjects')->name('subjects.get_by_course');

And in the blade,

     {{ trans('Course') }}
          <select class="form-control select2" name="course_id" id="course_id">
              @foreach($courses as $id => $entry)
                    <option value="{{ $id }}" {{ old('course_id') == $id ? 'selected' : '' }}>{{ $entry }}</option>
              @endforeach
          </select>

        {{ trans('Subjects') }}
         <select class="form-control select2 multiple" name="subjects[]" id="subjects">
              <option value="">{{ trans('Please select) }}</option>
         </select>

But when I tried it, nothing showed up in the subjects dropdown list.
When I tried dd($subjects) with a specific course_id instead the $request->course_id, I have the result subjects that are ok.
What did I miss?


text:
Q: Database Row Locking My C# program is doing the following (pseudo code):
START TRANSACTION READ COMMITTED
Select isOriginal, * from myTable where tnr = x;
//Record found?
Yes:
  //isOriginal?
  Yes:
    update myTable set is_active = 0 where tnr = x;
  No:
    delete from myTable where tnr = x;
  //Do some simple logic on the values
  Insert into myTable (newvalues)
No:
  return record_not_found;
END TRANSACTION

However, when I start two instances of my program and both edit the same record at the same time two records are inserted as they both find the record in the select query.
What should happen is that the first transaction finds the record and inserts a new row while the second transaction returns a record not found.
How can I fix this? Put my transaction to serializable? Check the return value of update/delete? What's the best way?
Edit:
It should work on Sybase, Oracle & SQL Server.

A: If you are using MS SQL You will need to look at NOLOCK and ROWLOCK
NOLOCK tells SQL Server to ignore any type of locks and read directly from the actual tables.  The pro is it has great performance, the con is in this way you are circumventing a locked system.  ROWLOCK on the other hand asks SQL Server to use row-level locks.  Performance does hinder with rowlock so you need to determine if you need to lock on UPDATES / DELETES
In your case SELECT isOriginal, * FROM myTable WITH (NOLOCK) WHERE tnr=x
Then UPDATE myTable WITH (ROWLOCK) SET is_active=0 WHERE tnr=x

A: without knowing what db you are using you could setup a lock field in the db.
where each concurrent thread has a pid or thread id or at least a unique timestamp
just do a
update myTable set lock = <pid> where pid = null limit 1;

select isOriginal, * from myTable where lock = <pid>


text:
Q: I think we need to modify the proof. About Theorem 11.1(c) on p.91 in "Analysis on Manifolds" by James R. Munkres.
I am reading "Analysis on Manifolds" by James R. Munkres.

Definition:
  In this book, we call $A$ has measure zero in $\mathbb{R}^n$ if for every $\epsilon > 0$, there is a countable covering of $A$ by closed rectangles $Q_1^{'}, Q_2^{'}, \cdots$ such that $$\sum_{i=1}^{\infty} v(Q_i^{'}) < \epsilon.$$

By the way, in this book, the author didn't write $[a_1, b_1] \times \cdots [a_n, b_n]$ is a closed rectangle or not if $a_i = b_i$ for some $i$. But I believe $[a_1, b_1] \times \cdots [a_n, b_n]$ is a closed rectangle when $a_i = b_i$ for some $i$.
There is the above Theorem 11.1(c) on p.91 in this book.
I think we need to modify the following part of the proof because if $v(Q_i^{'})$ is equal to $0$, then there is no $Q_i$ such that $Q_i^{'} \subset \text{Int } Q_i \text{ and } v(Q_i) \leq 2 v(Q_i^{'})$.

Cover $A$ by rectangles $Q_1^{'}, Q_2^{'}, \cdots$ of total volume less than $\frac{\epsilon}{2}$. For each $i$, choose a rectanble $Q_i$ such that $$Q_i^{'} \subset \text{Int } Q_i \text{ and } v(Q_i) \leq 2 v(Q_i^{'}).$$

I modified like the following:

Cover $A$ by rectangles $Q_1^{'}, Q_2^{'}, \cdots$ of total volume less than $\frac{\epsilon}{4}$. For each $i$, choose a rectanble $Q_i$ such that $$Q_i^{'} \subset \text{Int } Q_i \text{ and } v(Q_i) < \max \{2 v(Q_i^{'}), \frac{\epsilon}{2^{i+1}}\}.$$

If we modify like the above, then $$\sum v(Q_i) < \sum \max \{2 v(Q_i^{'}), \frac{\epsilon}{2^{i+1}}\} \leq \sum (2 v(Q_i^{'}) + \frac{\epsilon}{2^{i+1}}) = \frac{\epsilon}{2} + \frac{\epsilon}{2} = \epsilon.$$
I am not good at mathematics, so I am not sure I am right or not.
Am I right or not?


text:
Q: ¿Cómo se separan los diferentes elementos de un SELECT COUNT? Tengo una consulta SQL que me dice cuantos personas se han connectados al menos una vez el dia pasado y me gustaría hacer una consulta para saber cuantos personas se han conectado al menos una vez durante el año pasado para cada lenguaje (Lang).
Por ejemplo con este schema:
CREATE TABLE sessions
    (`App Type` varchar(11), `Lang` varchar(2), `Session ID` int, `session_time` datetime, `User ID` int)
;

INSERT INTO sessions
    (`App Type`, `Lang`, `Session ID`, `session_time`, `User ID`)
VALUES
    #july 2021
    ('browser', 'fr', 46960339, '2021-07-29 00:00:00', 1292997),
    ('browser', 'es', 46960407, '2021-07-29 00:00:00', 1055040),
    ('pwa_android', 'fr', 46960412, '2021-07-29 00:00:00', 1120109),
    ('browser', 'fr', 46960391, '2021-07-29 00:00:00', 955480),
    ('pwa_android', 'en', 46960389, '2021-07-29 00:00:00', 800169),
    ('browser', 'es', 46960353, '2021-07-29 00:00:00', 1193745),
    # june 2021
    ('browser', 'fr', 46960339, '2021-06-29 00:00:00', 1292997),
    ('browser', 'es', 46960407, '2021-06-29 00:00:00', 1055040),
    ('pwa_android', 'fr', 46960412, '2021-06-29 00:00:00', 1120109),
    ('browser', 'fr', 46960391, '2021-06-29 00:00:00', 955480),
    ('pwa_android', 'en', 46960389, '2021-06-29 00:00:00', 800169),
    ('browser', 'es', 46960353, '2021-06-29 00:00:00', 12345),
    # june 2020
    ('browser', 'fr', 46960339, '2020-06-29 00:00:00', 1292997),
    ('browser', 'es', 46960407, '2020-06-29 00:00:00', 1055040),
    ('pwa_android', 'fr', 46960412, '2020-06-29 00:00:00', 1120109),
    ('browser', 'fr', 46960391, '2020-06-29 00:00:00', 955480),
    ('pwa_android', 'en', 46960389, '2020-06-29 00:00:00', 800169),
    ('browser', 'es', 46960353, '2020-06-29 00:00:00', 54321)

;

Puedo saber cada día cuántas personas se conectan al menos el año pasado gracias a:
SELECT sessions.session_time, (
  SELECT COUNT(DISTINCT(`USER ID`))
  FROM sessions s2
  WHERE s2.session_time BETWEEN DATE_SUB(sessions.session_time, INTERVAL 1 YEAR) AND sessions.session_time
)
FROM sessions
GROUP BY sessions.session_time

Que pueden probar en este Fiddle enlace.
Pero cómo puedo hacerlo para obtener los mismos resultados para cada Lenguaje? Hasta hoy intenté:
SELECT sessions.session_time, (
  SELECT COUNT(DISTINCT(`USER ID`))
  FROM sessions s2
  WHERE s2.session_time BETWEEN DATE_SUB(sessions.session_time, INTERVAL 1 YEAR) AND sessions.session_time
)
FROM sessions
GROUP BY sessions.session_time, sessions.Lang

Utilizo MySQL 5.7
Con la respuesta de A. Cedano
Lo he adaptado para intentar obtener el número de personas por idioma que se han conectado al menos una vez en el último año :
 SELECT
    DATE(session_time),
    Lang,
    COUNT(*) AS total
 FROM sessions
    WHERE YEAR(session_time) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))
 GROUP BY Lang, DATE(session_time)

A: Si quieres contar la cantidad de usuarios por lenguaje durante el año pasado, con esta consulta bastaría:
 SELECT
    `User ID`,
    COUNT(*) AS total
 FROM sessions
    WHERE YEAR(session_time) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))
 GROUP BY  Lang, `User ID`

No tienes por qué liarte con sub-consultas ni con DISTINCT ...
Si quieres que agrupe también por cada día, sólo tienes que agregar la parte de la fecha de session_time en el GROUP BY usando DATE, eso agrupará los registros sin tomar en cuenta la hora:
 SELECT
    `User ID`,
    COUNT(*) AS total
 FROM sessions
    WHERE YEAR(session_time) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))
 GROUP BY  Lang, `User ID`, DATE(session_time)

A: Si en el select principal agregas Lang, tu consulta te dirá en qué idioma se inició sesión y cúantas veces
SELECT sessions.session_time, `Lang`, (
  SELECT COUNT(DISTINCT(`USER ID`))
  FROM sessions s2
  WHERE s2.session_time BETWEEN DATE_SUB(sessions.session_time, INTERVAL 1 YEAR) AND sessions.session_time
)
FROM sessions
GROUP BY sessions.session_time, sessions.Lang

Edito:
utilizando la cláusula with
with sesiones as(
  select session_time, Lang,
    USER_ID
  from sessions s2
  WHERE s2.session_time BETWEEN DATE_SUB(session_time, INTERVAL 1 YEAR) AND session_time
)
 SELECT
    session_time,
    lang,
    COUNT(DISTINCT(User_ID))
 FROM sesiones
 GROUP BY  Lang

con ese ejemplo que te dejo, me funciona con los datos que habias dejado anteriormente, sería cuestión de que pruebes si te funciona con la gran cantidad de datos que manejas en la BD


text:
Q: How multiple rows can be selected from a table in triggers in postgres I am trying to write a trigger in which I have to create a Json after getting data(multiple rows) from another table.
I have two table task and data. data table contains multiple information about the task in key/value pair.
 task schema
 taskid
 description
 value

data table schema
  id
  taskid
  key
  value

Now in trigger I want to fetch all data corresponding to a task and prepare a JSON from that.
I am using below
 CREATE OR REPLACE FUNCTION event()
  RETURNS trigger AS
     $BODY$

        DECLARE
         _message json;
         _data data;

         BEGIN

         SELECT * INTO _data FROM data WHERE data.taskid = New.taskid;
          IF      TG_OP = 'INSERT' THEN
                          _messag:=json_build_object('taskId',NEW.taskid,'description',NEW.description,'value',NEW.value,'clientis',_data);

          END IF;

       INSERT INTO events(message)
       VALUES(_messag);

       RETURN NULL;
       END;

        $BODY$
LANGUAGE plpgsql VOLATILE

Here, I am using below query to get all data from data table corresponding to a taskid
SELECT * INTO _data FROM data WHERE data.taskid = New.taskid;

Here, the problem is that I am getting only one row. How can all rows will be fetched? If anyone has any idea?

A: You can aggregate everything into a single JSON value:
declare
...
  _data jsonb; --<< change the data type to jsonb
begin
...
IF TG_OP = 'INSERT' THEN
  -- only select everything if you really need it
  SELECT jsonb_agg(to_jsonb(data))
    INTO _data
  FROM data
  WHERE data.taskid = New.taskid;

  _message := json_build_object('taskId',NEW.taskid,'description',NEW.description,'value',NEW.value,'clientis',_data);
END IF;
...

A: It works for me:
CREATE OR REPLACE FUNCTION event()
 RETURNS trigger AS
 $BODY$

    DECLARE
    _message json;
    _data jsonb;

     BEGIN

   *****SELECT json_agg(tmp)
    INTO _data
  FROM (
    -- Your subquery goes here, for example:
    SELECT data.key, data.value
    FROM.data
    WHERE data.taskid = New.taskid
    ) tmp;*****

      IF      TG_OP = 'INSERT' THEN
                      _messag:=json_build_object('taskId',NEW.taskid,'description',NEW.description,'value',NEW.value,'clientis',_data);

      END IF;

   INSERT INTO events(message)
   VALUES(_messag);

   RETURN NULL;
   END;

    $BODY$
  LANGUAGE plpgsql VOLATILE

Research link: select statement in postgres function called inside a trigger


text:
Q: Unable to select the children of the next bootstrap carousel slide? I am trying to to get id of the image of the carousel that will be the active item. That is I am trying to get of the image id of the slide event. Currently, I have:
function ModalImageCaption () {
   var activeImage =
   $('.carousel').on('slide.bs.carousel', function(event){
       var imageId = $(event.relatedTarget).find('.carousel-inner');
       console.log (imageId);
   });
}

The console log implies that there are children nodes one of them being the image child so I update imageId variable to
var imageId=$(event.relatedTarget).find('.carousel-inner').children('img').attr('id');

but it always comes back as undefined is there something I am missing?

A: You can try to do:
$('.gallery-carousel').data("bs.carousel").getActiveIndex()

or
getItemIndex()

after 3.2
from:
Twitter Bootstrap Carousel - access current index
And:
https://github.com/twbs/bootstrap/pull/2404#issuecomment-4589229


text:
Q: How to write a boolean value to peripheral device (PSoC BLE) from central device (iPhone 7) I am very new at BLE implementations, so bear with me.  I am using Xcode 9.3, iOS version 11.3, and a PSoC 4200 BLE device.
I've got a custom circuit attached to the PSoC module that outputs a voltage to be sent via uint32 data packets to my iOS application.  My next step is to be able to create a UIButton object (just an on/off for now) and pass it's state back to the PSoC.
Forgetting the software used to setup the PSoC (Cypress's PSoC Creator 4.0 just fyi), I would like to know which delegate method/methods to use in Xcode to get this to work...my best guess is peripheralManager:didReceiveWriteRequests: in the CBPeripheralManagerDelegate protocol.  If I can only write back to the peripheral once the characteristic is read by the central, then I can use the last 8 bits of the uint32 voltage packet for the time being, if that's what the process requires. If it's better to create a new uint8 or boolean packet instead, and just use that as a write characteristic without intervening with the uint32, then I can do that too.
I have no transmission time requirements or energy consumption concerns as of now...I just need to get that boolean sent to the PSoC.
Any help at all will be much appreciated, thanks.
UPDATE:
after peripheral:didUpdateValueForCharacteristic:error: gets called, I call [self getTransducerData:characteristic withPeripheral:peripheral error:error];
Here is what happens in that method (I have added what I think is the appropriate way to use writeValue:forCharacteristic:type:)
- (void)getTransducerData:(CBCharacteristic*)characteristic withPeripheral:(CBPeripheral*)peripheral
                error:(NSError*)error {
    NSData* data = [characteristic value];
    const uint8_t *reportData = [data bytes];
    uint32_t v0 = (uint32_t)reportData[0];
    uint32_t v1 = (uint32_t)reportData[1] << 8;
    uint32_t v2 = (uint32_t)reportData[2] << 16;
    //uint32_t v3 = (uint32_t)reportData[3] << 24;

    int32_t voltage = v0 | v1 | v2; //| v3;

    if ((characteristic.value) || !error) {

        /* _captureOn is the boolean value after my UIButton object receives a touch.
           On and Off.
           If it's on, notify the peripheral with the last 8 bits of the uint32_t characteristic with 0x01.*/
        if (_captureOn) {
            uint8_t temp[4];
            temp[0] = v0;
            temp[1] = v1;
            temp[2] = v2;
            temp[3] = 0x01;
            NSData *data = [NSData dataWithBytesNoCopy:temp length:4 freeWhenDone:YES];
            [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }

        self.transducerValue = voltage;
        self.realVoltage = voltage/1000000.0;

        //self.levelView.value = self.realVoltage;

        if (self.realVoltage <= _originalHigh && self.realVoltage >= _originalLow) {
            self.testerVoltage = self.realVoltage;
            self.middleTachometer.currentLevel = (float)self.realVoltage;
            self.transducerPosition.text = [NSString stringWithFormat:@"%0.3lf V", self.realVoltage];
        }
    }
}


text:
Q: Filter Out Data in Json I have the below json file, where i need to filter the City data based on flag value equals to true
"attributes": { "State":
    [ { "type": "sc", "ov": true, "value": "TN" } ],
    "City": [ { "type": "c", "flag": true, "value": "Chennai" },
    { "type": "c", "flag": false, "value": "Coimbatore" } ],
    }

Expecting the output as below
State: TN
City: Chennai

A: Just load the json file into memory, then use a list comprehension to filter for where the flag is true.
import json

with open('yourfile.json', 'r') as citydata:
    cities_dict = json.load(citydata)

true_cities = [city for city in cities_dict['attributes']['City'] if city['flag']]

This won't mutate the original data, and will return a separate list of cities where the flag is true. You can just set the same list to the list comprehension's return value to mutate the original data in memory, such as:
cities_dict['attributes']['City'] = [city for city in cities_dict['attributes']['City'] if city['flag']]

A: you can write something like below to only filter city based on flag is True.
import json

data = json.loads(open("/home/imtiaz/tmp/data1.json").read())
data1 = [city for city in data['attributes']['City'] if city['flag'] is True]
data['attributes']['City'] = data1


text:
Q: Tweepy: extended mode with api.search I've written a simple script to get the most trending 300 tweets containing a specific hashtag.
for self._tweet in tweepy.Cursor(self._api.search,q=self._screen_name,count=300, lang="en").items(300):
        self._csvWriter.writerow([self._tweet.created_at, self._tweet.text.encode('utf-8')])

It works well and it save the result to CSV but the tweets are truncated.
I modified the code like this, adding the twitter_mode=extended parameter:
for self._tweet in tweepy.Cursor(self._api.search,q=self._screen_name,count=300, lang="en", tweet_mode="extended").items(300):
        self._csvWriter.writerow([self._tweet.created_at, self._tweet.text.encode('utf-8')])

But I got this exception:
AttributeError: 'Status' object has no attribute 'text

My question is: how can I save an complete tweet using a Cursor? (complete = not truncated)
Thanks in advance (and sorry, I'm a Tweepy newbie trying to learn as much as possible)

A: You're really close, do this instead:
for self._tweet in tweepy.Cursor(self._api.search,q=self._screen_name,count=300, lang="en", tweet_mode="extended").items(300):
    self._csvWriter.writerow([self._tweet.created_at, self._tweet.full_text.encode('utf-8')])

Notice that I used full_text in self._tweet.full_text.encode('utf-8'), rather than just text. The text property is null when you use tweet_mode='extended' and the tweet appears in full_text instead.


text:
Q: Stack Overflow Error when getting integer size? As part of a class code project, part of the assignment is to construct an algorithm that will multiply two matrices using the Strassen method.
I have created the algorithms necessary to do so, however I am getting a Stack Overflow error on a getSize() call. Any help with figuring out why this is would be appreciated.
I have not appended all code, just that which pertains to the question.
    // CODE CALLING THE MULTIPLICATION
    Matrix m = new Matrix(Integer.parseInt(size.getText()), 20);
    Matrix m2 = new Matrix(Integer.parseInt(size.getText()), 20);
    Matrix m3 = m.strassenMult(m2);

    // THE MATRIX CLASS
    public class Matrix {

    private int[][] vals;
    private int size;
    private boolean stable = false;
    private long time;

    // Constructor for known data
    public Matrix(int[][] vals) {
    this.vals = vals;
    this.size = vals.length;
    stable = true;
    }

    // Constructor for matrix with random size, if bounds = 0 it is empty
    public Matrix(int size, int bounds) {
    this.size = size;
    vals = new int[size][size];
    stable = true;
    if (bounds != 0) {
        Random rand = new Random(System.currentTimeMillis());
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                int x = rand.nextInt();
                x = x % bounds;
                vals[j][i] = x;
            }
        }
    }
    }

    private Matrix add(Matrix m2) {
    ///////////////////////// THE ERROR IS ON THE BELOW LINE
    int n = m2.getSize();
    int[][] newVals = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            newVals[i][j] = vals[i][j] + m2.getVal(i, j);
        }
    }
    Matrix sum = new Matrix(newVals);
    return sum;
    }
    private Matrix subtract(Matrix m2) {
    int n = m2.getSize();
    int[][] newVals = new int[n][n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            newVals[i][j] = vals[i][j] - m2.getVal(i, j);
        }
    }
    return new Matrix(newVals);
    }

    // The strassen multiplication algorithm
    public Matrix strassenMult(Matrix m2) {
    int n = m2.getSize();
    int newSize = n / 2;
    // initialize new sub-matricies
    Matrix a11 = new Matrix(newSize, 0);
    Matrix a12 = new Matrix(newSize, 0);
    Matrix a21 = new Matrix(newSize, 0);
    Matrix a22 = new Matrix(newSize, 0);
    Matrix b11 = new Matrix(newSize, 0);
    Matrix b12 = new Matrix(newSize, 0);
    Matrix b21 = new Matrix(newSize, 0);
    Matrix b22 = new Matrix(newSize, 0);
    Matrix aResult = new Matrix(newSize, 0);
    Matrix bResult = new Matrix(newSize, 0);

    // divide existing matries into the sub-matricies
    for (int i = 0; i < newSize; i++) {
        for (int j = 0; j < newSize; j++) {
            a11.set(i, j, vals[i][j]); // top left
            a12.set(i, j, vals[i][j + newSize]); // top right
            a21.set(i, j, vals[i + newSize][j]); // bottom left
            a22.set(i, j, vals[i + newSize][j + newSize]); // bottom right

            b11.set(i, j, m2.getVal(i, j)); // top left
            b12.set(i, j,m2.getVal(i, j + newSize)); // top right
            b21.set(i, j, m2.getVal(i + newSize, j)); // bottom left
            b22.set(i, j, m2.getVal(i + newSize, j + newSize)); // bottom right
        }
    }
    // Calculating p1 to p7:
    ////////////////////////////////// ERROR IS CALLED BY THIS METHOD
    aResult = a11.add(a22);
    bResult = b11.add(b22);
    Matrix p1 = aResult.strassenMult(bResult);
    // p1 = (a11+a22) * (b11+b22)

    aResult = a21.add(a22); // a21 + a22
    Matrix p2 = aResult.strassenMult(b11); // p2 = (a21+a22) * (b11)

    bResult = b12.subtract(b22); // b12 - b22
    Matrix p3 = a11.strassenMult(bResult);
    // p3 = (a11) * (b12 - b22)

    bResult = b21.subtract(b11); // b21 - b11
    Matrix p4 = a22.strassenMult(bResult);
    // p4 = (a22) * (b21 - b11)

    aResult = a11.add(a12); // a11 + a12
    Matrix p5 = aResult.strassenMult(b22);
    // p5 = (a11+a12) * (b22)

    aResult = a21.subtract(a11); // a21 - a11
    bResult = b11.add(b12); // b11 + b12
    Matrix p6 = aResult.strassenMult(bResult);
    // p6 = (a21-a11) * (b11+b12)

    aResult = a12.subtract(a22); // a12 - a22
    bResult = b21.add(b22); // b21 + b22
    Matrix p7 = aResult.strassenMult(bResult);
    // p7 = (a12-a22) * (b21+b22)

    // calculating c21, c21, c11 e c22:
    Matrix c12 = p3.add(p5); // c12 = p3 + p5
    Matrix c21 = p2.add(p4); // c21 = p2 + p4

    aResult = p1.add(p4); // p1 + p4
    bResult = aResult.add(p7); // p1 + p4 + p7
    Matrix c11 = bResult.subtract(p5);
    // c11 = p1 + p4 - p5 + p7

    aResult = p1.add(p3); // p1 + p3
    bResult = aResult.add(p6); // p1 + p3 + p6
    Matrix c22 = bResult.subtract(p2);
    // c22 = p1 + p3 - p2 + p6

    // Grouping the results obtained in a single matrix:
    Matrix result = new Matrix(n, 0);
    for (int i = 0; i < newSize; i++) {
        for (int j = 0; j < newSize; j++) {
            result.set(i, j, c11.getVal(i, j));
            result.set(i, j + newSize, c12.getVal(i, j));
            result.set(i + newSize, j, c21.getVal(i, j));
            result.set(i + newSize, j + newSize, c22.getVal(i, j));
        }
    }
    return result;
    }

    public int getSize() {
    return size;
    }

A: Your Strassen multiplication function is missing a base case. At some point, you need to stop recursing and call a different matrix multiplication algorithm.


text:
Q: Jquery - after cloning a div how to get it by pre set id? I'm creating div dynamically by cloning with some content. After this I have to change content dynamically. For example bellow div's are generating dynamically by $.each and set the content.

content 1

content 2

content 3

content 4

Now I want to change content dynamically again. Here is a prat of my example code.
 $.each( data, function( key, d ) {
   var $tabId = '#tab'+d.id;
   //check is ID created
   if(document.getElementById($tabId) == null)
   {
     $newTab = $modelTab.clone().prop('id', $tabId );
     $newTab.find('.content').text(d.content);  //this part is working
   }
   else
   {
     $($tabId).find('.content').text(d.content); //not working
   }
 });

That mean's I just clone a div once at a time with ID and next I will just update the specific content. Please give me a solution. What I have to do?


text:
Q: Class name is wrong in Python code Below is the code that I have generated using wxFormBuilder however when I tied to run the code its giving error.
import wx
import wx.xrc

class MyFrame2(wx.Frame):   #Class defined

    def __init__(self, parent):
    wx.Frame.__init__(
        self,
        parent,
        id = wx.ID_ANY,
        title = wx.EmptyString,
        pos = wx.DefaultPosition,
        size = wx.Size(1020, 486),
        style = wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL,
    )

self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize)

gbSizer1 = wx.GridBagSizer(0, 0)
gbSizer1.SetFlexibleDirection(wx.BOTH)
gbSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

self.m_textCtrl6 = wx.TextCtrl(
    self,
    wx.ID_ANY,
    wx.EmptyString,
    wx.DefaultPosition,
    wx.DefaultSize,
    0,
)
gbSizer1.Add(self.m_textCtrl6, wx.GBPosition(0, 0),
    wx.GBSpan(1, 1), wx.ALL, 5)

self.m_button4 = wx.Button(
    self,
    wx.ID_ANY,
    u 'MyButton',
    wx.DefaultPosition,
    wx.DefaultSize,
    0,
)
gbSizer1.Add(self.m_button4, wx.GBPosition(0, 1), wx.GBSpan(1,
    1), wx.ALL, 5)

self.SetSizer(gbSizer1)
self.Layout()

self.Centre(wx.BOTH)

def __del__(self):
    pass

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame2(parent = None)
    frame.Show()
    app.MainLoop()

Error msg is:Why I am getting error msg when I am trying to invoke the class.
I can see that MyFrame is defined but still getting below error.
NameError: name 'MyFrame2' is not defined
Any Help on this.


text:
Q: How to allow short tags in php with apache how can I allow apache to use
'<?'

Now it understands only
'<?php'

Found answer: in php.ini short_open_tag should be On.

A: You are looking for the short_open_tag configuration option.


text:
Q: How to get rid of the "Error in CPL_write_ogr" error when using "st_write" to export a sf object? I'm trying to intersect two sf objects for the US (one at the township level and the other one at the census tract level). I'm getting both using tigris and tidycensys. My final goal is to have an unique sf object with information at the township level (with information from both the originals township and census tract level sf objects). And after I do this intersection, I want to export this sf object using st_write from the sf package. Here is the code I've used:
library(tigris)
library(sf)
library(purrr)
library(tidycensus)
library(tidyr)
library(dplyr)

##Data at township level
#---------------------------#
MN_Township_SHP <- county_subdivisions("Minnesota", cb = TRUE)%>% st_transform(., crs=32618)
MN_Township_SHP$County <- substr(MN_Township_SHP$NAMELSADCO,1,nchar(MN_Township_SHP$NAMELSADCO)-7)
Dataset <- MN_Township_SHP

#Data at census tract level
#---------------------------#
Sys.getenv("CENSUS_API_KEY")

my_vars <-
  c(total_pop        = "B01003_001",
    race_denominator = "B02001_001", #Total
    white            = "B02001_002")
mn <- unique(fips_codes$state)[24]
MN_CensusTract_SHP <-map_df(mn, function(x) {
  get_acs(geography = "tract",
          geometry = T,
          variables = my_vars,
          state = mn) })
MN_CensusTract_SHP <- MN_CensusTract_SHP %>% dplyr::select(-moe)
Social_Dat <-
  MN_CensusTract_SHP %>%
  as.data.frame() %>%
  pivot_wider(names_from = variable,
              values_from = c(estimate)) %>%
  dplyr::mutate(year=2021) %>%
  dplyr::rename_all(funs(paste0("ACS_", .)))
Social_Dat$ACS_year <- as.double(Social_Dat$ACS_year)
Social_Dat$ACS_GEOID <- as.double(Social_Dat$ACS_GEOID)
Social_Dat <- st_as_sf(Social_Dat, sf_column_name = 'ACS_geometry')%>% st_transform(., crs=32618)

#Intersection between township and census tract levels
#---------------------------#
final_df <- st_intersection(Dataset, Social_Dat, all=TRUE)

#Export sf object as shapefile
#---------------------------#
st_write(final_df, "Input_Intermediate/final_df.shp",  delete_layer = TRUE)

However, when I run this final step, I get the following error:
"Error in CPL_write_ogr(obj, dsn, layer, driver, as.character(dataset_options),  :
Write error"
Does anyone know how to solve this? I've tried so many ways that I found in google, but none of them worked for me. Many thanks in advance!!!

A: You can use the function st_collection_extract and get only the polygon type from your geometry column, and then you can proceed and use st_write again.
df <- st_collection_extract(final_df, type = "POLYGON")
st_write(df, "Input_Intermediate/final_df.shp",  delete_layer = TRUE)


text:
Q: How does Elasticsearch client works? I'm a newbie to Elasticsearch, I'm using Elasticsearch for my app. My app has the following code to interact with ES.
- Client (Singleton)

if(client==null) {
        client = new TransportClient().addTransportAddress(new InetSocketTransportAddress(host,port.toInteger()))
}

This client is used in throughout the app and destroyed on the shutdown of the app. I don't close the client anywhere else. Recently, I started facing "No Node Available" exception. I tried digging into that and found some people talking about closing the connection every time after any operation. So my question is, how does the Java client actually work? Does it create a connection with the cluster and keep it alive (till the timeout if specified) to be reused or every time it tends to create new connection?


text:
Q: Parsing an xml file and storing it into a database Is there a generic/automatic way in R or in python to parse xml files with its nodes and attributes, automatically generate mysql tables for storing that information and then populate those tables.

A: Regarding

Is there a generic/automatic way in R
  to parse xml files with its nodes and
  attributes, automatically generate
  mysql tables for storing that
  information and then populate those
  tables.

the answer is a good old yes you can, at least in R.
The XML package for R can read XML documents and return R data.frame types in a single call using the xmlToDataFrame() function.
And the RMySQL package can transfer data.frame objects to the database in a single command---including table creation if need be---using the dbWriteTable() function defined in the common DBI backend for R and provided for MySQL by RMySQL.
So in short: two lines can do it, so you can easily write yourself a new helper function that does it along with a commensurate amount of error checking.

A: They're three separate operations: parsing, table creation, and data population.  You can do all three with python, but there's nothing "automatic" about it.  I don't think it's so easy.
For example, XML is hierarchical and SQL is relational, set-based.  I don't think it's always so easy to get a good relational schema for every single XML stream you can encounter.

A: There's the XML package for reading XML into R, and the RMySQL package for writing data from R into MySQL.
Between the two there's a lot of work. XML surpasses the scope of a RDBMS like MySQL so something that could handle any XML thrown at it would be either ridiculously complex or trivially useless.

A: We do something like this at work sometimes but not in python. In that case, each usage requires a custom program to be written. We only have a SAX parser available. Using an XML decoder to get a dictionary/hash in a single step would help a lot.
At the very least you'd have to tell it which tags map to which to tables and fields, no pre-existing lib can know that...


text:
Q: Django: field's default value from model instance I'm trying to get the last_name and first_name of the newly created user and create the foldername using both values.
But I get type object 'User' has no attribute 'first_name'
This is my Users model:
def create_folder_name(first_name, last_name):
    return first_name + last_name

class User(AbstractUser):
    folder_name = models.CharField(max_length=255, unique=True,
                                   default=create_folder_name(User.first_name, User.last_name))

How can I pass the User.first_name to my function

A: If your default is constructed from other field values, you need to have a model instance to get the values.
Override the save() method:
class User(AbstractUser):
    folder_name = models.CharField(max_length=255, unique=True)

    def save(self, *args, **kwargs):
        if not self.folder_name:
            self.folder_name = create_folder_name(self.first_name, self.last_name)
        super(User, self).save(*args, **kwargs)

A: I think you're better off overriding the save method in your User model:
class User(AbstractUser):
    folder_name = models.CharField(max_length=255, unique=True)

    def save(self, *args, **kwargs):
        self.folder_name = create_folder_name(self.first_name, self.last_name)
        super(User, self).save(*args, **kwargs)


text:
Q: How does jOOQ support MySQL's dual? I can't use the jOOQ generator to generate a Dual.java class for MySQL,
but inverse in PostgreSQL
I have included "dual" in the code generation config file:
<includes>dual</includes>

<name>org.jooq.util.DefaultGenerator</name>

I'm using jOOQ's latest version: 2.4.0. What could be the problem?

A: With jOOQ, you don't have to worry about the DUAL table. jOOQ handles that for you. The following jOOQ query:
create.select(val(1), val(2)).fetch();

Will render
-- MySQL
SELECT 1, 2 FROM DUAL

-- Postgres
SELECT 1, 2

For more info about the DUAL tables and similar constructs in various SQL dialects, read this blog post:
http://blog.jooq.org/2011/10/16/sql-trouble-with-dummy-tables/


text:
Q: What do the older X-series games offer not included in Albion Prelude It was recommend to me to take a look at the X Series for a flight simulator with fighting and trading
X3:Terran Conflict with X3:Albion Prelude expansion is the latest.
How many hours of game play does it offer?
Do you need the previous games, Reunion and The Threat to understand the game?
X3: Reunion  is this even worth getting if you have X3:Terran Conflict?  Does one game handle better than the other in smoothness of play and UI controls?
x2: The Threat released in 2006 -- does it run on a i5 processor now a days?  Is there anything in this game that was good and not carried over to the  X3: Terran Conflict game
X: Tension and
X: Beyond the Frontier released in 2010  -- Same questions as above
Thanks for the help

A: Trying to answer only the concrete aspects of the question:

*

*X3:Albion Prelude is the latest in the X series, it is built on top of X3: Terran Conflict and contains the latest advances in the gameplay as well as graphics.  From a gameplay perspective, there's no reason to play any older games in the series, just AP.

*The X games will run fine on a i5 processor, but you will also need a graphics card to handle it.

*The only reason to ever play the earlier games is for the story, which you can easily gleam from reading a wiki about them.

A: If you can run X3:TC then get that AND X3:AP. Both games are amazing and in-depth as any of the previous titles, plus the X3 series has advanced physics simulation.
However for me, X2:The Threat was the most immersive due to having first person cockpit view, which has since been removed, but there are several mods that add them back in.
Docking was also more fun in X2; more realistic in X3, but it was nice to actually see the inside of the stations on X2, even if you couldn't really explore them.


text:
Q: Flutter_background_service doest work IOS Why does the background service not work on iOS devices? I gave all the necessary permissions and tried every way. flutter_background_service: I'm using ^0.0.1+21 and it says IOS support.
I'm trying to add a pedometer. It works perfectly in the background on Android, but I could not run it on IOS even though I met all the conditions.
When I close the application, it continues to work on android. How can I make this possible on iOS?


text:
Q: Panels creation at runtime can't see them My problem is i am trying to make a panel. My button in in Main.mxml whereas the panel functions are defined in panel_Create.mxml. the code works fine. In panel_Create their are functions to create panels at runtime. The problem i am facing is when i run the program it wont show the panels but it does increase the value of n and after 8 clicks it gives alert message. Please tell me why cant i see panels. The code works fine when i put all the code in Main.mxml
<fx:Script>
            <![CDATA[

                import Components.panel_Create;
                import mx.controls.Alert;
                import spark.components.Button
                public var adminPanel:panel_Create = new panel_Create();

                public var n:Number = 0;
                public function panel(event:MouseEvent): void
                {
                    if ( n < 8)
                    {
                        adminPanel.panel_Create(n);
                        n++;
                    }
                    else
                    Alert.show('More Panels Not Allowed', 'Alert Box', mx.controls.Alert.OK);
                }
            ]]>
        </fx:Script>

        <s:Button id="add" includeIn="State1" x="398" y="10" label="Add Panel" click="panel(event)"/>
        <Components2:panel_Create includeIn="State1" x="10" y="66" width="737" height="599">
        </Components2:panel_Create>

    </s:Application>

A: I believe that the 8 panels are created and based on the code in one of your comments they are added as child elements to the adminPanel.
The problem is that your adminPanel is never added to the stage so is not visible.

A: Try this instead:
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx">
    <fx:Script>
        <![CDATA[
            private var panels:Array = [];

            private function addPanel():void
            {
                if (panels.length < 8)
                {
                    var panel:Panel = new Panel();
                    panel.title = "Panel "+(panels.length + 1);
                    panels.push(panel);
                    addElement(panel);
                }else{
                    trace('More Panels Not Allowed');
                }
            }
        ]]>
    </fx:Script>
    <s:Button label="Add Panel" click="addPanel()"/>
</s:Application>

A: adminPanel is not being created. you have to do addElement(adminPanel) itself
if ( n < 8)
                    {
                        adminPanel.panel_Create(n);
                        addElement(adminPanel)
                        n++;
                    }


text:
Q: In which scenarios it is acceptable to disable Same Origin Policy of browsers? I want to make a HTTP GET request to a site in a different domain than the client site. The final objective is to display a dashboard in the client site for the data that in the source site. The server of the source site is not configured for CORS and therefore it's not possible to make a simple AJAX call using JavaScript.
So I have two options, either to set up a proxy or disable Same Origin Policy for the browser. This dashboard is to be displayed on a dedicated machine on a common display. Is it okay to disable Same Origin Request restriction for the browser since it's only used for this purpose? Thanks.

A: You have another option that you didn't mention: get the data from the external site server-side, and pass it to your own dashboard. This btw, is the preferred way.

A: You can disable it, but you need to understand the consequences. The main goal of the single-origin-policy is to help prevent XSS attacks. The SOP protects users from unknowingly having malicious AJAX making requests on their behalf.
With Cross-Origin-Resource-Sharing disabled, if malicious JavaScript is injected into a browser session, say through an ad network, then that JavaScript would be blocked from things like connecting to the user's online banking page.
When you indiscriminately bypass the SOP in a browser, then any browsing session can be attacked in this way. If you're on a secure network and can guarantee that your site isn't compromised, and the browser won't be used for other purposes, then-and-only-then you are guaranteed to be safe.
On the other hand, as soon as someone uses that browser to connect to an unknown site, you have opened an attack vector. It's probably best not to mess with that setting, but only you can determine what is best for your specific scenario.


text:
Q: Android - How to access local storage values in WebView? Is it possible to access the Local Storage data from a WebView? Here is a screenshot of Chrome of the values that I am needing to read from my app's WebView. I am needing to get the data from the "Value" column in my app.
What I am trying to do, for example, is go to google.com in my WebView, then read the value "1" from the key "nullctx".

Any help of how to read these values would be appreciated.

A: window.localStorage returns all the values in local storage.
You can print them all to console by `console.log(window.localStorage);
You can use Console APIs in WebView to get the stuff from console
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
  public void onConsoleMessage(String message, int lineNumber, String sourceID) {
    Log.d("MyApplication", message + " -- From line "
                         + lineNumber + " of "
                         + sourceID);
  }
});

You can try with following HTML if you want
`

value read from localstorage:<input type="text" id="test">

value read from localstorage:<input type="text" id="test2">

Open Console to read all values

But this is for things that are stored in your page. You cannot directly read information from other pages in iFrame from different domain. However, if you own all those pages, you can do use info from Cross-Domain LocalStorage.


text:
Q: How can i replace strings in to resource files from web.sitemap and telerik menu for multilanguage support in asp.net(c#) my web.sitemap is
<?xml version="1.0" encoding="utf-8" ?>
<siteMap  xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"  >
  <siteMapNode url="~/Index.aspx?id=Home" title="Dashboard" description="">
    <!-- Catalog Management-->
    <siteMapNode url="~/Index.aspx?id=CategoryHome&category=CatalogManagement" title="Catalog Management" description="">
      <siteMapNode url="~/Index.aspx?id=ProductManager" title="Products" description="">
        <siteMapNode url="~/Index.aspx?id=EditProduct" title="Add Product" description="" />
      </siteMapNode>
      <siteMapNode url="~/Index.aspx?id=Attributes" title="Variations" description="">
        <siteMapNode url="~/Index.aspx?id=AddEditVariation" title="Add/Edit Variations" description="" />
      </siteMapNode>
      <siteMapNode url="~/Index.aspx?id=GiftCertificateManager" title="Generate Gift Cards" description="" />
      <siteMapNode url="~/Index.aspx?id=DepartmentManager" title="Departments" description="">
        <siteMapNode url="~/Index.aspx?id=AddEditDepartment" title="Add/Edit Department" description=""/>
      </siteMapNode>
      <siteMapNode url="~/Index.aspx?id=ManufacturerManager" title="Manufacturers" description="" >
        <siteMapNode url="~/Index.aspx?id=AddEditManufacturer" title="Add Manufacturer" description="" />
      </siteMapNode>
      <siteMapNode url="~/Index.aspx?id=WarehouseManager" title="Warehouses" description="">
        <siteMapNode url="~/Index.aspx?id=EditWarehouse" title="Add Warehouse" description="" />
      </siteMapNode>
    </siteMapNode>

one more XML is there for Telerik menu
<?xml version="1.0" encoding="utf-8" ?>
<PanelItems>
  <PanelItem Text="Dashboard" NavigateUrl="../Index.aspx?id=Home"></PanelItem>
  <PanelItem Text="Catalog Management" NavigateUrl="../Index.aspx?id=CategoryHome&category=CatalogManagement">                  <!--  -->
    <PanelItem Text="Products" NavigateUrl="../Index.aspx?id=ProductManager"/>                          <!-- Product Manager -->
    <PanelItem Text="Variations" NavigateUrl="../Index.aspx?id=Attributes"/>
    <PanelItem Text="Generate Gift Cards" NavigateUrl="../Index.aspx?id=GiftCertificateManager"/>       <!-- Gift Certificate Manager -->
    <PanelItem Text="Departments" NavigateUrl="../Index.aspx?id=DepartmentManager"/>                    <!-- Department Manager -->
    <PanelItem Text="Manufacturers" NavigateUrl="../Index.aspx?id=ManufacturerManager"/>                <!-- Manufacturer Manager -->
    <PanelItem Text="Warehouses" NavigateUrl="../Index.aspx?id=WarehouseManager"/>                      <!-- Warehouse Manager -->
  </PanelItem>
  <PanelItem Text="Customer Management" NavigateUrl="../Index.aspx?id=CategoryHome&category=CustomerManagement">                <!--  -->
    <PanelItem Text="Customers" NavigateUrl="../Index.aspx?id=CustomerManager" />
    <PanelItem Text="Export Subscribers" NavigateUrl="../Index.aspx?id=ExportSubscriptions"/>           <!-- Export Subscribers -->
  </PanelItem>
  <PanelItem Text="Order Management" NavigateUrl="../Index.aspx?id=CategoryHome&category=OrderManagement">                      <!--  -->
    <PanelItem Text="Orders" NavigateUrl="../Index.aspx?id=FindOrders" />                               <!-- Find Orders -->
    <PanelItem Text="Shopping Carts" NavigateUrl="../Index.aspx?id=CartView"/>                          <!-- View Cart -->
    <PanelItem Text="Wish Lists" NavigateUrl="../Index.aspx?id=ViewWishList"/>                          <!-- View Wish List -->
  </PanelItem>

and one more thig is I am using 5 resource file for 5 menus
how to convert XML in to resources

A: I don't know if I fully understand the question. If you want to take these XML and instead of deploying them along with your apllication to have them as a resource in an assembly then you need to do the following:

*

*select the file in the Solution Explorer

*open Properties window (F4)

*set Embedded Resource in Build Action

Now your XML is embedded as a resource in your assembly. Now the question is how to access it. For this use the following code:
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("<default namespace.>MyFile.xml");
StreamReader streamReader = new StreamReader(stream);
// now process the stream the way you want -- for example streamReader.ReadToEnd() to get it as a text

There is a good CodeProject article called Embedded resources.


text:
Q: my whole computer is now linked with git trying to link an existing R project MAC Hi I ran into a problem when I tried to link a regular R Project with Git. Here's the break down:

*

*In terminal I managed to find the directory ~cd...

*git init worked

*"git add ." worked but here's where I ran into the problem. Terminal started asking for permissions to access documents, downloads, pictures (Seriously? but why?) and I kept pressing "dont allow". Terminal stopped working and I quit Terminal.

*Then on one of the discussion threads I came across with this link https://happygitwithr.com/existing-github-last.html

*In short I logged-in to my Git Hub account, went to Repo, and uploaded the R Project that was not under version control. Upload was successful but nothing changed in R Studio. So I restarted R Studio and viola, there is "Git" Tab in environment window. Now the bigger problem!

*When I clicked the Git tab I could see my directory for pictures, downloads, movies basically every major directory on my MAC. Luckily my repo is private so hopefully no one will be able access pictures and what not. No sure how much of it has been put on the repo. On Git Hub I could only see my newly uploaded RProj and R Scripts from the past

Why did it happen? and what do I do next? Any thoughts, comments?
Screenshot of RStudio;

A: It all depends where you did git init .
If you did it in ~ ($HOME, that is /home/<you>), meaning if you see a /home/<you>/.git/ folder, that would explain why Git had to access all those directories (Pictures, Music, ...)
Simply remove that folder, and do a git init . in the actual folder where you have your R project.


text:
Q: true/false vs int in JavaScript (unexpected behavior) I'am kind of new to javascript and today I was working on a function that basically toggles a value and displays it as alert but I stumbled across a weird behavior of JavaScript relating to true/false and 0/1.
The following code , when user clicks on toggle anchor link, it doesn't seem to toggle the value and the alert always gives "true" (which i thought should happen):
document.body.innerHTML = ' toggle '+ document.body.innerHTML;
function f() {
    this.status = true;
    var btn = document.getElementById("toggle")
    btn.addEventListener("click", () => {
        if (this.status == true) {
             alert(this.status)
            this.status = false;
        } else {
            alert(this.status)
            this.status = true;
        }

     }, false)
}

f()

But if I use 0 and 1 instead of true/false the code works for some reason.
document.body.innerHTML = ' toggle ' +document.body.innerHTML;

function f() {
    this.status = 1;
    var btn = document.getElementById("toggle")
    btn.addEventListener("click",()=>{
    if(this.status==1){
         alert(this.status)
         this.status = 0;
    }else{
        alert(this.status)
        this.status = 1;
      }

     },false)
 }

 f()

I have no idea what's going on here, Is this because of this pointer i am using in the function or something?.

A: The problem is that your function f is called without new so the this refers to the window object, which already has astatus property with its own meaning.
You can see this if you print its type:

function f() {
    this.status = true;
    console.log(typeof this.status);
 }

 f()

Note how the result is string instead of the expected boolean.
But if you name it differently:

function f() {
    this.myprop = true;
    console.log(typeof this.myprop);
 }

 f()

It yields the correct type.
So to make it work you need only to change its name. But the if else logic you have to invert the boolean can be turned into a !(not), which simplifies the code a lot:

document.body.innerHTML = ' toggle ' + document.body.innerHTML;

function f() {
  this.myStatus = true;
  var btn = document.getElementById("toggle");

  btn.addEventListener("click", () => {
    this.myStatus = !this.myStatus; //here the value is inverted only with the ! (not)
    console.log(this.myStatus);
  }, false);
}

f();

But using the window object is discouraged, for reasons much like the one you were experiencing, and the myStatus property is still being stored there.
You can improve the solution a bit more:

document.body.innerHTML = ' toggle ' + document.body.innerHTML;

function f() {
  let myStatus = true;
  var btn = document.getElementById("toggle");

  btn.addEventListener("click", () => {
    myStatus = !myStatus; //here the value is inverted only with the ! (not)
    console.log(myStatus);
  }, false);
}

f();

Also, don't forget to finish the statements with the semicolons, i noticed that you had almost none of them.

A: Since you're new to JavaScript you probably haven't heard, but you should know when to use === instead of == (hint: always).
In a nutshell, because JavaScript is weakly/un-typed it can be difficult to know if you're actually comparing two of the same thing (numbers) or two different things (number and object):
new Number(10) == 10 // true
new Number(10) === 10 // false

Because:
typeof Number(10) // returns number
typeof 10 // returns number
typeof new Number(10) // returns object

^ Above example from https://coderwall.com/p/bqurhg/why-always-use-in-javascript

A: Other people have posted some good responses, but here's my two cents.
You can initialize a local variable in your function that will initialize a value and then alternate on that value when the button is clicked. Your use of this notation does not seem to be necessary here.
document.body.innerHTML = ' toggle '+ document.body.innerHTML;
function f() {
    var status = true;
    var btn = document.getElementById("toggle")
    btn.addEventListener("click", () => {
        if (status === true) {
            alert(status)
            status = false;
        } else {
            alert(status)
            status = true;
        }

     }, false);
}

f();

When using this, always know what you are referring to. As Isac pointed out, your this referred to the document window, which seems to have been an issue.
Codepen:
https://codepen.io/foozie3moons/pen/gGRBxZ?editors=0010

A:

document.body.innerHTML = ' toggle '+ document.body.innerHTML;
function f() {
    let status = true;
    let btn = document.getElementById("toggle");
    btn.addEventListener("click", () => {
        if (status === true) {
            alert(status);
            status = false;
        } else {
            alert(status);
            status = true;
        }

    }, false)
}

f();


text:
Q: Filtering row values in pandas by threshold value I have a pandas correlation matrix dataframe that has hundreds of columns and rows. I want to filter the whole dataframe so that i only get cells that are above a certain value, any row value > .4, for example. I'm not sure what is the best way to do that. I've seen multiple posts that filter by column name, but with hundreds of columns, how would you iterate through each column?

A: If want filter only rows use boolean indexing with mask created by gt > with any for check at least one True:
df[df.gt(.4).any(axis=1)]

Or if want filter rows and columns:
m = df.gt(.4)
df.loc[m.any(axis=1), m.any()]

If want only values by condition is possible use where for replace another values  to NaNs:
df.where(df.gt(.4))

Sample:
np.random.seed(4137)
df = pd.DataFrame(np.random.rand(5,3), columns=list('ABC'))
df['A'] /=  10
print (df)
          A         B         C
0  0.090262  0.313517  0.319292
1  0.086841  0.346788  0.314144
2  0.044069  0.764295  0.886659
3  0.089739  0.230103  0.594301
4  0.047101  0.132819  0.692846

df1 = df[df.gt(.4).any(axis=1)]
print (df1)
          A         B         C
2  0.044069  0.764295  0.886659
3  0.089739  0.230103  0.594301
4  0.047101  0.132819  0.692846

m = df.gt(.4)
df2 = df.loc[m.any(axis=1), m.any()]
print (df2)
          B         C
2  0.764295  0.886659
3  0.230103  0.594301
4  0.132819  0.692846

df3 = df.where(df.gt(.4))
print (df3)
    A         B         C
0 NaN       NaN       NaN
1 NaN       NaN       NaN
2 NaN  0.764295  0.886659
3 NaN       NaN  0.594301
4 NaN       NaN  0.692846

Detail:
print (m)
       A      B      C
0  False  False  False
1  False  False  False
2  False   True   True
3  False  False   True
4  False  False   True

print (m.any(axis=1))
0    False
1    False
2     True
3     True
4     True
dtype: bool

print (m.any())
A    False
B     True
C     True
dtype: bool


text:
Q: c# How to upload multiple files to SQL Server database? Given:

*

*c# WinForms application

*more than 1000 .txt, .pdf, .doc files

*SQL Server 2008 table
create table docs
(
    id int not null identity primary key,
    filename nvarchar(255),
    filecontent varbinary(MAX),
    filetype nvarchar(10),
)

I know how to upload file by file using INSERT or MERGE, but it is a long operation.
How to effectively fast upload many files into the table?

A: use SqlBulkCopy operation so that you can insert multiple records faster.


text:
Q: Android Failure [INSTALL_FAILED_UID_CHANGED] after adb tries to uninstall Many times during developing, I will be on an older branch that has a higher version number of the app that I'm developing. Thus, when I run my code on my device, adb will try to uninstall the app (with the higher version) to install my working branch (which has a lower version).
After adb tries to do this, I often get the error INSTALL_FAILED_UID_CHANGED. I assume this is due to adb screwing up the uninstall somehow, and now the phone thinks there is already a version of the app installed? Either way, after this I have to reset my phone in order for my app to be installed again.
I've looked up some solutions to this problem, but all of them seem to rely on the fact that the phone is rooted and that you have root access. Is there any way to solve this problem without root access?


text:
Q: Euler equation and conservation of angular momentum (rigid body) I am a beginner in this field.
Just ask a simple question which confuses me.
Please consider the following:

*

*Conservation of angular momentum about fixed point $o$: $\dot{H}_o = M$.
$M$: the total external torque applied to the body about $o$.

*Euler equation: $I\dot{\omega}+\omega\times  I \omega = M$.
$I$: moment of inertia in matrix form (suppose diagonal $I$ for simplicity.)

My question:  If there is no external torque ($M=0$), then from 1., we know $\dot{H}_o=0$ and by $H=I\omega$, we know $\dot{\omega}=0$ (Due to rigid body, $I$ is constant).
However, by 2., if $M=0$, $I\dot{\omega}=-\omega\times  I \omega $.  So $\dot{\omega}\ne 0$.
It confuses to me.  Where am I wrong?

A: The first equation is valid in the space frame of reference while the second one (Euler's equation) is valid in the body frame of reference.
So, in the case of zero torque the (physical ie as expressed in space frame of reference) angular velocity vector of a rigid body vector is indeed constant. But $\omega$ in Euler's equations refer to the angular velocity vector expressed in the (moving) body frame of reference. And because the frame of reference is moving the description of the vector is non-constant.


text:
Q: Can document.querySelector() Find an IMG Element According to a SRC FileName (instead of full URL)? I am currently using document.querySelector() to Find an IMG Element on the current page,
via supplying the SRC Attribute's value of that IMG Element.
For example, I use this line:
var E =document.querySelector("img[src='https://images.website.com/folder1/folder2/12345.gif']");

As can be seen, in this example I have the full URL for the Image that is specified in the SRC Attribute,
and I give that full URL to document.querySelector().
I now need to slightly improve this:
There are cases where I only know the Image's File Name,
and the Folders part of the URL may change, and is unknown to me.
So my question is:
Can I use document.querySelector() to Find an IMG Element on the current page,
when I only know the FileName part of the Image's URL?
In the above example, it would mean that I have "12345.gif",
but I don't know the names of folder1, folder2..

A: Attributes can be matched by different signs.
[attr] // attribute itself
[attr=value] // is value
[attr~=value] // contains a word containing value
[attr|=value] // contains a complete word value
[attr^=value] // begins with value
[attr$=value] // ends with value
[attr*=value] // contains a part of value

In your example check for
[src$=12345.gif]


text:
Q: Core Data Update/AppStore update I have an app in the AppStore which includes its own database. This database can be updated by the user.
My question is, if I update with a new version y app, via AppStore, how can I mix old data with new data? I don't need to change the model, only mix data.
Do I need to do a "Lightweight Migration"? Is there any way to mix automatically all data?

A: There are a few answers here about pre-loading data into coreData that might address your question.
You basically want to ship a database (store) with your app. This store will contain "your data". At run-time you merge "your data" with the users data into the apps database. The app can then use the merged data


text:
Q: Template to render is unable to find I know there are similar questions like that, but the errors don't apply to me.
So I'm trying to render a template in my LuckyController.php file which looks like that:
<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class LuckyController extends AbstractController{

    /**
     *
     *@Route("/lucky/number")
     */

    public function number(){

        $number = random_int(0,100);

        return $this->render('lucky/number.html.twig',[
            'number' => $number,
        ]);
    }
}

Then, I have the base.html.twig template that I want to render:
{# templates/lucky/number.html.twig #}
   <h1> Your lucky number is {{ number }} </h1>

This is a part of my file structure that could be eventually relevant:
Project
|
--src
   |
   --Controller
         |
         -- LuckyController.php
--templates
   |
   -- number.html.twig

The problem that I have:

Unable to find template "templates/number.html.twig" (looked into: ~\symfony\Project/templates,
      ~\symfony\Project\vendor\symfony\twig-bridge/Resources/views/Form).

A: you should put your twig file in a subfolder of "templates" and call it "lucky" so the path to your twig template should be: templates/lucky/number.html.twig and not directly under templates
--templates
   |
   -- lucky
       |
       -- number.html.twig


text:
Q: No results found in query I'm trying to modify a field for the the currentUser in Parse. I run the following code and my log keeps returning "no results found". I've logged the ObjectId for reference and verified that it's correct in my database.
ParseQuery<ParseUser> query = ParseQuery.getQuery("User");
          query.getInBackground(ParseUser.getCurrentUser().getObjectId(), new GetCallback<ParseUser>() {
              public void done(ParseUser object, ParseException e) {
                if (e == null) {
                    Log.i("objectId", userObjectId);
                    object.put("instructorId", instructorId.getText().toString());
                    object.saveEventually();
                } else {
                    Log.e("objectId", "Error: " + e.getMessage());
                    Log.i("objectId", userObjectId);
                }
              }
          });
        }
    });

A: Your assumption that the User class has the classname User is probably the issue. Try _User.
BUT, you should really be creating your query as
ParseQuery<ParseUser> query = ParseUser.getQuery();

That way you don't even need to know the classname for the user object.


text:
Q: CUDA - nvcc -G - if not working properly I'm currently working on porting a lava flow model in CUDA (full code on github here: Full source of the CUDA-SCIARA Fv2 lava flow model .
EDIT
In order to reproduce the issue, use the instruction on github README in order to get a dev copy of the project SCIARA_FV2_CUDA_MULTICELLS. Then compile withouth -G option and passing as command line argument -c ../data/2006/PARAMETERS.cfg . (quoted code is at line 260 in this file )
I'm facing a problem with an if construct inside a __device__ function.
Based on the current lava quantity and temperature it computes the new temperature and if it is lower than a constant parameter (the variable d_PTsol=1143.0) the lava is solified.
The problem in the code below is that is works perfectly if I compile with the -G options (for the generation of device code debug infos) but behave wrongly without.
double new_temp = d_computeNewTemperature(sommah,sommath);
if(new_temp <= d_PTsol){
            printf("Solidified %.5f,%.5f\n",new_temp,d_PTsol);
            double newQuote = d_sbts_updated[d_getIdx(row,col,ALTITUDE)]+d_sbts_current[d_getIdx(row,col,THICKNESS)];
            //CODE FOR LAVA SOLIDIFICATION HERE
    }else{
           //there is lava and is not solidified -> activate this cell!
           adjustAdaptiveGrid(row,col);
 }

ouptutting something like this at a certain point of the simulation:
Solidified 1344.68654 1143.00000
Solidified 1343.99509 1143.00000
Solidified 1320.50061 1143.00000
Solidified 1325.53942 1143.00000

To make things more subtle the problem completly disappear if I change the the if condition to a strict inequality if(new_temp < d_PTsol).
Compilation is carried out with the following options and in separate compilation mode
-O3 -Xcompiler -fPIC -std=c++11

and linking using
--cudart static --relocatable-device-code=true -gencode arch=compute_35,code=compute_35 -gencode arch=compute_35,code=sm_35

Has someone faced a similar issue before? Am I doing something wrong?
UPDATE
The problem seem to be somehow related to the translation of the if else construct with the <=  as condition. Translating
if(new_temp <= d_PTsol) {
        //solidification
}else{
        //something else
}

to
if(new_temp <= d_PTsol) {
        //solidification
}
if(!(new_temp <= d_PTsol)){
        //something else
}

makes the code work perfectly.

A: I had an similar issue. My code worked with -G option but not without. I just needed to add -fmad=false and -prec-div=false to the compiler options (for more information see: http://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#options-for-steering-gpu-code-generation).
By default this values are true and optimise your single precision operations, but at the cost of your precision. If you enable debug mode this optimisation will be disabled. I needed exact values, therefore my code worked only with -G. Maybe you have a similar issue. (more information about CUDA floating point precision: http://docs.nvidia.com/cuda/cuda-c-programming-guide/#mathematical-functions-appendix)


text:
Q: how to apply std::setprecision while casting from float to double I have the following float value that is being converted to double
float fVal = 0.0f;
double dVal = static_cast<double>(fVal);

I want to control the number of decimal places that dVal gets. I found std::setprecision. But, all examples demostrate its usage in std::couts.
How can apply std::setprecision here to get 2 or 3 decimal places of precision ?


text:
Q: mouse scrolling I have a mouse "logitech m510", when I scroll on one window (let's say chrome browser) and then I alt tab to another window (let's say VSCODE) the scroll bar at the other window makes a big jump.
This is completely disorienting.
How can I overcome that?
And yes, I tried also an old wired mouse and it happened with it too. And it happened with the prior Ubuntu 22.04 (and I didn't upgrade I installed fresh).
BTW, I'm using the most amazing fresh install of Ubuntu 22.10 (you have to love that Kudu wallpaper)


text:
Q: Custom label for chemical structures I need a custom label for my chemical structures and everything works fine but the label isn't centered. Does anyone know how to center the label?
\documentclass{minimal}
\usepackage{hyperref}

\makeatletter
\newcounter{chem}
\addtocounter{chem}{1}
\newcommand{\chemlabel}[1]{%
  \hypertarget{#1}{\textbf{\number\value{chem}}}
   \protected@write\@auxout{}{\string\newlabel {#1}
   {{\number\value{chem}}{\thepage}{\number\value{chem}}{#1}{}}}%
  \refstepcounter{chem}
}
\makeatother

\usepackage{chemfig}
\begin{document}

\chemname{\chemfig{*6(-=-=-=)}}{Benzen}
\chemname{\chemfig{*6(-=-=-=)}}{\chemlabel{str:benzen}}
\chemname{\chemfig{*6(-=-=-=)}}{\chemlabel{str:benzen1}}
\chemname{\chemfig{*6(-=-=-=)}}{\chemlabel{str:benzen2}}
\chemname{\chemfig{*6(-=-=-=)}}{\chemlabel{str:benzen3}}

\end{document}

A: You need some % at the end of lines in your definition of \chemlabel otherwise the ends of lines appear as spaces:
\documentclass{article}
\usepackage{hyperref}

\makeatletter
\newcounter{chem}
\addtocounter{chem}{1}
\newcommand{\chemlabel}[1]{%
  \hypertarget{#1}{\textbf{\number\value{chem}}}% <<<<
   \protected@write\@auxout{}{\string\newlabel {#1}
   {{\number\value{chem}}{\thepage}{\number\value{chem}}{#1}{}}}%
  \refstepcounter{chem}% <<<<
}
\makeatother

\usepackage{chemfig}
\begin{document}

\chemname{\chemfig{*6(-=-=-=)}}{Benzen}
\chemname{\chemfig{*6(-=-=-=)}}{\chemlabel{str:benzen}}
\chemname{\chemfig{*6(-=-=-=)}}{\chemlabel{str:benzen1}}
\chemname{\chemfig{*6(-=-=-=)}}{\chemlabel{str:benzen2}}
\chemname{\chemfig{*6(-=-=-=)}}{\chemlabel{str:benzen3}}

\end{document}

BTW: do you know chemnum?


text:
Q: How can I reinit or clear google maps infowindow cache I have created a nested carousel inside of a gmaps infowindow, the top level carousel keeps track of all of the nested slides. It works perfect on the first infowindow instance, but when I click another marker and when the next infowindow opens the count is based off of the previous infowindow..
is there a way to destory the last instance of the infowindow?

A: Fixed the issue, had to change the event listener to just addListenerOnce.


text:
Q: Get device name via telnet emulated application (Delphi console), is it possible? I have an application written in Delphi console that runs on data collectors, this application is called via telnet (terminal emulation).
Is there any way for my application to capture the name of the device that is emulating it?
Example:
The collector name that is registered in the windows registry is "DT-XXXXX"
And is written to the following windows registry HKEY_LOCAL_MACHINE \ Ident \ Name
Is it possible to capture this information by an emulated application like mine?