text:
Q: mysql permanently prepared statements i am looking to accelerate some queries using prepared statements on a high traffic site. what i don't think i'm understanding correctly is the benefit from using prepared statements unless they can stay prepared over multiple connections. it looks like this is not possible with PDO which also does not allow persistent connections. but the persistent connection functions don't allow PDO.
lets say for arguments sake i am running a query 5,000 times per second:
SELECT * FROM some_table WHERE some_column LIKE 'some_value'
from what i understand, PDO would prevent mysql from re-compiling and evaluating the query if i were to change "some_value" each time i needed to query. i also understand that "some_value" could be transmitted in binary instead of ASCII to save bandwidth, but it wouldn't be saving much if i had to send the entire query each time i open the connection.
also from what i have read, stored procedures are not the solution, because those do not stay compiled through multiple connections either.
is there any solution to this problem? storing a prepared statement on the server somewhere and having it stay compiled in memory and ready to fire as soon as it receives the variables?
is there any way to make this happen by combining connection pooling with PDO? (although i have also heard connection pooling is not ideal because it can cause blocking in certain conditions)

A: After running numerous benchmarks, we found that prepared statements prepared on the server provided us the greatest speed benefits. Here's an example:
DROP PROCEDURE IF EXISTS get_user;

DELIMITER //

CREATE PROCEDURE get_user(IN v_user VARCHAR(255))
DETERMINISTIC
READS SQL DATA
SQL SECURITY INVOKER
COMMENT ''
proc: BEGIN
    SET @user = v_user;

    IF ISNULL(@get_user_prepared) THEN
        SET @get_user_prepared = TRUE;

        SET @sql = "SELECT * FROM mysql.user WHERE user = ?";

        PREPARE get_user_stmt FROM @sql;
    END IF;

    EXECUTE get_user_stmt USING @user;
END;
//

DELIMITER ;

A: Using prepared statements with MySQL isn't likely to make your queries much faster, and it prevents the query cache from working too.  You need some caching in front of your database if you really need to run the same query 5k/s. Memcached is popular, as is Redis.  Depending on what you're doing, caching elements or the whole page might be an option too.

A: Nope, there is no way to use persistent prepared statements.
However, there is an ideal solution for the query running 5,000 times per second - Handlersocket


text:
Q: WinForm App not working on others computer I have created a simple clone FM Radio from http://csharptutorialsfree.blogspot.my/2013/10/c-radio-streaming-bug-fixed.html
But there is one problem :
When I published / deploy my radio followed exactly from this tutorial https://www.youtube.com/watch?v=USfQzZX-ytQand
When I run my radio app on others computer(which doesn't have visual studio installed). Windows Media Player inside my application not working(doesn't produce any stream music). But it's works on my work computer(That has Visual Studio installed).
Can anyone help me with this, Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Paypal digit goods flow dialog - prevent refresh I'm using Paypal digit goods flow to get the integrated payment dialog into my site. When user open the dialog and they clicks cancel, it seems PayPal forces a refresh. Same thing happens when they complete the purchase.
Is there any way to prevent this? I'm also using Google Wallet which does not do this because it's terrible for user experience and I have to worry about preserving the state of the page now.


text:
Q: .htaccess rewrites are conflicting / pretty urls I have a website where the url looks like this:
example.com/sample?m=1389&t=name-title
but I want it to look like this:
example.com/1389/name-title
I think two of the rewrites are conflicting. The top one is to remove the .php off of every page and the second one is to make the sample.php more seo friendly. Here's my whole htaccess code. Let me know what I'm doing wrong. I don't want file extensions and I want my page urls to look really nice. Thank you.
Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

# Remove www from any URLs that have them:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

Options All -Indexes

ErrorDocument 403 http://example.com/tapes.php
ErrorDocument 404 http://example.com/404

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 month"
ExpiresByType image/jpeg "access 1 month"
ExpiresByType image/gif "access 1 month"
ExpiresByType image/png "access 1 month"
ExpiresByType text/css "access 1 week"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/x-javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
ExpiresByType image/x-icon "access 1 month"
</IfModule>
## EXPIRES CACHING ##

# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

# Or, compress certain file types by extension:
<files *.html>
SetOutputFilter DEFLATE
</files>

RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)\.html$ /sample?m=$1&t=$2 [L]

A: You can use that in your root .htaccess:
Options +FollowSymlinks -MultiViews -Indexes
RewriteEngine on
RewriteBase /

# Remove www from any URLs that have them:
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

# remove php
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L]

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+sample\?m=([^&]+)&t=([^\s&]+) [NC]
RewriteRule ^ /%1/%2? [R=301,L,NE]

# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(\d+)/([^/]+)/?$ sample.php?m=$1&t=$2 [L,QSA,NC]

# add php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

ErrorDocument 403 http://example.com/tapes.php
ErrorDocument 404 http://example.com/404


text:
Q: Discord bot profile application How to create an application on the user's profile with pycord(https://i.stack.imgur.com/vmt03.jpg)](https://i.stack.imgur.com/kMRc7.jpg)
I searched but did not find anything

A: Actually this is happens only mobile view.
What is causing this is "user.command".
@bot.user_command(name="name")
async def name(ctx, user: discord.Member):
    await ctx.respond(user.name)


text:
Q: Reviewing a First Answer with red flags leads to "Possible spam" notice shown for question There is a First Answers review item about a (questionable) answer that received four (still pending) rude/abusive flags. That leads to the familiar notice

Our system has identified this post as possible spam; please review carefully

but it's shown on the Question tab, rather than where it belongs, the Answer tab. I checked the question but it did not have any disputed or declined spam flags.


text:
Q: Why these random variables in bounded difference concentration inequality are bounded and with ranges $c_i$? When I read the proof of bounded difference concentration inequality, I have this question.

Part of proof is in the follwing:
.

Now, my question is why $\xi_i$ conditioned on $X_1,...,X_{i-1}$are bounded?

The following is my try:

Proof: We know $\xi_i|x_1,...,x_{i-1}=\mathbb{E}_{X_{i+1},...,X_{n}}[f(x_1,...,x_{i-1},X_i,...,X_{n})]-\mathbb{E}_{X_i,...,X_n}[f(x_1,...,x_{i-1},X_i,...,X_n)]$, and the term on the most right is a constant in this case, so we can continue the equation by equal$\mathbb{E}_{X_{i+1},...,X_n}[f(x_1,...,x_{i-1},X_i,...,X_n)-\mathbb{E}_{X_i,...,X_n}[f(x_1,...,x_{i-1},X_i,...,X_n)]]$. And from this, I cannot go on.

This pdf file is from Chi Jin's lecture note on machine learning theory.machine learning lecture notes


text:
Q: Script to compare dates I would like to compare an elastic search date with a format YYY-MM-DD HH:MM:SS as to compare the results of the past 30 days. So if the given date is equal to NOW()-30D it should give me the result wanted.
I have tried comparing it this way with a script but it doesn't work :
getMillis(doc["date"].value) >= (new Date().getTime() - 30 * 24 * 60 * 60 * 1000)  ? 1 : 0
Another test not working :
$total= new \Elastica\Aggregation\Sum('total');
$total->setScript('doc["date"].value >= (new Date().getTime() - 30) ? 1 : 0');

This should do this : If doc["date"].value is higher or equal to the last 30 days it should give me 1, else it would give me 2.
How can I achieve that? Knowing that I'm using groovy scripting.

A: The script you're looking for looks like this:
ChronoUnit.DAYS.between(Instant.ofEpochMilli(doc['date'].date.millis), Instant.ofEpochMilli(new Date().getTime())) > 30 ? 0 : 1

We compute the number of days between the date field and now. If the number of days is bigger than 30, we return 0, otherwise we return 1.

A: You achieve same using range query or date range aggregation, I suggest not to use the script with elastic search unless and until it is difficult to get the result using search query


text:
Q: Is Map.containsKey() useful? I'm wondering, does it make any sense to check for a particular key before trying to access it. Example:
Map myMap ....
if myMap.containsKey(key) {
   Object value = myMap.get(key);
   .....
}

Example of not using containsKey:
Object value = myMap.get(key);
if (value != null) {
 ......
}

EDIT: to clarify on null keys and values. Let's say, that map doesn't allow null keys and null values, so this two examples be identical.

A: In case your map allows for null values, with just get(key) you can't differentiate between key/value pair that has value = null and "no matching key/value pair exists".

A: Yes - keys can have null values:
Map myMap = ...;
myMap.put("foo", null);
if (myMap.containsKey("foo")) {
   Object value = myMap.get(key); // value is null
}

Object value = myMap.get("foo");
if (value != null) {
    // you won't get here
}

You could argue (and I'd agree) that not distinguishing a null value from a non-existent entry was a pretty bad design decision when they first made Java's collection API.
(Some maps - Hashtable and ConcurrentHashMap, at least - don't allow null values, which makes containsKey less important there, but it's still a nice readability improvement over m.get(k) == null.)

A: Yes it is useful - especially if your Map allows null values...
@Test
public void testContainsKey() {
    Map<String, Object> strObjMap = new HashMap<String, Object>();
    strObjMap.put("null", null);

    assertTrue(strObjMap.containsKey("null"));
    assertNull(strObjMap.get("null"));
}


text:
Q: Toggle script: change from jQuery to "normal javascript" code I've been using a toggle script (open/close text container when clicking on a certain link) for a website that uses jQuery. In order to clean up the website I want to get rid of jQuery completely but have some problems converting the existing jQuery code into "normal javascript".
Here is the existing code:
jQuery(function($){
$(document).ready(function(){
    $(".toggle_container").hide();
    $("h4.trigger").click(function(){
        $(this).toggleClass("active").next().slideToggle("normal");
        return false; //Prevent the browser jump to the link anchor
});
});
});

Which corresponds to this HTML source code:

Click to show more

Hidden Text

I've tried the following code which doesn't give me an error but just doesn't do anything when clicking on the trigger:
var el = document.querySelectorAll('h4.trigger');
for(var i=0; i < el.length; i++){
    el[i].addEventListener('click', function () {
        this.classList.toggle("active").nextSibling.classList.toggle("toggle_container-active");
    }.bind(this));
}

The only thing I really need for the code is: clicking on the class "trigger" should toggle some HTML class "active" to both the trigger element as well as the toggle_container element. The rest I'm able to change with just CSS.
The hard part of the code is that it should work for multiple toggle areas on one page separately (therefore using a class, not an id).
Any idea where my code has a problem or any (completely) different suggestions?
I have very limited experience with javascript/jQuery and feel more at home with HTML/CSS.
Thanks,
Patrick

A: The this.classList.toggle("active") doesn't return the element back again, but just a boolean to inform if the action was successful. Chaining happens only in jQuery and not in vanilla JavaScript.
this.classList.toggle("active").nextSibling.classList.toggle("toggle_container-active");

You should be using something like this instead of the above:
this.classList.toggle("active");
this.nextSibling.classList.toggle("toggle_container-active");


text:
Q: Проблемы с получением результатов из ThreadPoolExecutor.map Python я уже задавал вопрос в этом посте  Возможно ли ускорить обработку hdf5 файла с помощью threading Python 3.6. Я продвинулся немного дальше, но теперь возникает проблема с получением результатов из map объекта: кажется, что часть данных просто куда-то теряется. Я сначала полагал, что проблема в куске:
    data = np.zeros(shape=((chunkSize,) + dataShape[1:]), dtype=f[data_path].dtype)

    imageNumber_variable = 0
    for imageNumber_file in range(start, end):
        data[imageNumber_variable,] += f[data_path][imageNumber_file,]
        imageNumber_variable += 1

который нужен, чтобы ускорить выгрузку данных из файла (если делать это напрямую - f[data_path][start : start + chunk_size], то занимает в 100 раз больше времени, чем заполнение numpy.array). Поэтому я предполагаю, что проблема кроется в следующей части кода:
with ThreadFuture.ThreadPoolExecutor(max_workers=3) as executor:
    tmp_return = executor.map(processing_chunk, func_arguments)

    for pixel_sum in tmp_return:
        intensity_total += pixel_sum

Привожу также полный скрипт:
#!/usr/bin/env python3
# coding: utf8

import h5py as h5
import numpy as np
import concurrent.futures as ThreadFuture
from itertools import product

chunk_size = 5000

def processing_chunk(file_info):
    filename = file_info[0]
    data_path = file_info[1]
    chunk_start = file_info[2]

    with h5.File(filename, 'r') as f:
        dataShape = f[data_path].shape
        imageCount= dataShape[0]

        start = chunk_start
        end = min(chunk_start + chunk_size, imageCount)
        chunkSize = end - start

        data = np.zeros(shape=((chunkSize,) + dataShape[1:]), dtype=f[data_path].dtype)

        imageNumber_variable = 0
        for imageNumber_file in range(start, end):
            data[imageNumber_variable,] += f[data_path][imageNumber_file,]
            imageNumber_variable += 1

    pixel_sum = np.sum(data, axis=0)

    return pixel_sum

def main(filename, data_path):

    global length
    global intensity_total

    chunk_starts = np.arange(0, length, chunk_size)

    func_arguments = product((filename,), (data_path,), chunk_starts)

    with ThreadFuture.ThreadPoolExecutor(max_workers=3) as executor:
        tmp_return = executor.map(processing_chunk, func_arguments)

        for pixel_sum in tmp_return:
            intensity_total += pixel_sum

if __name__ == "__main__":

    filename = 'test.cxi'
    data_label = '/data/data'

    total_num_patterns = 0

    data_file_shape = (27270, 16, 512, 128)

    intensity_total = np.zeros(data_file_shape[1:])

    length = 27270

    total_num_patterns += length

    main(filename, data_label)

    f_name = 'parallel-av-num-patterns.h5'

    f = h5.File(f_name, 'w')
    f.create_dataset('/data/data', data=np.array([intensity_total / total_num_patterns]))
    f.close()

Буду благодарен за любые замечания/предложения.


text:
Q: USB Format Error I'm having a real headache trying to reformat a USB drive. Initially it had a 200mb EFI partition and it caused the drive to disappear altogether. Since then I ran the CMD and wiped the disk using 'diskpart'. It took a few attempts but it finally cleaned the drive.
Since then it has reappeared under (:E) however I am unable to access the drive and Windows is preventing me from reformatting it. I am just presented with 'Windows was unable to complete the format'. It's now acting like a CD drive instead of removable storage.
I've tried going through Disk Management and I'm presented with the same error. I've removed
the USB controllers from Device Manager - when the drive is connected again it re-installs the drivers and acts the same way.
Any help given will be greatly appreciated, thank you.
(Windows 7 machine)

A: You will need to format the drive with an actual disk management application that will allow you to format the drive.


text:
Q: Constants and independent variables in function definitions I have an equation which I try to plot and work with in Mathematica which is of the form
f(x,y) = (x^2 - a^2)^2 + x^2 y^2

Here x and y are independent variables and a is a constant. What is the standard way of defining a function such as this: should the constants/parameters be present in the list of arguments or should this list just contain the independent variables? Alternatively, should the parameters be present in the argument list but as optional arguments (with default values)?

A: All of those options are possible, and each is reasonable in some circumstance.
Present in the list of arguments:
f[x_, y_, a_] := (x^2 - a^2)^2 + x^2 y^2

Or:
f[a_][x_, y_] := (x^2 - a^2)^2 + x^2 y^2

Only the independent variables:
Globally defined a value
a = 3.14;
f[x_, y_] := (x^2 - a^2)^2 + x^2 y^2

As optional argument
f[x_, y_, a_:3.14] := (x^2 - a^2)^2 + x^2 y^2

You'll need to be more specific regarding your use if I am to provide a more specific answer.  The globally defined a value should be used with caution, but it is certainly not without its place.

A: You could also create yourself a function that generates the the one that you need.
f[a_] := Function[{x, y}, Evaluate[(x^2 - a^2)^2 + x^2 y^2]]

and then use it to generate the function
f[23]

You then could use that
f[23][2, 3]

or store help = f[23] and use
help[2,3]

Hope this helps


text:
Q: Reuse of sockets I have a simple TCP server using the socketserver library. It used to work fine, but now I get this error message whenever I run it:
socket.error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted

Here is the code:
class Handler(socketserver.StreamRequestHandler):
    def handle(self):
        sys.stdout = self.wfile
        self.data = str(self.request.recv(1024).strip(), "utf-8")
        exec(self.data, globals())

    def handle_error(request, client_address):
        print("Quitting...")

if __name__ == "__main__":
    HOST, PORT = "localhost", 5555

    server = socketserver.TCPServer((HOST, PORT), Handler)

    server.serve_forever()

I've tried changing the port, but I get the same error. What is the problem?


text:
Q: Event with cursor not working I am trying to insert a record into one table based on the select query result.
When I am executing a query that time I clearly able to see that record should need to insert into a table as am expecting.
But somehow it's not inserted a record So would like to know, What I miss to add
Snippet Code :
CREATE EVENT event_1 ON SCHEDULE  EVERY 60 SECOND DO
                            BEGIN
                            DECLARE lc_current_time DATETIME;
                            DECLARE unuse_count INT;
                            DECLARE assign TINYINT;
                            DECLARE total_sum INT;
                            DECLARE check_count INT;
                            DECLARE select_cursor CURSOR FOR SELECT count(id) as count,A.assign, B.sum, truncate(B.sum*100.00/100,0) as check_count FROM table1 A INNER JOIN (Select assign, count(id) sum from table1 where cli_group_id = 5 Group by assign) B on A.assign = B.assign WHERE cli_group_id = 5 and field1 ='' Group by field1, A.assign;
                            SET lc_current_time = CONVERT_TZ(NOW(), @@session.time_zone, '+0:00');
                            OPEN select_cursor;
                            LOOP
                            FETCH select_cursor INTO unuse_count,assign,total_sum,check_count;
                            IF unuse_count <= check_count THEN
                                insert into report(triggered_date,alert_id,alert_name,type,status,email,trunk_cli_id,triggered_value,threshold_value) values (lc_current_time,19,'CLI',4,1,'abc@test.com',5,check_count,unuse_count);
                            END IF;
                            END LOOP;
                            CLOSE select_cursor;
                            END

Output of select query :
+-------+-------------+-----+-------------+
| count | assign      | sum | check_count |
+-------+-------------+-----+-------------+
|     8 |           0 |  11 |          11 |
|     2 |           1 |   3 |           3 |
+-------+-------------+-----+-------------+
2 rows in set (0.00 sec)

Problem :
Here from output we can clearly see that count < check_count  so record should have to insert an entry into report table.


text:
Q: Cant find kivy logs when running with Kivy Launcher When running my kivy app on Android Kivy Launcher it crashes instantly. I've looked everywhere for the logs, but couldn't find them. No .kivy folder is created, apps that view android logcat require root access and I couldn't get working adb logcat. Can someone explain to me how to use adb logcat to catch the error, or state another solution to my problem?
PS: The app uses kivy 1.9.1 and py 3.4.4, runs fine on windows and my cellphone is a Xperia Z5 running Android Marshmallow 6.0.1

A: Finally figured out how to use adb logcat. Install android studio 2.2. Connect your device to the PC via USB and enable debugging mode in the developer options. cd in command prompt to C:\Users[user]\AppData\Local\Android\sdk\platform-tools, and run adb devices. If the serial number of your android device appears, you're good to go. Then run adb logcat while executing the kivy app in your phone, and you'll get the realtime logs.


text:
Q: URLSearchParams returning null for the first query string Why is timeperiod null

const url = 'http://example.com?timeperiod=lasttwentyeightdays&pagesize=20'
const args =  new URLSearchParams(url);
alert('timeperiod='+args.get('timeperiod') + ' and pagesize='+ args.get('pagesize'));

But in the below code it works

  const url = 'http://example.com?x=c&timeperiod=lasttwentyeightdays&pagesize=20'
  const args =  new URLSearchParams(url);
  alert('timeperiod='+args.get('timeperiod') + ' and pagesize='+ args.get('pagesize'));

A: You need to create a URL object and then retrieve the params with url.search:
See

const url = new URL('http://example.com?timeperiod=lasttwentyeightdays&pagesize=20');

const args =  new URLSearchParams(url.search);

console.log(`timeperiod=${args.get('timeperiod')} and pagesize=${ args.get('pagesize')}`);

A: one liner with slight changes for ES6,
const caller = new URLSearchParams(URL(decodeURIComponent(import.meta.url)).search).get('pagesize');


text:
Q: Gorm Golang fetching a collection and its relationships I recently started using Golang and decided to give GORM a try as an ORM.
It works pretty well on most things, but as most ORMs are sometimes it's limited. Luckily it ties very well into database/sql so I can do custom queries easily.
I'm wondering if there is any other way to do this in gorm:
I have a struct Companies, Companies have one to many relationships w/ emails, addresses, and phones.  I use the following code in gorm to pull a list of companies and their corresponding info.   I use gorm's Preload function.
db.DBAccess.
    Model(&companies).
    Count(&dbInfo.Count).
    Order("companies.id asc").
    Offset(offset).
    Limit(length).
    Preload("Addresses").
    Preload("Phones").
    Preload("Emails").
    Find(&companies)

This works perfectly fine. However I feel like there is another way to accomplish this without the Preload function. Any ideas?

A: You can load the related entities later (only when/if needed), using DB.Related as shown in the documentation :
// User has many emails
db.Model(&user).Related(&emails)
//// SELECT * FROM emails WHERE user_id = 111;
// user_id is the foreign key, 111 is user's primary key's value

// Specify the foreign key
db.Model(&user).Related(&emails, "ProfileId")
//// SELECT * FROM emails WHERE profile_id = 111;
// profile_id is the foreign key, 111 is user's primary key's value

I do not see another way in the documentation.


text:
Q: EF EntityState.Modified Try Catch Issue I have a code like this:
try
{
    Member member = database.Members.Where(m=>m.ID=1).FirstOrDefault();
    member.Name = "NewMemberName";
    database.Entry(member).State = EntityState.Modified;
    database.SaveChanges();
 }
 catch (Exception ex)
{
    database.Logs.Add(new Log() { Value=ex.ToString() });
    database.SaveChanges();
}

And Entity:
[StringLength(5)]
public string Name { get; set; }

If the Name String more than 5 it would be error and catch the exception ,but when I add a log then save ,the exception from SaveChange(); still remains,how should I do?(Can't change the schema)

A:
the exception from SaveChange(); still remains

Well, if this throws an exception:
database.SaveChanges();

Then there's a pretty good chance that this will also throw an exception:
database.SaveChanges();

Basically, in your catch block you shouldn't be immediately re-trying the operation that just failed a millisecond ago.  Instead, log the failure and handle the exception:
catch (Exception ex)
{
    // DO NOT call SaveChanges() here.
}

Of course, if writing to the database is failing, then logging to the database is also likely to fail.  Suppose for example that the connection string is wrong or the database is down or timing out.  You can't log that.
I recommend using a logging framework (log4net, NLog, etc.) as a separate dependency from your Entity Framework data access layer.  It's a small learning curve, but you end up with a pretty robust logging system that can much more effectively handle problems.  And can be easily configured to log to multiple places, so if writing to one error log (the database) fails then you still have another one (a file, for example).
At the very least, if persisting your data context fails, you'll need to log to a new data context.  Otherwise the part that failed is still there.
Something structurally more like this:
try
{
    using (var database = new DbContext())
    {
        Member member = database.Members.Where(m=>m.ID=1).FirstOrDefault();
        member.Name = "NewMemberName";
        database.Entry(member).State = EntityState.Modified;
        database.SaveChanges();
    }
}
catch (Exception ex)
{
    using (var database = new DbContext())
    {
        database.Logs.Add(new Log() { Value=ex.ToString() });
        database.SaveChanges();
    }
}


text:
Q: Trying to take a screenshot to camera roll without a navigation/status bar in the image - Swift 3, Xcode 8, IOS Using: Swift 3, Xcode 8, IOS
My screenshot works fine, I just need to omit the navigation bar from the image in my camera roll. This is what I have so far:
@IBAction func buttonAction(_ sender: UIButton) {

UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
}

A: Simply cropping out the status bar before saving would seem like the ideal solution. Here is another post with someone doing this.


text:
Q: Unable to access HTTPS service using Spring Rest Template - TrustStore issue? While accessing a HTTPS service I am facing the below issue :
Error:
..Certification authentication failed</TITLE>
...
An attempt to authenticate with a client certificate failed.
A valid client certificate is required to make this connection.
I am using Spring RestTemplate excahnge API :
restTemplate.exchange(reqInfo.getUrl(),HttpMethod.GET,requestEntity,String.class);
I tried 2 methods to provide the trustStore but still the error persists:
1.) Passing as arguments :
java -cp -Djavax.net.ssl.trustStore="trustStore.jks"
-Djavax.net.ssl.trustStorePassword="pwd"  Test
2.) Setting the property
System.setProperty("javax.net.ssl.trustStore","path to truststore");
System.setProperty("javax.net.ssl.trustStorePassword","pwd");
Also I tried with  simple Java code using HTTPclient then it works fine but with SPring RestTemplate none of option is working , am i missing something here ?
Note :  If I do curl of that URL I get the same error as truststore is not provided . Hence I am assuming that this issue is due to TrustStore.

A: Finally I was able to solve the above issue .
While building the SSL context I did not load the key store ( although I was passing it via arguments) due to which I was getting Certification authentication failed as the Key store was not available .
Below code fixed the issue : (added loadKeyMaterial )
sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
                            .loadKeyMaterial(keyStore, keyStorePwd).build();


text:
Q: list all images in directory in JSON I need away to list all images in a directory in a CLEAN json format. I need it to look like this:
URLLINK:"image of where the image is"

That is all I need.

A: $files = array();

$dir = opendir('/tmp');
while ($file = readdir($dir)) {
    if ($file == '.' || $file == '..') {
        continue;
    }

    $files[] = $file;
}

header('Content-type: application/json');
echo json_encode($files);

Something like this.
You can convert it in any structure you want

A: A one line code would be:
echo json_encode(glob("*.{jpg,gif,png}", GLOB_BRACE));

References:

*

*PHP: glob

*Glob Patterns for File Matching in PHP


text:
Q: Unusual error message - sql server the row object is inconsistent. please rerun the query I'm reviewing the error logs for an instance of SQL Server 2012 and found the following error in the log (error 669):
The row object is inconsistent. please rerun the query

I googled and the only answers seem to be generic listings of sys.messages showing the error number and error description.
Has anyone come across this error before? My thoughts so far is it indicates some kind of data corruption, but the error message doesn't say which database is affected.

A: As a first step, I'd suggest running DBCC CHECKDB against all databases on that instance.  Here's a quick script that will run against each database (including system databases).  This could take quite a bit of time (depending on the size of your databases), but you need to let it finish running.
DECLARE @Message VARCHAR(max);
DECLARE @databaseList AS CURSOR;
DECLARE @databaseName AS NVARCHAR(500);
DECLARE @tsql AS NVARCHAR(500);

SET @databaseList = CURSOR  LOCAL FORWARD_ONLY STATIC READ_ONLY
FOR
        SELECT QUOTENAME([name])
        FROM sys.databases
        WHERE [state] = 0;
OPEN @databaseList;
FETCH NEXT FROM @databaseList into @databaseName;
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @Message = 'Starting DBCC for ' + @databaseName + ' -> (' + convert(varchar,getdate(),121) + ')'
    RAISERROR(@Message,0,1) WITH NOWAIT
    SET @tsql = N'DBCC CheckDB(' + @databaseName + ') WITH ALL_ERRORMSGS,NO_INFOMSGS;';
    RAISERROR(@tsql,0,1) WITH NOWAIT
    exec SP_EXECUTESQL @tsql;
    SET @Message = 'Completed DBCC for ' + @databaseName + ' -> (' + convert(varchar,getdate(),121) + ')'
    RAISERROR(@Message,0,1) WITH NOWAIT

    FETCH NEXT FROM @databaseList into @databaseName;
END
CLOSE @databaseList;
DEALLOCATE @databaseList;

A: Got the same error, used DBCC to Check the tables concerned and nothing was reported.
In the end we had to rebuild the indexes on 1 of the tables to rectify the problem.
Gary

A: The issue may be because the subquery is returning duplicate records.
For example: in the below sub query if the Employee table has duplicate IDs then this issue can happen
DELETE
FROM   employee
WHERE  id IN (SELECT TOP 1 id
              FROM   Employee
              WHERE  NAME IN (SELECT NAME
                              FROM   employee
                              GROUP BY
                                     NAME
                              HAVING COUNT(*) > 1))


text:
Q: How to create a new tab in products in Magento admin panel I just started to work with Magento. Cool thing. But I think I jumped in the middle of it so fast. However, I've been asked to create a new tab called Promotions when adding a Product. It will then have an option field (named "Is Featured") and it has values of "Yes" or "No" in form of a dropdown.
I am familiar with the structure of Magento, but I can't find where I can do the changes.
I'm using Magento 1.9.2.3 Full release.
I made an image for you guys to understand what I want better.
What should I do?!

A: You will have to first create the attribute:

*

*open Catalog > Attributes > Manage Attributes

*click on Add New Attribute

*create a new boolean attribute (chose Yes/No in "Catalog Input Type for Store Owner") and fill the other fields

Then add the attribute to the Promotions group:

*

*open Catalog > Attributes > Manage Attribute Sets

*chose the attribute set you are going to use for this product

*add a new "Group" to the column on the left with the Add New button (in this case, name it "Promotions")

*drag and drop the newly created group to the position you'd like it to be

*drag and drop the newly created attribute from the right column to the left one, under the Promotions group

A: In the installer of any of your suitable extension, add an attribute to the product with a new group, and they will be displayed there.
$installer = $this;
$installer->startSetup();

$installer->addAttribute('catalog_product', 'is_featured',
    array(
        'group'            => 'Promotions',
        'type'             => 'int',
        'backend'          => '',
        'frontend'         => '',
        'label'            => 'Is Featured',
        'input'            => 'select',
        'class'            => '',
        'source'           => 'eav/entity_attribute_source_boolean',
        'global'           => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE,
        'visible'          => true,
        'required'         => false,
        'user_defined'     => false,
        'default'          => '',
        'searchable'       => false,
        'filterable'       => false,
        'comparable'       => false,
        'visible_on_front' => false,
        'unique'           => false,
        'sort_order'       => 60
    ));

$installer->endSetup();

It will look like that:
https://gyazo.com/9a0e423d0c3e78e7c440b5cd79a3e547
Tweak attribute settings according to your requirements.


text:
Q: Alternate indentation display in Vim I came across this question:
https://softwareengineering.stackexchange.com/questions/87077/how-can-a-code-editor-effectively-hint-at-code-nesting-level-without-using-inde
and thought that Vim might be able to do something similar as well with a plugin.
I believe the indentation level could be indicated with the a sign (icon in GUI, text with highlighting in term).  The piece I'm not sure about is displaying the lines without indentation.  Does anyone know, is it possible and/or how you would do it?
This question is not whether or not displaying indentation levels in this manner is desirable; but how to accomplish it in Vim.

A: You could use the conceal feature that is new in 7.3.
Here is a function that does roughly what the article is describing (for spaces; accounting for tabs instead would be a fairly trivial addition):
function! IndentationHeatMap()
    set conceallevel=1
    for i in range(1,9)
        let indentation = repeat(" ", &sts * i)
        exe 'syntax match NonText "^' . indentation . '" conceal cchar=' . i
    endfor
endfunction

A solution closer to what you are requesting might use conceal to hide all leading whitespace with

syntax match NonText "^\s\+" conceal

and then use signs to provide the indicators based on custom calculations.
Note: NonText in these syntax commands is an arbitrary highlight group.

A: Take a look at these plugins: Indent Guides and IndentHL
Both have screenshots.


text:
Q: Does every hyperplane have a unique normal vector (up to non-zero scalar multiplication)? I am able to prove that the conjecture below is true in the $\mathbb{R}^3$ case, but I was wondering if the general case is true and if it is, how we might (nicely) prove it.
Conjecture. Suppose $p$ is a hyperplane in $\mathbb{R}^{n}$. Then $p$ has a normal vector and moreover, this normal vector is unique (up to non-zero scalar multiplication).

My definitions:
Definition 1. Given $\mathbf{x}=\left(x_1,x_2,\dots,x_n\right)$ and $\mathbf{y}=\left(y_1,y_2,\dots,y_n\right)$, we define: $$\mathbf{x}\cdot \mathbf{y}=\sum_{i=1}^n x_i y_i.$$
Definition 2. A hyperplane in $\mathbb{R}^{n}$ is any set of points that can be written as $$\left\{ \mathbf{x}\in\mathbb{R}^{n}:\mathbf{a}\cdot\mathbf{x}=c\right\},$$ for some $\mathbf{a}\in\mathbb{R}^{n}\setminus\left\{ \mathbf{0}\right\} $ and some $c\in\mathbb{R}$.
Definition 3. We say that $\mathbf{b}=\left(b_{1},b_{2},\dots,b_{n}\right)\neq\mathbf{0}$ is a normal vector of the plane $p$  if: $$\mathbf{x},\mathbf{y}\in p \implies \mathbf{b}\cdot\left(\mathbf{x}-\mathbf{y}\right)=0.$$
Related.

A: Short answer, yes.
In fact your "definition 2" gives $\mathbf a$ as the coefficients of the equation of a hyperplane as a nonzero vector, and this nonzero vector is a normal to that hyperplane as called for in "definition 3".
The algebra to prove this is very easy.  Write down the equations, satisfied by $x$ and $y$ of the hyperplane respectively, and take the difference.  We immediately have $\mathbf a \cdot (x-y) = 0$ as the constant $c$ cancels.
The argument goes the other way, to show that when $\mathbf b$ in "definition 3" is given, it also serves as a set of coefficients $\mathbf a$ in "definition 2".  That is, suppose a hyperplane $p$ has a normal vector $b$ as described above, and fix some point $y$ in that hyperplane:
$$ \mathbf b \cdot (x-y) = 0 \; \text{ for any } x\in p$$
Expanding the above gives $\mathbf b \cdot x = \mathbf b \cdot y$, and now that $y$ is fixed we get an equation of the form in "definition 2" where constant $c = \mathbf b \cdot y$:
$$ \mathbf b \cdot x = c $$
Therefore any $\mathbf a$ that defines the hyperplane equation in "definition 2" will serve as the normal vector $\mathbf b$ defined in "definition 3", and any normal vector $\mathbf b$ that satisfies "definition 3" will serve as the vector of coefficients $\mathbf a$ in "definition 2".  As a result these quantities have the same uniqueness property, namely that they are unique only up to taking a nonzero scalar multiple of a vector.

There seems to be a lesson here about rank or dimension of a subspace.  The normal vector to a hyperplane is unique (up to a nonzero scalar multiple) in $\mathbb R^n$ because the hyperplane is an $n-1$ dimensional thing, and this leaves only one dimension for things to be perpendicular to this.
So the uniqueness you want to show depends on making use of the $n-1$ dimensional nature of the hyperplane.  The easiest way to discuss this depends to a great extent on your background in linear algebra.
From the perspective of the one linear equation $\mathbf a \cdot x = c$, we see that the matrix form of this equation has a coefficient matrix of rank one (because $\mathbf a$ is nonzero).  Therefore the solutions to this equation (via the principle of superposition) consist of a particular solution to the inhomogenous equation plus all solutions of the homogenous equation $\mathbf a \cdot x = 0$.  Thus we have an $n-1$ dimensional "affine variety" of solutions.
But let's consider the uniqueness strictly from the perspective of the normal vector.  To simplify things, the normal vectors to the hyperplane $\mathbf a \cdot x = c$ are exactly the same as the normal vectors to the subspace $\mathbf a \cdot x = 0$.  This subspace has a basis of $n-1$ linearly independent vectors.  There is a one dimensional subspace orthogonal to these, (orthogonal is another word for perpendicular or normal), and that subspace is generated by vector $\mathbf a$.
Taken together the basis for the subspace $\mathbf a \cdot x = 0$ and the normal vector $\mathbf a$ give us a basis for all of $\mathbb R^n$.  The latter (because it is generated by one vector) is one dimensional, and the former is $n-1$ dimensional (so that the dimension of $\mathbb R^n$ is $n$ as we know).
This is a special case of the Rank-Nullity Theorem, which says the dimension of the row space of the coefficient matrix of the linear "system" $\mathbf a \cdot x = 0$ plus the dimension of the nullspace (the solutions/points of the hyperplane $\mathbf a \cdot x = 0$) is equal to the dimension $n$ of the domain $\mathbb R^n$.
Now the statement that all the nonzero normal vectors to the hyperplane are related by $\mathbf b = k\mathbf a$ for nonzero scalars $k$ is exactly the proposition that the subspace generated by one of these normal vectors is one dimensional.  In other words Span($\mathbf b$) = Span($\mathbf a$) forces $\mathbf b$ to be a nonzero multiple of $\mathbf a$ and vice versa.


text:
Q: How to ARRAYFORMULA SUMIF that looks at each row? I can't work out how to ARRAYFORMULA this formula that I have in each row of a column as it checks whether the cell in the row is in the column:
=IF(L2=1, SUMIFS(G:G,D:D,D2,C:C,C2,B:B,B2),"")
=IF(L3=1, SUMIFS(G:G,D:D,D3,C:C,C3,B:B,B3),"") etc.
I have tried:
=ARRAYFORMULA(IF(INDIRECT(CONCAT("L",ROW(L2:L)))=1,SUMIFS(G2:G,D2:D,INDIRECT(CONCAT("D",ROW(D2:D))),C2:C,INDIRECT(CONCAT("C",ROW(C2:C))),B2:B,INDIRECT(CONCAT("B",ROW(B2:B)))),"")) to try and check the cell on the given row against the column, but the formula isn't working for each row, only the row the formula is in.
Please could someone help?
Solved with =ARRAYFORMULA(IF(L2:L=1,SUMIF(D2:D&C2:C&B2:B,D2:D&C2:C&B2:B,G2:G),""))

A: try:
=ARRAYFORMULA(IF(L2:L=1, SUM(IF((D2:D=D2)*(C2:C=C2)*(B2:B=B2), G2:G, ), ))

A: Solved with =ARRAYFORMULA(IF(L2:L=1,SUMIF(D2:D&C2:C&B2:B,D2:D&C2:C&B2:B,G2:G),""))


text:
Q: Selenium: enable XPCOM access and write to a file from Javascript in Firefox In this question there is an example how to request XPCOM access from Javascript:
How to create a file using javascript in Mozilla Firefox
 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

I was hoping to find a way to enable XPCOM access in similar manner for my Selenium test scripts, so that Javascript could directly write  RAW image data to a file. This actually continues my previous questions how to extract pixel data from  in optimized manner:
Firefox, Selenium, toDataURL, Uint8ClampedArray and Python
What I am hoping to achieve

*

*Enable XPCOM access for Javascripts run through Selenium

*Render image on  Canvas

*Read canvas pixels as raw image data (public API should be available on the canvas itself)

*Write  RAW image data to a file using XPCOM interfaces in a known path location
Note: PNG etc. encoding is unaccetable. This must be raw data for the speed, as it will be directly feed to a video encoding,

A: It seems to me that this blog post is what you are looking for:
Save to local files with XPCOM for Selenium Firefox Chrome
function saveFile(fileName, val){
   try {
      netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   } catch (e) {
      //alert("Permission to save file was denied.");
   }
   var file = Components.classes["@mozilla.org/file/local;1"]
             .createInstance(Components.interfaces.nsILocalFile);
   file.initWithPath(fileName);
   if (file.exists() == false) {
     //alert("Creating file... " );
     file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
   }
   var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
            .createInstance(Components.interfaces.nsIFileOutputStream);
   outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 );
   //UTF-8 convert
   var uc = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
     .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
   uc.charset = "UTF-8";
   var data_stream = uc.ConvertFromUnicode(val);
   var result = outputStream.write(data_stream, data_stream.length );
   outputStream.close();
}

You'll have to adapt it for your situation (RAW datatype) but that's basically it!

A: I don't know much about Selenium, but IF you can install an extension on the version of Firefox that will be running the page, you can inject your own script into the page when it loads. See this SO answer


text:
Q: inotifywatch: continue watch after file rotation I'm trying to write a script that uses inotifywatch to watch for changes in a log file. If a specific message is written to the log file, it's supposed to trigger a certain function. The script currently exists in this basic form:
while inotifywait -e modify /var/log/auth.log
do
  alert=$(tail -n1 /var/log/auth.log | grep -E -o ".{0,7}password")
  if [[ $alert == "Failed password" ]]
  then
   echo "FAILURE" >> test.log
  elif [[ $alert == "cepted password" ]]
  then
   echo "LOGIN" >> test.log
  fi
done

Everything works fine – up until the point where the logfile watched by inotifywatch is rotated. Then it ceases to function. I presume that's because during rotation the watched file is renamed and no longer written to afterwards and a new file with the old name is created in its place which inotify has never been told to watch in the first place.
I tried to circumvent this by switching from inotifywatch to using tail -f but the same problem seems to apply there as well.
Now I realize this could probably be solved by creating a huge if-structure in which inotifywatch not only watches for modify, but also for file creation and restarts a watch for modification. But I like to keep things simple, so does anyone know if there's a simpler way? (And please, no, I don't want to use prefabricated solutions like fail2ban etc. – the interesting part for me is to create stuff like this myself with simple tools.)

A: inotify is used to monitor files an directory by their inode, not by their name. When the file is rotated, its content does not change any longer (except for a short period, until the daemons are reloaded so that they use the newly created log file)
AFAIK, tail -f uses the inotify system, so it won't help. But if you have a working solution with tail -f then use tail --follow=name (or tail -F) if this is supported by your version of tail (POSIX tail does not support this). tail will then monitor the file identified by its filename. Here is an excerpt of the man page:

With --follow (-f), tail defaults to following the file descriptor, which
  means that even if a tail'ed file is renamed, tail will  con‐ tinue to
  track its end.  This default behavior is not desirable when you really want
  to track the actual name of the file, not the file descriptor (e.g., log
  rotation).  Use --follow=name in that case.  That causes tail to track the
  named file in a way that  accommodates renaming, removal and creation.

[update]
Example of use:
tail -n0 -F my_file.log \
| while read -r log_line; do
    do_something_with "$log_line"
done

Because of the pipe, the while loop executes in a sub-process, which may cause you troubles if you want to modify variables outside the loop. If you use bash, you may want to use this alternative syntax which does not have this undesirable effect (but is less readable):
while read -r log_line; do
    do_something_with "$log_line"
done < <(tail -n0 -F my_file.log)

A: It can be done with inotifywait with a one-liner:
inotifywait -e move_self -e modify -m /path/to/some/file | awk '$2=="MODIFY" {system("/bin/echo Yes")}'

The -m flag keeps monitoring the file indefinitely, for the events move_self (which allows monitoring the name change of a file or directory) and modify, passing the output to an awk command which weeds out move_self events, executing the command inside the system set of parentheses for every modify event. You will have to write your own shell script in lieu of my echo command. Please pay attention to the various sets of apostrophes and quotation marks.


text:
Q: Calling functions based on command received in Ruby Given a text command, I need to figure out which class and method in the project needs to be called.
e.g. /help should trigger Generic.new.help and an /edit should trigger the user.edit function respectively.
What I've done is this huge switch-case tree which does the work. Looks somewhat like,
case command
when '/help'
  Generic.new.help
when '/edit'
  user.edit
when /^\/action_[a-z]+$/
  user.action(command)
end

This works but was wondering if there is a better solution for the same.
The only additional problem in this whole scenario is the regex based commands for example, if the command is /action_a or /action_b it should invoke the same user.action method

A: Calling different methods on some user object may be done as
user_methods = %w(show edit create update)
case
when user_methods.include?(command[1..-1])
  user.send(command[1..-1])
end

First line forms array of valid user methods as strings. command[1..-1] expression removes the first character (/) from command. If command exists in the array, users's method send invokes command on this object.
As for regex you can
case command
when /^\/someaction_[a-z]+$/, /^\/anotheraction_[a-z]+$/
  real_cmd = command.split('_').first
  user.send(real_cmd[1..-1], command)
end

Splitting your command by underscore symbol gives you the real action name and you can send it as above.


text:
Q: PySpark is not able to read Hive ORC transaction table through sparkContext/hiveContext ? Can we update/delete hive table data using Pyspark? I have tried to access the Hive ORC Transactional table (which has underlying delta files on HDFS) using PySpark but I'm not able to read the transactional table through sparkContext/hiveContext.
/mydim/delta_0117202_0117202
/mydim/delta_0117203_0117203

A:
Officially Spark not yet supported for Hive-ACID table, get a
  full dump/incremental dump of acid table to regular hive orc/parquet partitioned table then read the data using spark.

There is a Open Jira saprk-15348 to add support for reading Hive ACID table.

*

*If you run major compaction on Acid table(from hive) then spark able to read base_XXX directories only but not delta directories Spark-16996 addressed in this jira.

*There are some workaround to read acid tables using SPARK-LLAP as mentioned in this link.

*I think starting from HDP-3.X HiveWareHouseConnector is able to support to read HiveAcid tables.


text:
Q: Ordenar duas listas com base na ordem da primeira Vou dar um exemplo pois fica mais claro para explicar:
x = [7,5,9,4,2,3,8,1,10]
y = ['sete', 'cinco', 'nove', 'quatro', 'dois', 'tres', 'oito', 'um', 'seis', 'dez']

Preciso ordenar a lista x, de modo que x[i] = y[i], ou seja, as listas devem ficar assim:
new_x = [1,2,3,4,5,6,7,8,9,10]
new_y = ['um', 'dois', 'tres', 'quatro', 'cinco', 'seis','sete', 'oito', 'nove', 'dez']

Exemplo:
x[5] = 3
y[5] = 'tres'

Após ordenar:
new_x[5] = 6
new_y[5] = 'seis'

Basicamente precisaria ordenar a segunda lista ao mesmo tempo que ordeno a primeira. De modo que os elementos sigam pareados.
Como poderia fazer isso?

A: Uma alternativa é criar uma lista de índices, e ordenar estes índices de acordo com o respectivo valor em x.
Depois você usa estes índices para ordenar as listas:
x = [7, 5, 9, 4, 2, 3, 8, 1, 6, 10]
y = ['sete', 'cinco', 'nove', 'quatro', 'dois', 'tres', 'oito', 'um', 'seis', 'dez']

# ordene os índices em vez dos elementos em si
indices = list(range(len(x)))
indices.sort(key=lambda i: x[i]) # ordene os índices com relação ao seu respectivo valor em x

# crie as listas baseado na ordem dos índices
new_x = [x[i] for i in indices]
new_y = [y[i] for i in indices]

print(new_x) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(new_y) # ['um', 'dois', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez']

list(range(len(x))) cria a lista com os índices (no caso, os números de zero até o tamanho de x).
A seguir, ordenamos os índices, usando como critério o respectivo valor na lista x. Após o sort, a lista indices será [7, 4, 5, 3, 1, 8, 0, 6, 2, 9], o que quer dizer que x[7] é o primeiro elemento de x (quando este for ordenado), x[4] é o segundo, etc, e o mesmo vale para y.
Sendo assim, basta colocar as listas x e y na ordem indicada pela lista indices.

Outra forma de criar a lista de índices já ordenada seria:
indices = sorted(range(len(x)), key=lambda i: x[i])

A: Tem a caminho da programação funcional utilizando as funções builtin zip() para juntar as duas lista, sorted() para ordenar essa junção e map() para aplicar uma função separadora da listas ordenadas:
x = [7, 5, 9, 4, 2, 3, 8, 1, 6, 10]
y = ['sete', 'cinco', 'nove', 'quatro', 'dois', 'tres', 'oito', 'um', 'seis', 'dez']

xy = zip(x, y)                               #Junta as duas listas numa lista d tuplas: [(7, 'sete'), (5, 'cinco'), (9, 'nove'), (4, 'quatro'), (2, 'dois'), (3, 'tres') (8, 'oito'), (1, 'um'), (6, 'seis'), (10, 'dez')] .

sorted_xy = sorted(xy, key= lambda t: t[0])  #Orderna xy com base no primeiro elemento de cada tupla.

new_x= list(map(lambda t: t[0], sorted_xy))  #Extrai o resultado da ordenação da lista x.
new_y= list(map(lambda t: t[1], sorted_xy))  #Extrai o resultado da ordenação da lista y.

print(new_x)
print(new_y)

Resultando:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
['um', 'dois', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez']


text:
Q: Flex Prevent soft keyboard from closing I have a mobile AIR app with a simple layout:
<s:layout><s:VerticalLayout /></s:layout>

<s:TextArea width="100%" height="100%" />

<HGroup width="100%" >
     <s:Button label="button" />
     <s:Button label="button" />
     <s:Button label="button" />
</HGroup>

The application is set to resize when the soft keyboard opens by setting resizeForSoftKeyboard="true" in the main app. The textArea uses the default Flex 4.6 skin.
My problem is, that if the user opens the keyboard by typing text into my texArea, he will be unable to click the buttons below the TextArea, because as soon as he tries to click a button the soft keyboard lowers (because the focus it out of the TextArea?) and immediately opens again (because the mouseDown position is now above the TextArea?).
How can i prevent the soft keyboard from closing, so the user is able to click the buttons between the TextArea and the keyboard?
Thanks

A: This is very strange. I tried running your program myself, and I have no trouble at all:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark" applicationDPI="320" resizeForSoftKeyboard="true">
    <s:layout><s:VerticalLayout /></s:layout>

    <s:TextArea width="100%" height="100%" />

    <s:HGroup width="100%" >
        <s:Button label="button" click="trace('clicked')"/>
        <s:Button label="button" click="trace('clicked')" />
        <s:Button label="button" click="trace('clicked')" />
    </s:HGroup>
</s:Application>

The keyboard opens when I touch the text area, closes when I click a button (without opening again), and the clicks show up in the console when debugging.
You didn't post the entire app, do you have anything in the complete program that I don't? In that case, I would see if any of that could interfere with the UI.

A: Maybe add an event to bring up the keyboard when the button is clicked i.e. in the click event handler of that button.
Also (and I havnt tried this myself), but in the deactivate event for the keyboard for that view, add event.preventDefault()
Brian


text:
Q: How do I get possible selection creteria for getContentResolver().query for MediaStore.Images.Media I want to just images just after a certain date. The code is:
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date lastRunDate = sdf.parse(sdf.format(lastRunTIme.getTime()));
        selection = "MediaStore.Images.Media.DATE_ADDED >=" + lastRunDate;

    final Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            null,
            MediaStore.Images.Media.DATE_TAKEN);

And this is not working. I am sure I am adding correct way to the selection creteria. Can you please help.


text:
Q: How to loop over each page in laravel paginator I've used laravel pagination to retrieve data from a table, I'm able to get the items of the first page but how to loop over each page and get the items from each page
Here is my code
public function handle()
{
    $productsInstance = Products::query()->paginate(10);
    $totalPages = $productsInstance->lastPage();

    for ($i=1; $i <= $totalPages; $i++) {
        foreach ($productsInstance as $productInstance) {
            $items = $productInstance->items;

            foreach ($items as $item) {
                // operation performed on each item
            }
        }
    }
}

The products table I'm querying and paginating is having a record of more than 200k, I'm able to perform the foreach operation on the first page but how to get items from each page

A: You should install QueryFilter package & use that package reference in your Model

*

*Create Product Model and use App\Filters\QueryFilter;

*Next in Product Model use below function
/* scope for filters */
public function scopeFilter($query, QueryFilter $filters)
{
return $filters->apply($query);

}

*In Controller or Jobs
$limit = request()->limit ?? 10;
$products = Product::filter($filter)->paginate($limit);

*Route should be to get products-> /api/products?limit=10&page=1


text:
Q: How to make custom error pages django 2.2 I am creating a blog using Django 2.2, and I have recently finished almost all of it. All that is left is making custom error pages. I have a book that shows how to do it, but it doesn't work. I have checked all over online, but nothing works. Please help? Here is the code:
settings.py:
    """
Django settings for boy_talks_about_coding project.

Generated by 'django-admin startproject' using Django 2.2.12.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '8rk31cd@y065q)l9z2x@4j#a*gz6g3lw_$$g3e7#@de4xyj#xg'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['localhost''boytalksaboutcoding.com''boytalksaboutcoding.herokuapp.com']

# Application definition

INSTALLED_APPS = [
    # My apps
    'blog_posts',

    # Third party apps
    'bootstrap4',

    # Default Django apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'boy_talks_about_coding.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'boy_talks_about_coding.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'blog_posts/static'),
)

# Heroku settings
import django_heroku
django_heroku.settings(locals())

if os.environ.get('DEBUG') == 'TRUE':
    DEBUG = True
elif os.environ.get('DEBUG') == 'FALSE':
    DEBUG = False

views.py:
    from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
    """The home page for my blog."""
    return render(request, 'blog_posts/index.html')

def old_posts(request):
    """Where I will show earlier posts."""
    return render(request, 'blog_posts/old_posts.html')

def todays_post(request):
    """Where I will show this week's post."""
    return render(request, 'blog_posts/todays_post.html')

def custom_404(request):
    return render(request, 'blog_posts/404.html', status=404)

def custom_500(request):
    return render(request, 'blog_posts/500.html', status=500)

urls.py:
    """Defines URL patterns for blog_posts."""

from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from django.http import HttpResponse
from django.conf.urls import *

from . import views

app_name = 'blog_posts'
urlpatterns = [
    # Home page
    path('', views.index, name='index'),

    # This week's post
    path('this-weeks-post/', views.todays_post, name="todays_post"),

    # Earlier posts
    path('earlier-posts/', views.old_posts, name="old_posts"),
] + static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)

handler404 = views.custom_404
handler500 = views.custom_500

Here is the error message I get:
    Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Users/isaac/opt/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/Users/isaac/opt/anaconda3/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/isaac/Desktop/blog/b_env/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/Users/isaac/Desktop/blog/b_env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "/Users/isaac/Desktop/blog/b_env/lib/python3.7/site-packages/django/core/management/base.py", line 436, in check
    raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:

ERRORS:
?: (urls.E007) The custom handler404 view 'blog_posts.views.custom_404' does not take the correct number of arguments (request, exception).

System check identified 1 issue (0 silenced).

A: As specified by the error, the view needs to take two parameters, the request, and the exception:
from django.http import HttpResponseNotFound
from django.template.loader import render_to_string

def custom_404(request, exception):
    return HttpResponseNotFound(
        render_to_string('blog_posts/404.html', request=request)
    )
You should let it return a HttpResponseNotFound object [Django-doc], so we can here call render_to_string to first render the template to a string, and then wrap it in a HttpResponseNotFound.
The exception contains the exception object. You can for example read details from this object and add these to the exception page.
This is specified in the documentation on handler404:

(…) If you implement a custom view, be sure it accepts request and exception arguments and returns an HttpResponseNotFound.


text:
Q: Xcode add reference to files instead of copy I have created my framework that i want to add in my project. What i do is:

*

*In my project i chose Xcode -> File -> Add Files to..

*In prompt window i go for framework directory, chose .xcodeproj file

*Check "Copy items if needed" and "Added folders - Create groups" radio button

What i expect - .xcodeproj that contain my framework is added and copied to my project
What i got - i can see file in Xcode, but not in folder when my app exist. So, when i try to Delete -> Move to trash my framework, it delete it in folder when it was created (not my project folder).
I can't figure out how to actually add and copy file instead of reference to it.


text:
Q: Save ggplot in loop with R I have a dataset with numeric and factor variables. I want to do one page with numeric and other with factor var. First of all, i select factor var with his index.
My df is IRIS dataset.
df<-iris
df$y<-sample(0:1,nrow(iris),replace=TRUE)
fact<-colnames(df)[sapply(df,is.factor)]
index_fact<-which(names(df)%in%fact)

Then i calculate rest of it (numerics)
nm<-ncol(df)-length(fact)

Next step is create loop
i_F=1
i_N=1
list_plotN<- list()
list_plotF<- list()

for (i in 1:length(df)){
  plot <- ggplot(df,aes(x=df[,i],color=y,fill=y))+xlab(names(df)[i])

  if (is.factor(df[,i])){
    p_factor<-plot+geom_bar()
    list_plotF[[i_F]]<-p_factor
    i_F=i_F+1
  }else{
    p_numeric <- plot+geom_histogram()
    list_plotN[[i_N]]<-p_numeric
    i_N=i_N+1
  }
}

When i see list_plotF and list_plot_N,it didn't well. It always have same vars. i don't know what i'm doing wrong.
thanks!!!

A: Consider passing column names with aes_string to better align x with df:
for (i in 1:length(df)){
    plot <- ggplot(df, aes_string(x=names(df)[i], color="y", fill="y")) +
              xlab(names(df)[i])
    ...
}

To demonstrate the problem using aes() and solution using aes_string() in OP's context, consider the following random data frame with columns of different data types: factor, char, int, num, bool, date.
Data
library(ggplot2)

set.seed(1152019)
alpha <- c(LETTERS, letters, c(0:9))
data_tools <- c("sas", "stata", "spss", "python", "r", "julia")

random_df <- data.frame(
  group = sample(data_tools, 500, replace=TRUE),
  int = as.numeric(sample(1:15, 500, replace=TRUE)),
  num = rnorm(500),
  char = replicate(500, paste(sample(LETTERS[1:2], 3, replace=TRUE), collapse="")),
  bool = as.numeric(sample(c(TRUE, FALSE), 500, replace=TRUE)),
  date = as.Date(sample(as.integer(as.Date('2019-01-01', origin='1970-01-01')):as.integer(Sys.Date()),
                        500, replace=TRUE), origin='1970-01-01')
)

Graph
fact <- colnames(random_df)[sapply(random_df,is.factor)]
index_fact <- which(names(random_df) %in% fact)

i_F=1
i_N=1
list_plotN <- list()
list_plotF <- list()
plot <- NULL

for (i in 1:length(random_df)){
  # aes() VERSION
  #plot <- ggplot(random_df, aes(x=random_df[,i], color=group, fill=group)) +
  #  xlab(names(random_df)[i])

  # aes_string() VERSION
  plot <- ggplot(random_df, aes_string(x=names(random_df)[i], color="group", fill="group")) +
    xlab(names(random_df)[i])

  if (is.factor(random_df[,i])){
    p_factor <- plot + geom_bar()
    list_plotF[[i_F]] <- p_factor
    i_F=i_F+1
  }else{
    p_numeric <- plot + geom_histogram()
    list_plotN[[i_N]] <- p_numeric
    i_N=i_N+1
  }
}

Problem (using aes() where graph outputs DO NOT change according to type)

Solution (using aes_string() where graphs DO change according to type)

A: I don't really follow your for loop code all that well. But from what I see it seems to be saving the last plot in every loop you make. I've reconstructed what I think you need using lapply. I generally prefer lapply to for loops whenever I can.
Lapply takes a list of values and a function and applies that function to every value. you can define your function separately like I have so everything looks cleaner. Then you just mention the function in the lapply command.
In our case the list is a list of columns from your dataframe df. The function it applies first creates our base plot. Then it does a quick check to see if the column it is looking at is a factor.. If it's a factor it creates a bar graph, else it creates a histogram.
histOrBar <- function(var) {
  basePlot <- ggplot(df, aes_string(var))
  if ( is.factor(df[[var]]) ) {
    basePlot + geom_bar()
  } else {
    basePlot + geom_histogram()
  }
}

loDFs <- lapply(colnames(df), histOrBar)


text:
Q: Why "typeof null == object" will stay in javascript? I was reading a article about front-end development on Medium, when I stumbled upon an interesting piece of information, which is as follows:

The type of a variable can be determined by using the typeof(var_name)
  function. One thing to note is that typeof(null) returns object. This
  is a long-standing bug in JS, but one that is likely never going to be
  fixed. Too much code on the Web relies on the bug and thus fixing it
  would cause a lot more bugs!

Why so? What kind bugs & code reliability this section is referring to?
Link for article :
https://medium.com/@shoaibkhan_31475/cracking-the-front-end-developer-interview-part-1-be3619b60cc4

A: Making breaking changes to JavaScript has serious consequences. There are millions of sites out there which run code that may have been written years and years ago, and will possibly never be touched again.
This means, if we change the way JavaScript works, but those sites rely on the way it used to work, parts of the internet will flat-out break -- the code that drives them no longer works as expected.
On top of that, even if the standards committee decides to change the specification accordingly, that doesn't magically 'fix' this issue. There's also the browser vendors which have to actually implement the specification -- Chrome's V8 engine, Firefox' SpiderMonkey engine etc. They also have a strong incentive to not break stuff, since, well, users would just switch to a different browser if theirs isn't able to display the sites they go to anymore.
For a related, pretty recent, and mildly entertaining topic, see also the discussion whether the JavaScript flatMap function should be called smoosh, for very similar reasons.


text:
Q: phpDocumentor to wiki? My company is working on end user/developer docs using mediawiki. I'd like to take a lot of the API docs that phpdoc spit out (for specific functions/methods) and have it in wiki markup for easy transfer.
Any solutions out there for getting wiki markup or wiki output from phpDoc? I've looked around and found nothing.

A: Just came across this while looking for a way to generate Twiki output from phpDoc. I haven't found a good solution for this either and have started a project here: http://step2.co.in/content/phpdoc-twiki to get work started on this. If anybody's interested in helping out, please get in touch.

A: According to the PHPDocumentor website and their documentation HTML and XML output is possible.  You can then import the XML using the built-in import features of MediaWiki though you may want to export first to look at what the format of the XML is.  They also mention that using XML to import large amounts of data can lead to timeouts and have an alternative which allows you to create SQL queries to insert the data.  Also you'll probably need an extension for MediaWiki to show code (something like SyntaxHighlight GeSHi).
All this doesn't really explain how to convert the output of PHPDocumentor into something usable with MediaWiki (ie using Wiki syntax).  Most likely you'll be using scripts to convert one syntax to the other.  It looks like creating your own output format via PHPDocumentor is the easiest way (though outputting as XML:DocBook may work).

A: One option (off the top of my head) is to use the API build in to MediaWiki, and post the data yourself. (via script, of course).
The only other way would be to hack phpDoc, and even then, you'd have to post it to MediaWiki somehow.


text:
Q: In Stargate: Atlantis, How are they able to disconnect the ZPM despite being under water? I am watching Stargate: Atlantis episode "Critical Mass" (S2E13). In this episode a bomb is placed on Atlantis and is set to go off should someone dial the gate back to Earth, which they do once a month.
Once they find out-as a way to prevent someone from dialing back to Earth and intentionally triggering the bomb-they entirely disconnect the ZPM, the only power source capable of doing so.
The problem with this is that they established earlier in the series that the ZPM is the only way they are able to maintain shields and submerge the city under the water safely. At the time the city was submerged as a way to fool the Wraith into thinking Atlantis was destroyed, so they very much needed the ZPM power to maintain the shields in that episode.
How is it possible that the ZPM was disconnected and Atlantis was still able to remain hidden under the water?

A: Nevermind, my mistake. This episode apparently took place before Atlantis was submerged. So there was no dilema to begin with.


text:
Q: Insert into global temporary table operation failed A select statement to store my temporary table data to a plsql table type:
select * from Global_temporary_table
bulk collect into plsql_table_type;

After doing some conversion, when i try to insert the data back to the Global_temporary_table table using below insert statement
INSERT INTO Global_temporary_table
VALUES v_rbct_tbl(i);
COMMIT;

it fails to complete the insert transaction. However, if i try to insert same data into non-global temporary table, it doesn't create any problem.
Help me out please!

A: Almost sure your commit deletes the data.
The data in a GTT is volatile and dissapears either after commit(ON COMMIT DELETE ROWS) or after the session ends(ON COMMIT PRESERVE ROWS).
If you need the data to stay after commit, create the table with ON COMMIT PRESERVE ROWS.
See the docs


text:
Q: Wrapping contents of element until specific element How can I wrap in a jQuery element the contents until a specific element, as shown in this  example:

       wrap this element

    text to wrap

        dont wrap this

to:

           wrap this element

        text to wrap

        dont wrap this

I tried:
$('div).contents().nextUntil('.dont-wrap').wrap('');

A: The following code works
$(function(){
    $('div').contents().each(function(){
        if(!$(this).hasClass('dont-wrap')){
            $(this).wrap('');
        }
    });
});

Here's a JSFiddle


text:
Q: In Android,layout not laying out properly first time but ok the consecutive times I have defined my xml in a relative layout in activity_main.xml. There are about 14 image buttons.  I have set the width and height of the buttons to an arbitrary number.
In the onCreate method of my java class, after the setContentView(R.layout.activity_main) statement, I compute and set the width and height of the buttons and spacing between the buttons based on the screen size using DisplayMetrics, and the height and width of the btooons as a fraction the screen size, so that it is uniformly laid out for all screen sizes.
This works fine, but except for the first time the program is loaded on a device..all other times it lays out just fine. Please help me on how to solve this. thankyou


text:
Q: Select option does not show in html In my struts project I have something like
<html:text styleId="textId" name="bean" property="<%=getMyField()%>"/>
<html:select styleId="fieldId" name="bean" property="<%=getMyField()%>"/>
<html:optionsCollection name="bean" property="selectOptions" value="label" label="label" />

In html I see something like
<select name="myData" id="fieldId">
   <option value="MyFirstValue">MyFirstValue</option>
   <option value="MySecondValue">MySecondValue</option>
   <option value="MyThirdValue">MyThirdValue</option>
</select>

There is no selected option and this is correct because from server,for that field I got none full value.  And in browser I see none selected item.
But if I do
document.getElementById('fieldId').childNodes[0].selected
i get true. Why?


text:
Q: How to switch mapboxgl language in DeckGL I'm currently playing around with deck.gl.
Taking the UK accident example (3d-heatmap). How can I change the language used to display the POI in mapboxGL?
Where should I put the mapboxGL equivalent of:
map.setLayoutProperty('country-label-lg', 'text-field', '{name_fr}');

A: This is mostly related to the usage of react-map-gl rather than deck.gl, given that's what the example is using.
You can grab the mapbox map instance using the getMap() method of the < MapGL> component, and call the method to change the layout property:
<MapGL ... ref='map' />

const map = this.refs.map.getMap()
map.setLayoutProperty('country-label-lg', 'text-field', '{name_fr}')


text:
Q: tomcat6 behind xinetd - real client ip In server.xml, at the Connector I specify proxyPort as 80.
Here's the xinetd service:
service http
{
        socket_type     = stream
        protocol        = tcp
        user            = tomcat6
        wait            = no
        bind            = 0.0.0.0
        port            = 80
        redirect        = 127.0.0.1 8080
        disable         = no
        flags           = REUSE
        log_type        = FILE /var/log/xinetd_http_access.log
        log_on_success  -= PID HOST DURATION EXIT

        per_source      = UNLIMITED
        instances       = UNLIMITED
}

Still, in the access logs of Tomcat I see lines like the following:
127.0.0.1 - - [17/Aug/2012:00:23:23 +0300] "GET / HTTP/1.1" 200 1975
127.0.0.1 - - [17/Aug/2012:00:23:23 +0300] "GET /_static/css/global.css HTTP/1.1" 304 -

Any ideas?

A: Can xinetd pass an X-FORWARDED-FOR HTTP header?
If tomcat is behind a reverse proxy (e.g. nginx) that passes X-FORWARDED-FOR, i.e.:
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Then you can set in your tomcat server.xml for the AccessLogValve:
pattern="%{X-Forwarded-For}i %l %u %t %r %s %b %{User-Agent}i %{Referer}i"

And you will get the originating IP address of the client in the access log.
Cheers

A: Nope, nothing can be done. You cannot do this with xinetd. It appeared working for me, but then I realize that most of the IP addresses in the log are still 127.0.0.1.
I finally managed to get Tomcat running as (mostly) restricted user using jsvc with the --user option. It is also possible with iptables.


text:
Q: Xbox 360 Kinect mic not working for chat but works as voice recognized My Xbox 360 Kinect is not working for game chat and party chat. It hears me when I say "Xbox" at the dash board but will not work for game chat. I've done the audio test 3 times and still won't work. The game chat option is on and it says it can hear me. Please respond to this ASAP

A: This is common among Kinect owners, and has happened to me personally numerous times. Unfortunately, there is no "one true solution" to this issue, as Microsoft provides very little support for the Xbox 360 Kinect anymore.
I would recommend you read through the Xbox 360 Live Chat Support website and going through each of the troubleshooting methods, as well as double checking your Xbox's privacy settings and chat settings. Since you are using the Kinect, ensure that you go through the Kinect's audio calibration and audio tuner just to make sure it's not an issue on that end.
Xbox Live 360 Chat Troubleshooting: https://support.xbox.com/en-US/xbox-360/xbox-live/troubleshoot-parties-voice-chat#c29f36195f53433cacfffe8b275159aa
If all else fails, you can contact Microsoft about the issue and they will be able to solve it directly: https://support.xbox.com/en-US/contact-us?NavigationPath=/en-US/xbox-360/xbox-live/troubleshoot-parties-voice-chat


text:
Q: How to set class property's value to be set to generated id value of another class on insertion to database? I have a bit of a hard time putting this just in words, so I'll use some code to help explain myself and my problem.
So imagine I have two classes ClassA and ClassB:
class ClassA
{
    public int ClassAId { get; set; }
    public string Name { get; set; }
}

[Owned]
class ClassAOwned
{
    public int ClassAId { get; set; }
    public string Name { get; set; }
}

class ClassB
{
    public int ClassBId { get; set; }
    public string Action { get; set; }
    public ClassAOwned ClassA { get; set; }
}

as you can see ClassB contains ClassA, but I have another class for it ClassAOwned because I want ClassB to own ClassA (flatten its columns into ClassB table), but also have ClassA DbSet as a seperate table (and as I understand entity class cannot be owned and have its own DbSet at the same time), so I had to use 2 different classes. Here's my context to make it easier to understand:
class TestContext : DbContext
{
    public DbSet<ClassA> ClassAs { get; set; }
    public DbSet<ClassB> ClassBs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseInMemoryDatabase("TestContext");
    }
}

Now my problem comes when I'm trying to insert ClassA and ClassB to context at the same time and have to match their ClassAId values which is generated by database provider:
var testContext = new TestContext();
var classA = new ClassA
{
    Name = "classAName"
};
var classB = new ClassB
{
    Action = "create",
    ClassA = new ClassAOwned
    {
        ClassAId = classA.ClassAId,
        Name = classA.Name
    }
};
testContext.ClassAs.Add(classA);
testContext.ClassBs.Add(classB);
classB.ClassA.ClassAId = classA.ClassAId;
testContext.SaveChanges();

when using InMemoryDatabase the following call:
testContext.ClassAs.Add(classA);

actually changes classA.ClassAId to correct generated value, however when using SQL server classA.ClassAId gets set to int.MinValue so next call:
classB.ClassA.ClassAId = classA.ClassAId;

sets classB.ClassA.ClassAId to int.MinValue. and the final call:
testContext.SaveChanges();

changes classA.ClassAId to correct generated value, but classB.ClassA.ClassAId stays as int.MinValue and that's the value that gets inserted into the database.
My question is: Is there a way to tell EF core that when adding two entities into context set one's property to whatever value was generated for another entity's primary key? So the functionality I'm looking for is exactly the same as adding two entities where one has a foreign key, except in this case it's not really a foreign key.
A simple workaround would be to set the "foreign key"(classB.ClassA.ClassAId) after testContext.SaveChanges() and save changes again, but then it becomes two separate operations and what if the second one fails? The database will be in invalid state.

A: It's possible, but with some trickery which works with the latest at this time EF Core 2.2, and might stop working in 3.0+ (at least needs to be verified).
First, it has to be mapped as relationship - there is just no other way. It doesn't need to be a real database relationship though, just should be such from the EF Core model point of view.
Second, and this is quite important, the delete cascade behavior should be set to  Restrict, which currently means enforce in the database, but do nothing with the tracked related entities in memory.
So let's do that with you sample. Both aforementioned mappings require fluent configuration similar to this:
modelBuilder.Entity<ClassB>().OwnsOne(e => e.ClassA)
    .HasOne<ClassA>().WithMany() // (1)
    .OnDelete(DeleteBehavior.Restrict); // (2)

If you are using migrations, the generated migration would contain something like this:
protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.CreateTable(
        name: "ClassA",
        columns: table => new
        {
            ClassAId = table.Column<int>(nullable: false)
                .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
            Name = table.Column<string>(nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_ClassA", x => x.ClassAId);
        });

    migrationBuilder.CreateTable(
        name: "ClassB",
        columns: table => new
        {
            ClassBId = table.Column<int>(nullable: false)
                .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
            Action = table.Column<string>(nullable: true),
            ClassA_ClassAId = table.Column<int>(nullable: false),
            ClassA_Name = table.Column<string>(nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_ClassB", x => x.ClassBId);
            table.ForeignKey(
                name: "FK_ClassB_ClassA_ClassA_ClassAId",
                column: x => x.ClassA_ClassAId,
                principalTable: "ClassA",
                principalColumn: "ClassAId",
                onDelete: ReferentialAction.Restrict);
        });

    migrationBuilder.CreateIndex(
        name: "IX_ClassB_ClassA_ClassAId",
        table: "ClassB",
        column: "ClassA_ClassAId");
}

Manually edit it and remove the ForeignKey command (line) since you don't want a real FK. You could also remove the corresponding CreateIndex command, although it won't hurt.
And that's all. The only important thing you need to remember is to use the principal TableAId property only after the new entity has been added to (thus tracked by) the context. i.e.
var testContext = new TestContext();
var classA = new ClassA
{
    Name = "classAName"
};
testContext.ClassAs.Add(classA); // <--
var classB = new ClassB
{
    Action = "create",
    ClassA = new ClassAOwned
    {
        ClassAId = classA.ClassAId, // <--
        Name = classA.Name
    }
};
testContext.ClassBs.Add(classB);
testContext.SaveChanges();

It will have generated temporary negative value, but after SaveChanged both ids will be updated with the actual database generated value.

A: Well... As far as I  know there is no direct way to do this.
What I would suggest would be to revisit the decision to have two copies of ClassA, one that is owned and another that is independent. This is inefficient and obviously it is causing you trouble. It also creates the likelihood that the two copies will eventually get out of sync.
The obvious approach would be to have ClassA be independent and then just use "Include" to include it in the data in your queries. All the challenges you have described here will go away. Instead of trying to keep two copies of A in sync you could just create the flattened copy of B including A if/when you need it.

A: After getting more information, one way to implement this is something like
class A
{
    public int ID;
    public string data;
...
}

class HistoryA
{
    public int ID;
    public int AID;
    public string data;
    public DateTime updated;
...
}

So I hade one class (class A) holding the current information and another historyA referencing the current one (HistoryA.AID = A.ID) and storing all the previous information in HistoryA.
So all data properties in A was duplicated in HistoryA.


text:
Q: How to assess the change in association between two variables? Let's say I have an psychological experiment in which I measure two variables. I am interested to test whether these variables are related (i.e., whether  they reflect related processes). I have a group of 20 participants and for each participant I measure two variables (two data points per participant).
I found some correlation between two variables. Now, I recruit another group of participants (N=20) that make exactly the same experiment, but this time I conduct brain stimulation. In this second group compared to the first group, one variable consistently increases, but other variable remains at the same level. So, this shows that at least in some cases these variables might be not be very related.
Is there a more direct way to test this? Comparing correlations between two groups seems meaningless, because increasing value of one variable, but not the other make just a scaling, without changing correlation (see attached). Note, that I have two different samples of subjects, so there is no paired statistics

A: If I understand correctly, it sounds like what you need to run is a mixed model with participants as a random effect. This will allow you to look at the cross-level interaction, that is, whether the within-subject correlation changes depending on the between-subjects condition. In R, it would look like this using the lme4 package and intercepts only for the random effect:
lmer(within1 ~ within2*between + (1|Subject), data=df)

However, it would be helpful to provide simulated data and more information about the issue.


text:
Q: Bypass window.onload I'm a student who has to deal with an intern hacking challenge. I'm that far that I'm able to insert JavaScript code.
The only problem is that I'll have to deal with a firewall.
So far so good I've managed to load an  tag with JavaScript in it.
Now I'm trying to change the webpage onload to another page.
Unfortunately a firewall blocks the 'onload' statement.
Is there another way to bypass this?
It seems like innerHtml is only local and it doesn't change the index page.
clicks

A: You can try to insert something like this in the  part:

And in your controlled myhackingcode.js you could do:
setTimeout(function() {
    document.body.innerHTML = '
 You have been hacked
';
    // Any other things you'd like to do, come here
}, 1000);

Which would replace the entire body content of the page with the html you provide.


text:
Q: How to close/remove menu item or tab when right click? I'm creating tab using multiview and what I want to do is to close one of the menu tabs when I right click on it.
These are part of the aspx and code behind:
ASPX Page:
<asp:Menu
    id="Menu1"
    Orientation="Horizontal"
    StaticMenuItemStyle-CssClass="tab"
    StaticSelectedStyle-CssClass="selectedTab"
    CssClass="tabs" width = "100%"
    OnMenuItemClick="Menu1_MenuItemClick"
    Runat="server" style=" text-align:center;">
</asp:Menu>

    <asp:MultiView
        id="MultiView1"
        ActiveViewIndex="0"
        Runat="server">
        <asp:View ID="v1" runat="server" >

        </asp:View>
        <asp:View ID="v2" runat="server" >

        </asp:View>
        <asp:View ID="v3" runat="server" >

        </asp:View>
        <asp:View ID="v4" runat="server" >

        </asp:View>
        <asp:View ID="v5" runat="server" >

        </asp:View>
        <asp:View ID="v6" runat="server" >

        </asp:View>
        <asp:View ID="v7" runat="server" >

        </asp:View>
        <asp:View ID="v8" runat="server" >

        </asp:View>
        <asp:View ID="v9" runat="server" >

        </asp:View>
        <asp:View ID="v10" runat="server" >

        </asp:View>
    </asp:MultiView>

Code Behind:
(This is part of the NodeChanged event)
...
...
...
int TabCount = Convert.ToInt32(lblTabCounter.Text.ToString());
int TabIndex = Convert.ToInt32(lblTabCounterIndex.Text.ToString());

if(TabCount <= 10)
    {
        divcont.Visible = true;
        string tabName = getURLName(uRL);
        MenuItem myItem = new MenuItem(tabName, TabIndex.ToString());
        Menu1.Items.AddAt(TabIndex, myItem);
        f1.Attributes.Add("src", lblURL.Text.ToString());
        MultiView1.ActiveViewIndex = TabIndex;
        TabCount++;
        TabIndex++;
        lblTabCounter.Text = TabCount.ToString();
        lblTabCounterIndex.Text = TabIndex.ToString();
        tvPermissions.ExpandAll();

        int i = ctr;
    }

(This is for the MenuItemClick Event)
protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
{
    int index = Int32.Parse(e.Item.Value);
    MultiView1.ActiveViewIndex = index;
}

This is the sample output:

The treeview is located in the orange part(left). While the blue one that is the target url that is located in the project. Based from the codes that I provided it will only point out to one frame named "f1" as an example though there are 10 of them. How can I remove a particular tab (say tab "Expenses") when I right click on it?
I want this to be done in the code behind. For javascript/jquery solutions please provide its code behind implementation or how to call/use it from code behind.
Please help me with this. For clarifications please leave a comment.
Thank you!

A: I tried a different approach. Instead of right click I use double click with confirmation to remove the tab.
I also adapted the user defined JS libraries to catch the double click and add more effects.
I mentioned as well that I already have my JavaScript function to work on this I'm just looking for alternatives other than JavaScript or JQuery. However I'm surprised that I didn't get any response or comments.
Thank you for reading this post.