text:
Q: How to assign value to $_SESSION with AJAX? Yes, I'm aware that this question has already been post, but ... I'm looking for a way to check if the Client has Javascript Enabled.
Here is my idea : At every loading page, PHP initialize $_SESSION['is_js'] to 0. Then, I wish AJAX to (via launching a script php ?) try to set $_SESSION['is_js'] to 1. If JS is enabled, AJAX will succeed, if not, the value remains 0.
I can't use jQuery or others libraries... I have to write this in pure AJAX (I mean not using framework or librairies), and I have no idea how to do this.
Edit : I can't use cookie. I don't want to use .

A: First you need to learn to do a ajax call in pure javascript, some website like w3schools  or others
And in the php files that the ajax call , you can set the session  variable to 1.
But there's maybe better way to find if the client have javascript enable.
EDIT: I suggest to check if your session variable is ,  if not, try the ajax call and set the variable at 0 .   If at page loading the variable is set and equal, that means the client doesn't have javascript/xmlhttprequest  enable.
And for a session, a cookie is store on the client side. So if the client refuse to store any cookie, you will never haver information in your session variables.

A: I would use a cookie. It will function nearly identical --
<?php
$_SESSION['js'] = (int) $_COOKIE['js']
setcookie('js', 0);
?>

You can use a set of cookie functions such as http://www.w3schools.com/js/js_cookies.asp
Good luck!

A: A rather unique (and IMO lame) approach is to use javascript to download a fake image:

Doesn't use AJAX, jQuery, Cookies, etc.

A: According to your idea and your requirements, if you can't use a library like jQuery or Prototype, and so on... you are enforced to use the "raw" XMLHttpRequest Object. The following code is an example.
Create a file called ajax_js_enabled_test.php and put this code inside:
<?php

    if(isset($_GET['PHPSESSID'])) session_id($_GET['PHPSESSID']);
    session_start();

    if(isset($_SESSION['user_js_support']) && $_SESSION['user_js_support']) echo "Javascript enabled";
    else $_SESSION['user_js_support'] = FALSE;

?>

    <a href="<?php echo '?PHPSESSID='.session_id(); ?>">
        Refresh

Create another file called check_js_user_support.php and put this code inside:
<?php

    if(isset($_GET['PHPSESSID'])) session_id($_GET['PHPSESSID']);
    session_start();

    $_SESSION['user_js_support'] = TRUE;

?>

Copy both files in your local web server root. Open the page ajax_js_enabled_test.php from your browser. The AJAX request starts and the page check_js_user_support.php will set the session param called user_js_support to TRUE. So by pushing the Refresh button the page will be reloaded, the $_SESSION['user_js_support'] will be TRUE and the script will write: "Javascript enabled"


text:
Q: Как клонировать нужную ветку? Как клонировать удаленный репозиторий и получить иную ветку, чем master (т.е. по умолчанию)?

A: git clone http://whatever.git -b branch-name
A: Этот вариант склонирует ПОЛНОСТЬЮ весь репозиторий и просто переключится на ветку branch-name:
git clone http://whatever.git -b branch-name

Иногда нужно склонировать ТОЛЬКО конкретную ветку, тогда:
git clone --branch=branch-name http://whatever.git

Еще иногда может потребоваться склонировать репозиторий без многолетней истории его коммитов, тогда нужно использовать параметр --depth=5, где 5 - количество коммитов от последнего:
git clone --depth=1 --branch=branch-name http://whatever.git

A: git clone создает копию удаленного (в общем случае) репозитория. Чтобы получить бранч из удаленного репозитория нужно после git clone выполнить:
git checkout -b [branch] [remotename]/[branch]

или
git checkout --track [remotename]/[branch]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache Spark on Google Cloud, Cluster or no Cluster I want to use Apache Spark to manipulate a huge volume of data in Google Cloud.
I followed the documentation to spin-up a Cloud Dataproc cluster with 5 nodes. Everything works flawlessly.
But my data is on Google Cloud Storage and I learned that I can directly query it using Spark and that is recommended by Google.
In that case, is it necessary to spin-up an entire cluster? Is Spark as efficient on Google Cloud Storage as on HDFS?
If not, it would be easier to just spin one big VM with Jupyter and Spark and use it to run jobs on the data stored on GCS.

A: On a Dataproc cluster, you can use Spark to process data from HDFS as well as GCS (Google Cloud Storage), both equally efficiently. Size of your cluster needs to be decided based on computations you plan to perform in your spark job. There are a bunch of tradeoffs you need to consider while comparing one big VM vs multiple (smaller) VMs - mainly there is an upper limit on how much you can vertically scale (with one VM).

A: If you only need analyze data from Google Cloud Storage,I would recommend you create a cluster on dataproc just when you need. But it still depend on how long will this job takes, and how frequently you doing this job.
For example, you have a scheduled hourly ETL job. You can create new cluseter every hour, and delete when job done. It's very cost effective.


text:
Q: How to have Logstash shipper to grab a value from a local file and passed to indexer ? I have a logstash project that in general is of this architecture:
"
Several logstash Shippers ==> Redis ==> Logstash Indexer ==> ES
".
For each individual Shipper, it needs to grab an ID VALUE from a local file, and have it passed to the Logstash Indexer, that will be used as its unique "INDEX" String. But I don't know how this can be done. Two Quesions here:
a) how this value may be grabbed from a file ?
b) how this value may be passed from shipper to the indexer ?
I know how it works if this string is part of the "path" value, but if it was from a file, I am still clueless.  Anyone has any clue for that ?
John.


text:
Q: What is the meaning of question marks '?' in Linux kernel panic call traces? The Call Trace contains entries like that:
 [<deadbeef>] FunctionName+0xAB/0xCD [module_name]
 [<f00fface>] ? AnotherFunctionName+0x12/0x40 [module_name]
 [<deaffeed>] ClearFunctionName+0x88/0x88 [module_name]

What is the meaning of the '?' mark before AnotherFunctionName?

A: '?' means that the information about this stack entry is probably not reliable.
The stack output mechanism (see the implementation of dump_trace() function) was unable to prove that the address it has found is a valid return address in the call stack.
'?' itself is output by printk_stack_address().
The stack entry may be valid or not. Sometimes one may simply skip it.
It may be helpful to investigate the disassembly of the involved module to see which function is called at ClearFunctionName+0x88 (or, on x86, immediately before that position).
Concerning reliability
On x86, when dump_stack() is called, the function that actually examines the stack is print_context_stack() defined in arch/x86/kernel/dumpstack.c. Take a look at its code, I'll try to explain it below.
I assume DWARF2 stack unwind facilities are not available in your Linux system (most likely, they are not, if it is not OpenSUSE or SLES). In this case, print_context_stack() seems to do the following.
It starts from an address ('stack' variable in the code) that is guaranteed to be an address of a stack location. It is actually the address of a local variable in dump_stack().
The function repeatedly increments that address (while (valid_stack_ptr ...) { ... stack++}) and checks if what it points to could also be an address in the kernel code (if (__kernel_text_address(addr)) ...). This way it attempts to find the functions' return addresses pushed on stack when these functions were called.
Of course, not every unsigned long value that looks like a return address is actually a return address. So the function tries to check it. If frame pointers are used in the code of the kernel (%ebp/%rbp registers are employed for that if CONFIG_FRAME_POINTER is set), they can be used to traverse the stack frames of the functions. The return address for a function lies just above the frame pointer (i.e. at %ebp/%rbp + sizeof(unsigned long)). print_context_stack checks exactly that.
If there is a stack frame for which the value 'stack' points to is the return address, the value is considered a reliable stack entry. ops->address will be called for it with reliable == 1, it will eventually call printk_stack_address() and the value will be output as a reliable call stack entry. Otherwise the address will be considered unreliable. It will be output anyway but with '?' prepended.
[NB] If frame pointer information is not available (e.g. like it was in Debian 6 by default), all call stack entries will be marked as unreliable for this reason.
The systems with DWARF2 unwinding support (and with CONFIG_STACK_UNWIND set) is a whole another story.


text:
Q: Unable to play RTSP video in Qt media player demo I was trying to develop a video management software for which I was evaluating Qt Phonon. The software would be built on windows platform and I understand that Phonon uses Directshow as windows backend and if it runs on Linux it uses GStreamer. Using Qt 4.7.4 on Linux which has a demo example of a video player using phonon I was successfully able to see video stream from panasonic IP camera (RTSP stream), however when I tried the same example on windows platform it does not work (returns error 0x800c0000d). What could be the problem?
Regards,
Saurabh Gandhi

A: 0x800c000d is INET_E_UNKNOWN_PROTOCOL, which in turn is "The specified protocol is unknown". DirectShow and Windows don't offer anything standard to support RTSP feeds, so the two together suggest that the IP camera feeds are not supported (at least without third party components).

A: From my experience I may say that Phonon sucks a lot. If you're not to attached to Phonon, use GStreamer withQt binding for it. You will get a lot more "cross platform" experience with it, as you're using same backend all the time so most of the media files works same way. As the GStreamer and it's Qt bindings are LGPL, you still may use it in closed source application.


text:
Q: Error while installing Visual studio 2005 in Windows 7 Ultimate I have tried to installed Visual Studio 2008 and Sql Server 2005 on windows 7 & following is the result.
SQL SERVER 2005 :- Installed correctly without any error, but when I opened Management studio, it is not showing any server name, I tried to put systemName , systemName/Sqlexpress.
Visual Studio 2008: After 8-9 minute of successful installation , I received a error in installing & I had no more option other than closing the installer window.
I really don't have any idea about installing it in Windows 7.
Please help
Thanks in advance.

A: I had the same problem when trying to upgrade from VS2005 to VS2008.
These problems normally happen because a previous Visual Studio version was not totally uninstalled.
You will not be able to install or uninstall any VS version until you completely erase all traces of this previous version. However, completely uninstalling VS is a very difficult exercise.
Here are some articles that contain methods of uninstalling VS.
Just follow all the advice and execute all the instructions, even if it seems that some of them might not pertain to your case.
How to remove Visual Studio 2005
Uninstall Visual Studio (All Versions)
How To Manually Uninstall Visual Studio with MSDN Library
EDIT
Solutions for "This copy of Windows 7 is not genuine" problem
You need to solve this problem before installing VS2008.
The above article lists three ways of doing so:

*

*Trying once more your Windows 7 Product Key.

*Using MGA Diagnostic Tool to resolve the problem.

*Activate Windows 7 using Phone.

The last method is required, if by any chance your Windows 7 serial number was discovered and used by hackers (using a serial number generator). In that case, the serial number is black-listed in the Microsoft Activation database. However, if you can show proof of ownership, the Microsoft person on the phone could give you a replacement serial number.
If the problem is rather that you're using a Beta version of Windows 7, the best solution is to reformat the hard disk and install the Windows 7 release. Please note that any serial number you got with the Beta is no longer valid, so if that's the case, you'll need to buy the Windows 7 release.

A: Did you make sure you were installing VS as an administrator? These sound like possible permissions issues

A: So assuming that to meet all of the system requirements(VS2008,SQL2005) for the software. Here's my recommendation on the steps to take to get this to work. You should start from a fresh OS, but that's not required:

*

*Uninstall any previous versions of VS or SQL.

*Make sure that your OS has passed genuine validation. Activate the OS and run windows update to prompt the genuine advantage validation. If you can download updates, you are valid.

*Turn off UAC. You can't just turn down the slider, you have to actually turn it off all of the way. The only sure fire way is to modify the EnableLUA registry setting and reboot.

*Run the installers.

*Download and run any service packs or updates for both Visual Studio and SQL server. You should be able to use windows update for this, but you may have to hunt around the microsoft website for them. From what I can tell, SP2 for SQL server is required to get it working.

*Reboot and try the software again. You can turn UAC back on once the install is done.

Hope that does it.


text:
Q: PC connects to Samba Server automatically This is a situation where the PC connects to Samba Server (SMB) automatically. I first realized this was happening on a Windows 8.1 laptop, which is a refurbished HP Pavilion g7 from HP. When booting using Kubuntu on USB, I then noticed in Network a Samba Server of 128 TiB (140 TB) in size.
A few days ago I borrowed someone else's laptop, a Toshiba running Windows 7. Everything seemed to run great for one day then once again a slew of problems with the PC. When I booted from Kubuntu using a USB drive, I noticed it was also connected to a Samba Server of the same size. In both cases it also shows a Loop Device.
Any ideas of how or why this exists? I have suspected unusual network traffic. Yesterday I downloaded Wireshark to learn how to analysis the traffic. Two hours later, my Wireshark starts up but the GUI is really messed up and the application is not functional. I did manage to get one short recording.
Looking through the file structure in Linux it doesn't appear to be a good thing, and it also seems it may be dual booting with Grub.


text:
Q: make div 'fadeOut' and then 'fadeIn' in different place So here is the deal. I am trying to build interactive list (just like ToDo list). My task is that on click 'div.item'should disappear (fadeOut) from "container" and then fadeIn in "trash can".
Here is the code, but when I run it, all animation happens in "trash can". I tried to set a variable equals to my ".item" and make manipulations with it, still no result.
<script type="text/javascript" src="createList.js">

  $(document).on('click', '.item', function (){
        $(this).fadeOut('slow');
        $(this).appendTo('#shoppingChart').fadeIn('slow');
    });
</script>

A: You need to animate, then run the function to append -
$(document).on('click', '.item', function (){
    $(this).fadeOut('slow',function () {
         $(this).appendTo('#shoppingChart').fadeIn('slow');
    });
});

Edit -- working example - http://jsfiddle.net/jmsessink/NHtv4/

A: The fading methods are non-blocking, so they won't prevent subsequent methods from taking place. If you wish to wait until they've finished before you continue, use their callbacks:
// Listen for any click on an img within #desktop
$("#desktop").on("click", "img", function () {
    // Fade that image out over a second
    $(this).fadeOut(1000, function () {
        // When fade is complete, move item and fade-in
        $(this).appendTo("#trash").fadeIn();
    });
});

Demo: http://jsfiddle.net/9U2dP/
You could also use a deferred:
// Listen for any click on an img within #desktop
$("#desktop").on("click", "img", function () {
    // When our hide instruction is done
    $.when($(this).hide(1000)).done(function(item){
        // Append the item to #trash, and fade it into view
        $(item).appendTo("#trash").fadeIn(1000);
    });
});

Demo: http://jsfiddle.net/9U2dP/3/

A: You have to wait for animation to finish, then append item to trash can, then fade in.
Here is a working demo:
http://jsbin.com/ipovic/1/edit

A: jsFiddle Demo
The fade operations are asynchronous, so invoking the methods simply triggers the action—the next call doesn't wait for it to complete. To show both parts of the animation, delay following actions by a time constant using JavaScript's native setTimeout method.
This example code allots 1 second for the fade-out action, stops the animation wherever it is after that point, then triggers the fade-in action appropriately.
$(document).on('click', '.item', function (){
    var $this = $(this);
    $this.fadeOut('slow');
    setTimeout(function() {
        $this.stop()
            .appendTo('#shoppingChart')
            .fadeIn('slow');
    }, 1000);
});


text:
Q: VC++ Interop DLL: Binary was not built with debug information I have a VC++ (.exe) application built in Visual Studio 2019. In project properties I have set to generate debug information for it.
Configuration Properties --> C/C++ --> Debug information format --> Program Database for Edit and Continue (/ZI)
Configuration Properties --> Linker --> Debugging --> Generate Debug Info --> Generate Debug Information (/DEBUG) (Also I have tried here: Generate Debug Information optimized for sharing and publishing (/DEBUG:FULL)

In the output it generates three files:
myApp.exe
myApp.pdb
myApp.Interop.dll

Now from another C# app I launched this VC++ exe app by using Process.Start("myapp.exe") in order to communicate between them later.
Now I am trying to debug C# and VC++ apps so I open two instances of VS, one for each app.
From VS I start debugging the C# app and from the another VS I attach to the process VC++ app. In the VS where I have launched my C# app, in modules window I can see below message:
C:\Users\myUser\AppData\Local\assembly\dl3\C23J1LN6.XOZ\GJPNWB74.YC1\bdcce8ba\10fb0e7d_e918d801\myApp.Interop.dll --> Binary was not built with debug information

Why isn't it capable to find my myApp.pdb file that was generated? all myApp.* are in the same directory.

A: It looks like an issue with the debugger type that you are using in the solution with the C# project. Visual Studio will default to "Managed only" when debugging a C# project. However, you want to debug both the C# project and the associated C++ dll. When trying to load the symbols for a native application / shared library it will fail as if there were no valid symbols.
Depending on how you attach to the C# executable:

*

*if you are starting the executable directly from Visual Studio, you need to check "Enable native code debugging" in the Debug tab of your project properties [1];

*if you are starting the executable externally and only later attaching using Visual Studio, you need to select "Native" and "Managed" clicking on the Select button in the "Attach to" row.

References

*

*[1] https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-debug-managed-and-native-code#configure-mixed-mode-debugging

*[2] https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-debug-in-mixed-mode


text:
Q: what does "I did not know you had been ill." mean exactly
I did not know you had been ill.

the person began to be ill before I knew it, but does that mean she is still ill or has the person recovered from his illness or does it depend on the
context and without context is it possible to know if she is still ill

A: "You had been ill" is past perfect tense, so it is set in the past. You are looking back from a moment in the past. If you want to express that someone is still ill in the present you`d have to say: "I didn't know you have been ill".
"I didn't know" is also in the present, because before now you didn't know but now you do.

A: If you had been ill, you are no longer ill. You were ill at some point in the past. When you were ill is not relevant. The fact is that you were ill and you are now well.
I did not know informs us that you were not aware that the person concerned had been ill.
Typically, you might meet someone whom you had not seen for some time.
This person might tell you that s/he had been ill.
You might reply that:I did not know that you had been ill.
You are both talking about something that took place in the past of which you were ignorant.
If that were changed to present perfect: I did not know that you have been ill, it signifies that the illness was recent. It is not clear whether the person concerned is well again.
The context is necessary to make the details clear.


text:
Q: Bootstrap: Floating labels with label before input field I want to use floating labels with some input fields.
The for is based on Bootstrap 4 styles but I can't change the structure of the elements.
I found this example for floating labels: https://www.cssscript.com/demo/bootstrap-4-form-floating-labels/
The problem is, that the HTML structure is different and in the example the input field comes before the label field. It's the opposite in my code and I can't change that part.
I figured out, that the CSS in the example works only if the structure is the same.
Here's the CSS code which doesn't work with my structure:
.form-label-group input:not(:placeholder-shown) ~ label {
  padding-top: calc(var(--input-padding-y) / 3);
  padding-bottom: calc(var(--input-padding-y) / 3);
  font-size: 12px;
  color: blue;
}

It needs the label after the input.
My HTML structure looks like this:

    First Name *

        <input type="text" class="input-text form-control" name="billing_first_name" id="billing_first_name" placeholder="" value="First Name" autocomplete="given-name">

As you can see, the label comes before the input.
I couldn't figure out how to change that.
If I change the CSS to this:
.form-label-group label ~ span input:not(:placeholder-shown) {

It will style the input instead of the label element.
Is there any other way?


text:
Q: How to integrate $\mid xy - x - y \mid $ I'm studying the region $D = \{(x,y)\in\mathbb{R}^2:0\leq x \leq 3 \land 2 \leq y \leq 4\}$ and I want to find where  $ xy - x - y \leq 0$ and  $ xy - x - y \geq 0$. I need to integrate the absolute value of this polynomial on $D$ and I want to spit the integral up. I just don't know how to split $D$ up, some help would be appreciated.

A: Draw a figure! It shows the rectangle $D=[0,3]\times[2,4]$ and the hyperbola $(x-1)(y-1)=1$, whose right branch intersects the top and bottom edges of $D$ at $x={4\over3}$ and at $x=2$.  To simplify the computations we write the arc $\gamma$ within $D$ in the form
$$x={y\over y-1}\qquad(2\leq y\leq 4)\ .$$
To the left of $\gamma$ we have $xy-x-y<0$, and to the right of it we have $xy-x-y>0$. We therefore can write
$$\int_D|xy-x-y|\>{\rm d}(x,y)=\int_2^4\left(\int_0^{y/(y-1)}(x+y-xy)\>dx +\int_{y/(y-1)}^3(xy-x-y)\>dx\right) \,dy$$
My computer obtained $8+\log 3$ as end result.

A: Let us call $f(x,y)=x+y-xy$. Then you are interested in
$$
A=\{(x,y)\in D~:~f(x,y)\geq 0\}\text{ and }B=\{(x,y)\in D~:~f(x,y)\leq0\}.
$$
First, we consider
$$
f(x,y)=x+(1-x)y.
$$
We can see that $x=1$ is somehow special. If $x\in[0,1]$ and $y\geq 0$, then $x+(1-x)y$ is a sum of two nonnegative numbers. Hence $f(x,y)\geq 0$. So we can see $[0,1]\times[2,4]\subseteq A$.
Next, for $x>1$ we see
$$
x+(1-x)y\geq 0\Leftrightarrow x\geq (x-1)y \Leftrightarrow y\leq \frac{x}{x-1}.
$$
Define $g(x)=\frac{x}{x-1}$. Then $A$ contains all $(x,y)$ below the graph of $g$. But $g(x)>4$ for $x\in\left(1,\frac43\right)$ and $g(x)<2$ for $x>2$. Therefore,
$$
A=\left[0,\frac43\right]\times[2,4]\cup \left\{(x,y)~:~2\leq y\leq g(x),~x\in\left[\frac43,2\right]\right\}
$$
and
$$
B=\left\{(x,y)~:~4\geq y\geq g(x),~x\in\left[\frac43,2\right]\right\}\cup[2,3]\times[2,4].
$$


text:
Q: DynamoDB Query / Scan with combined conditions I am facing an architectural problem (or a logical one) and am not sure what is the best way to proceed. I am building a small matchmaking app to study AWS Mobile HUB and it's services and get a bit more familiar with it.
My DynamoDB contains a table with rendezvous that have the following 2 properties (and some more which are not important here):
Rendezvous

- from_gender
- interest_gender

Additionally i am using cognito and have my users have a property
User

- usr_gender
- interest_gender

Basically I want to match up users that are interested in from_gender and possess a gender of interest_gender
At the moment, User can be either male or female whereas interest_gender can be either male, female or all.
This means for a user we have 6 combinations:
Gender -> Interested In

Male -> female
Female -> female
Female -> all
Male -> all
Male -> male
Female -> male

Now it gets tricky:
Example
User A (female interested in all) is looking for rendezvous
She should be shown the 4 following rendezvous types:
from_gender, interest_gender

male, female
male, all
female, female
female, all

which means that I would need a query of sorts (dummycode):

rendevous.query("
(from_gender = male) AND ((interest_gender = female") OR (interest_gender = all)) OR
(from_gender = female) AND ((interest_gender = female") OR (interest_gender = all))
")

However
I have not yet found a way to get this working with query or scan as they do not support OR queries on the same property.
I tried
to create indeces (using codes for the different combinations, but i did not find a way to create a queryable index for all cases), note that additionally to this interest I would also need to sort by age (between min / max) and location min/max lat, min/max long.
Are there any smart approaches using DynamoDB or am I forced to go the SQL route?
This is the query expression I have tried latest: Works
func generateScanExpression() -> AWSDynamoDBScanExpression {
    let usr = UserHelper.sharedHelper.currentUser
    let expression = AWSDynamoDBScanExpression()
    expression.limit = 10

    // Male interested in male
    if (usr?.interest == Constants.CONST_MALE) && (usr?.gender == Constants.CONST_MALE){
        expression.filterExpression = "details_fromGender = :fg AND ( match_interest = :ig OR match_interest = :all )"
        expression.expressionAttributeValues = [":fg": Constants.CONST_MALE, ":ig": Constants.CONST_MALE, ":all": Constants.CONST_ALL ]
    }
    // Female interested in female
    if (usr?.interest == Constants.CONST_FEMALE) && (usr?.gender == Constants.CONST_FEMALE){
        expression.filterExpression = "details_fromGender = :fg AND ( match_interest = :ig OR match_interest = :all )"
        expression.expressionAttributeValues = [":fg": Constants.CONST_FEMALE, ":ig": Constants.CONST_FEMALE, ":all": Constants.CONST_ALL ]
    }
    // Male interested in female
    if (usr?.interest == Constants.CONST_FEMALE) && (usr?.gender == Constants.CONST_MALE){
        expression.filterExpression = "details_fromGender = :fg AND ( match_interest = :ig OR match_interest = :all )"
        expression.expressionAttributeValues = [":fg": Constants.CONST_FEMALE, ":ig": Constants.CONST_MALE, ":all": Constants.CONST_ALL ]
    }
    // Female interested in male
    if (usr?.interest == Constants.CONST_MALE) && (usr?.gender == Constants.CONST_FEMALE){
        expression.filterExpression = "details_fromGender = :fg AND ( match_interest = :ig OR match_interest = :all )"
        expression.expressionAttributeValues = [":fg": Constants.CONST_MALE, ":ig": Constants.CONST_FEMALE, ":all": Constants.CONST_ALL ]
    }
    // Male interested in all
    if (usr?.interest == Constants.CONST_ALL) && (usr?.gender == Constants.CONST_MALE){
        expression.filterExpression = "( details_fromGender = :fg OR details_fromGender = :all ) AND match_interest = :ig"
        expression.expressionAttributeValues = [":fg": Constants.CONST_MALE, ":ig": Constants.CONST_MALE ]
    }
    // Female interested in all
    if (usr?.interest == Constants.CONST_ALL) && (usr?.gender == Constants.CONST_FEMALE){
        expression.filterExpression = "( details_fromGender = :fg OR details_fromGender = :all ) AND match_interest = :ig"
        expression.expressionAttributeValues = [":fg": Constants.CONST_MALE, ":ig": Constants.CONST_FEMALE ]
    }

    return expression
}

A: Are you absolutely certain you can't use an OR condition on a DynamoDB scan operation? I'm not saying you're wrong, I just seem to remember doing it. Here is some code I would try if I were working on the same issue:
func findMatches(interestGender: String, userGender: String, allCondition: String, map: AWSDynamoDBObjectMapper) -> AWSTask<AnyObject> {
    let scan = AWSDynamoDBScanExpression()
    scan.filterExpression = "interest_gender = :interestGender AND usr_gender = :userGender OR interest_gender = :allCondition"
    scan.expressionAttributeValues = [":interest_gender":interestGender, ":usr_gender":userGender, ":interest_gender":allCondition]

    return map.scan(Rendezvous.self, expression: scan).continue({ (task: AWSTask) -> AnyObject? in
        if (task.error != nil) {
            print(task.error)
        }

        if (task.exception != nil){
            print(task.exception)
        }

        if let result = task.result {
            return result.items as! [Rendezvous] as AnyObject?
        }

        return nil
    })

}

This would assume that you have your Rendezvous object that conforms to AWSDynamoDBObjectModel and AWSDynamoDBModeling. Try it, and let me know if it works for you, otherwise I'll delete my answer. I don't have the ability to test it for you until much later tonight, so I'm not 100% certain it will work.


text:
Q: How can I use reflection to find the properties which implement a specific interface? Consider this example:
public interface IAnimal
{
}

public class Cat: IAnimal
{
}

public class DoStuff
{
    private Object catList = new List<Cat>();

    public void Go()
    {
        // I want to do this, but using reflection instead:
        if (catList is IEnumerable<IAnimal>)
            MessageBox.Show("animal list found");

        // now to try and do the above using reflection...
        PropertyInfo[] properties = this.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            //... what do I do here?
            // if (*something*)
                MessageBox.Show("animal list found");
        }
    }
}

Can you complete the if statement, replacing something with the correct code?
EDIT:
I noticed that I should have used a property instead of a field for this to work, so it should be:
    public Object catList
    {
        get
        {
          return new List<Cat>();
        }
    }

A: You can look at the properties' PropertyType, then use IsAssignableFrom, which I assume is what you want:
PropertyInfo[] properties = this.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
    if (typeof(IEnumerable<IAnimal>).IsAssignableFrom(property.PropertyType))
    {
        // Found a property that is an IEnumerable<IAnimal>
    }
}

Of course, you need to add a property to your class if you want the above code to work ;-)

A: Please note that in your example, catList would not be found with GetType().GetProperties ().  You would use GetType().GetFields () instead.
If you are trying to determine whether the property is defined as IEnumerable you can do this:
if (typeof(IEnumerable<IAnimal>) == property.PropertyType)
{
   MessageBox.Show("animal list found");
}

If you want to know if you can assign the value of the property into a IEnumerable<IAnimal>, do this:
if (typeof(IEnumerable<IAnimal>).IsAssignableFrom (property.PropertyType))
{
   MessageBox.Show("animal list found");
}

If the property type is not specific enough (like object Animal{get;set;}) to get your answer, you will need to get the value to decide.  You can do this:
object value = property.GetValue(this, null);
if (value is IEnumerable<IAnimal>)
{
   MessageBox.Show("animal list found");
}

A: Another way to do it is just call GetProperties() on the interface from within the object, opposed to on the object itself.
public static void DisplayObjectInterface(object source, Type InterfaceName)
{
    // Get the interface we are interested in
    var Interface = source.GetType().GetInterface(InterfaceName.Name);
    if (Interface != null)
    {
        // Get the properties from the interface, instead of our source.
        var propertyList = Interface.GetProperties();
        foreach (var property in propertyList)
            Debug.Log(InterfaceName.Name + " : " + property.Name + "Value " + property.GetValue(source, null));
    }
    else
        Debug.Log("Warning: Interface does not belong to object.");

}

I like to make InterfaceName parameter a Type to avoid any typo errors when looking up GetInterface() by string name.
Usage:
DisplayObjectInterface(Obj, typeof(InterFaceNameGoesHere));

EDIT: I just noticed that your example was a collection, this will not work on a collection passed as a whole. You would have to pass each item individually. I'm tempted to delete but this will probably help others that google this same question looking for a non-collection solution.


text:
Q: Is there a way to dynamically draw lines between points over a coordinate plane? I am completing a project in which I have implemented a brute force algorithm for solving the Convex Hull problem. I need to also create a visual for this algorithm. I am trying to create a coordinate plane ranging from (-100, 100) on both the x and y axis, plot all the points in the complete set, and dynamically draw lines between the points in order to create the convex hull. For example, assume I have 4 points: A(1, 1), B(3,2), C(2, 4), and D(1,3). I want to first plot all four of these points and then draw a line from A to B and then from B to C and then from C to D and then finally from D to A. So far I have been trying to do this using JavaFX LineChart.
//        creating axis
        NumberAxis xAxis = new NumberAxis(-100, 100, 1);
        NumberAxis yAxis = new NumberAxis(-100, 100, 1);
//        creating chart
        LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);

and then drew lines using
   public static void populatePoints(List<Double []> points, LineChart lineChart) {
        XYChart.Series series = new XYChart.Series();
        series.setName("Points of set");
        for (Double[] point : points) {
            series.getData().add(new XYChart.Data<Double, Double>(point[0], point[1]));
        }
        lineChart.getData().add(series);
    }

However, this just draws the lines in a typical line chart fashion. I need it to be in a convex shape. I have attached the result of my current code with points (-51.6, 72.97), (33.58, 98.97), (-86.68, 9.77), and (-49.41, -46.26).

A: You can use the approach shown here:

*

*Add the points to the series in the desired order.

*Specify SortingPolicy.NONE.
  series.getData().add(new XYChart.Data(-86.68,  9.77));
  series.getData().add(new XYChart.Data(-51.6,   72.97));
  series.getData().add(new XYChart.Data( 33.58,  98.97));
  series.getData().add(new XYChart.Data(-49.41, -46.26));
  series.getData().add(new XYChart.Data(-86.68,  9.77));
  …
  policy.getSelectionModel().select(LineChart.SortingPolicy.NONE);


text:
Q: Linker error and unexpected run-time behavior when compiling C++ class library on RHEL I wrote a small C++ class library and driver program to run on RHEL, as a learning exercise.  When building the library, there is usually a linker error that I don't understand.  Trial and error shows that I can eliminate the error by limiting what I try to write using printf/fprintf (e.g. don't hard-code characters in the format string, and only use the %c conversion spec.)  When I run the driver in the form it allows me to build, the output looks suspiciously like it's not executing as coded.
Here are the commands I'm using to build:
libxor.so: xor.cpp
    g++ -c -o xor.o xor.cpp
    gcc -shared -o libxor.so xor.o

drv: drv.cpp libxor.so
    g++ -o drv drv.cpp -L/home/xxx/source -lxor

Here is the linker error:
g++ -c -o xor.o xor.cpp
gcc -shared -o libxor.so xor.o
/usr/bin/ld: xor.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output
collect2: error: ld returned 1 exit status
make: *** [Makefile:5: libxor.so] Error 1

Statements in drv.cpp to write output don't cause problems, only in xor.cpp.  The statements it allows me to include in xor.cpp without breaking the build look like:
printf("%c", plainText[curSubscript]);

If I put more in the format string, or use a different conversion spec, I get the linker error.  I'd appreciate any help with this, i.e. what is causing the linker error and why would the output of the program be possibly unexpected when I eliminate the linker error.  Thanks.


text:
Q: JTable throwing IndexOutOfBoundsException during paint Hi I'm building an application using a JTable to display data from a database and I keep getting an IndexOutOfBoundException from tableModel.getValueAt(row,col) during painting. I debugged the code and it seems like the data isn't being saved to the DefaultTableModels data vector.
This is my code...
    public class TableFrame extends JFrame{
        public static void main(String[] args){
            TableFrame frame = new TableFrame();

        }

        private TablePanel tablePanel;
        public TableFrame(){
            super();
            setSize(new Dimension(500,500));
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            tablePanel = new TablePanel();
            add(tablePanel);

            updateLabels();
            setVisible(true);
        }

        public void updateLabels() {
            setTitle("Main Frame");

            tablePanel.updateLabels();
        }

        private static class TablePanel extends JPanel{

            private DefaultTableModel tableModel;
            private DefaultTableColumnModel colModel;
            private JTable table;

            private JPanel buttonPanel;
            private JButton refreshButton;

            public TablePanel(){
                setLayout(new BorderLayout());

        buttonPanel = new JPanel(new FlowLayout());
        refreshButton = new JButton();
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                refreshData();
            }
        });
        buttonPanel.add(refreshButton);
        add(buttonPanel,BorderLayout.NORTH);

        //TODO:Set the column renderers and editors
        colModel = new DefaultTableColumnModel();
        colModel.addColumn(new TableColumn(0,75));
        colModel.addColumn(new TableColumn(0,75));
        colModel.addColumn(new TableColumn(0,75));
        colModel.addColumn(new TableColumn(0,75));
        colModel.addColumn(new TableColumn(0,75));
        colModel.addColumn(new TableColumn(0,75));
        colModel.addColumn(new TableColumn(0,75));
        colModel.addColumn(new TableColumn(0,75));
        colModel.addColumn(new TableColumn(0,75));
        colModel.addColumn(new TableColumn(0,75));
        colModel.addColumn(new TableColumn(0,75));

        tableModel = new DefaultTableModel();

        table = new JTable(tableModel,colModel);

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane,BorderLayout.CENTER);

        updateLabels();
    }

    //This is going to query data from a database and populate the table
    //problem occurs during painting
    public void refreshData(){
        Random rand = new Random();

        for(int i=0;i<1000;i++){
            Vector<Object> fields = new Vector<Object>();
            for(int j=1;j<=11;j++){
                fields.add(rand.nextInt());
            }
            tableModel.addRow(fields);
        }
    }

    public void updateLabels() {
        colModel.getColumn(0).setHeaderValue("Col 1");
        colModel.getColumn(1).setHeaderValue("Col 2");
        colModel.getColumn(2).setHeaderValue("Col 3");
        colModel.getColumn(3).setHeaderValue("Col 4");
        colModel.getColumn(4).setHeaderValue("Col 5");
        colModel.getColumn(5).setHeaderValue("Col 6");
        colModel.getColumn(6).setHeaderValue("Col 7");
        colModel.getColumn(7).setHeaderValue("Col 8");
        colModel.getColumn(8).setHeaderValue("Col 9");
        colModel.getColumn(9).setHeaderValue("Col 10");
        colModel.getColumn(10).setHeaderValue("Col 11");

                refreshButton.setText("Refresh");

                repaint();
            }
        }
    }

This is the exception...
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Vector.java:447)
at TableFrame$TablePanel.refreshData(TableFrame.java:108)
at TableFrame$TablePanel$1.actionPerformed(TableFrame.java:64)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2012)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2335)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:404)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6268)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6033)
at java.awt.Container.processEvent(Container.java:2045)
at java.awt.Component.dispatchEventImpl(Component.java:4629)
at java.awt.Container.dispatchEventImpl(Container.java:2103)
at java.awt.Component.dispatchEvent(Component.java:4455)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4633)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4297)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4227)
at java.awt.Container.dispatchEventImpl(Container.java:2089)
at java.awt.Window.dispatchEventImpl(Window.java:2517)
at java.awt.Component.dispatchEvent(Component.java:4455)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:649)
at java.awt.EventQueue.access$000(EventQueue.java:96)
at java.awt.EventQueue$1.run(EventQueue.java:608)
at java.awt.EventQueue$1.run(EventQueue.java:606)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:116)
at java.awt.EventQueue$2.run(EventQueue.java:622)
at java.awt.EventQueue$2.run(EventQueue.java:620)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:105)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:619)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)

I debugged the code and added a call to tableModel.getDataVector().getElementAt(0).getElementAt(0) and tableModel.getRowCount(). getRowCount() returned 1000 but getElementAt() resulted in the IndexOutOfBounds exception, just like in the awt event queue. I think what I did should work but obviously there's something I'm missing.

A: The TableModel doesn't refer to the ColumnModel to get the number of columns so this has to be set using tableModel.setColumnCount(). Otherwise the defaultTableModel justifies the data and truncates the row to the number retreived by getColumnCount().


text:
Q: Update date field from MAX date in another table I'm trying to update a DATETIME field in one table based on the latest date from another. The common field between the two tables is named msisdn. I was trying this
update table1 t1
join table2 t2
on t1.msisdn = t2.msisdn
set t1.bill_attempt = (Select max(event_time) from table2
where t1.msisdn = t2.msisdn)

In table1 I'm getting the latest same event time for all msisdn records. Please assist

A: Either:
UPDATE table1 t1
SET bill_attempt =
      ( SELECT MAX(event_time)
        FROM table2 t2
        WHERE t1.msisdn = t2.msisdn
      )

or:
UPDATE
      table1 t1
  JOIN
      ( SELECT msisdn
             , MAX(event_time) AS event_time
        FROM table2
        GROUP BY msisdn
      ) AS t2
  ON t1.msisdn = t2.msisdn
SET t1.bill_attempt = t2.event_time

A: UPDATE table1 t1
JOIN (SELECT MAX(event_time) AS event_time,msisdn FROM table2 GROUP BY msisdn) t2
ON t1.msisdn = t2.msisdn
SET t1.bill_attempt = t2.event_time


text:
Q: If you had been eating vs was eating Which one is correct ?:
1)-"If you had been eating well you wouldn't be scrawny."
2)-"If you was eating well you wouldn't be scrawny."
3)-"If you ate well you wouldn't be scrawny."--> this's incorrect because it's second conditional to talk about future/present ( If you did this, this would happen, even if the verb is in the past.) right ?

A: #1 is fine.  That's the mixed type conditional: if this thing had happened (in the past), then (some present conditional or perfect conditional).
#2 is wrong because in standard English you never say "You was".  If you change it to "If you were eating well...) it would be fine, because then it would be a present unreal conditional, of Type 2, using were because of the subjunctive mood.  If you were eating well (right now), then you wouldn't be scrawny.
#3 is also fine!  It's actually just Type 2 again: simple past + present conditional or present continuous conditional.  The Type 2 can be used to talk about the present or future.  Yes, it looks weird to use the simple past with a statement about the present or future, but in this context ate doesn't really refer to the past the way that had been eating does; it's the way we use the "simple past" to refer to a general hypothetical condition: If you ate well (in general, without any time reference), you wouldn't be scrawny.
Reference: Conditional


text:
Q: RxJS non-blocking pooling I'm working with Amazon Transcribe Service and in the SDK doesn't have any way to get when the transcription job has finished.
So we need to pool that information. Nowdays we have the following working code...
const jobid = nanoid();

await amazonTrascribeClient
  .startTranscriptionJob({
    IdentifyMultipleLanguages: true,
    TranscriptionJobName: jobId,
    Media: {
      MediaFileUri: "s3://file-location",
    },
    Subtitles: {
      OutputStartIndex: 1,
      Formats: ["vtt", "srt"],
    },
    OutputBucketName: `file-location`,
    OutputKey: `transcriptions/${jobId}/`,
  })
  .promise();

// HELP HERE:
const callIntervalFunc = () => {
  const callInverval = setInterval(async () => {
    const { TranscriptionJob } = await amazonTrascribeClient
      .getTranscriptionJob({ TranscriptionJobName: jobId })
      .promise();

    if (
      ["COMPLETED", "FAILED"].includes(TranscriptionJob.TranscriptionJobStatus)
    ) {
      clearInterval(callInverval);

      // Persist in database etc...
    }
  }, 2000);
};

callIntervalFunc();

But as you can see it's extremally expensive and don't work in the concurrency mode since it's lock the thread. The objective is pool the information without block the event loop, some people said to use fire and forget, but I have no idea where I should start.


text:
Q: Can we create mac app on older xcodes (8.x ,6.x) and older MAcosx (10.11) and notarise them We have our build systems in older macosx (10.11) and xcode 8 & 6 .Recently apple has introduced notarisation of apps for catalina (10.15). can i create an app in older macosx (10.11) and try to notarise that in another mac machine which will have xcode 10 and macosx 10.14 .Please let us know its possible or not .

A: Yes, notarization can be performed on any machine with xcode 10 or higher.


text:
Q: "not found" or "is not found" Why there is

file not found
access denied

and so on everywhere, when it should be (as far as I know)

the file was not found
the access is denied

I wonder which is actually correct? Both?

A: "The access" is not a proper construct.  "Your access" is fine, but I don't think it's necessary.  I'd say "Access was denied" if you want to spell it out more than tradition.
"The file was not found" is grammatically proper.
But "File not found" and "Access denied" get your point across just as well

A: As a programmer, I suspect that the message is coming from an underlying error class. The application is merely reporting the name of the type of error that occurred; it's not trying to have an intelligent conversation with the user.
This answer applies to programming in general, but here is an example of a list of status codes in the HTTP protocol. See
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error .
You will recognize some of them as messages you have received in your web browser at one time or another.

A: These are status messages similar to traffic signs like No Parking, One Way etc.
Even many news headlines in newspaper are very short and are not full sentences like "Man shot dead", "Man shot at", "Gold up" etc.
Statuses, titles etc need not be full sentences.

A: I think the main reason terse language, such as this, is used for error messages is simple: people don't want to read horrendously long error messages.
Case in point:

The computer searched the file system, unfortunately however, the file was not found.

Versus

file not found.

It's simple and yet it conveys all of the necessary information.
To answer your question, the shortened messages would not be appropriate anywhere that formal language is used. However, "the access is denied" is incorrect.  You would not use "the" to refer to access, in this case.  To be formal, you would say something like "Access to the resource was denied."

A: That probably comes from limited memory in the early days of computing, where  typing out a proper sentence would take up more memory and might cause problems.  It would have made things simpler to use an improper sentence that still got it's point across.  These days though it would hardly make any difference.


text:
Q: How to set a fixed screen size in flutter app I would like to test my flutter app on a real device (no emulator) but would like to set a smaller screen size.
As this is just for development how the app looks on smaller devices, the space around can just be empty.
I tried wrapping the Scaffold or the MaterialApp in a Container, SizedBox, ... with fixed sizes but it always takes up the whole screen.

A: What you need is device_preview plugin - you will be able to simulate the app running on different devices' types even when launching on your physical device.
Just remember not to release the app with this plugin implemented.


text:
Q: What is the best way to get an elements opposite index in an array? Say I have array
{0, 1, 2, 3, 4}

*

*index 0 and 4 are opposites

*index 1 and 3 are opposites

*index 2's opposite is undefined

Or
 {0, 1, 2, 3, 4, 5}

*

*index 0 and 5 are opposites

*index 1 and 4 are opposites

*index 2 and 3 are opposites

I remember seeing a really clever way to do this. Something like
i%array.length

A: Try this one:
oppIndex = array.length - firstIndex - 1;

A: array = {1, 2, 3, 4, 5}
idx = 0 /* 0 is the first array position with value of 1 */

IF array.length - idx - 1 > idx
   RETURN array[ array.length - idx - 1 ] /* returns array[4] == 5 */
ELSE
   RETURN undefined

array = {1, 2, 3, 4, 5}
idx = 2 /* 2 is the third array position with value of 3 */

IF array.length - idx - 1 > idx /* 5 - 2 - 1 == 2 which is NOT greater than 2 */
   RETURN array[ array.length - idx - 1 ]
ELSE
   RETURN undefined

A: Following what your first example logic ...
       if (array.length%2==0){
            for (int i =0; i<array.length/2; i++){
                   syso("the opposite of "+ array[i] + " is " + array[array.length -1-i]
             }
       }
       else {
           for (int i =0; i<floor(array.length/2); i++){
                   syso("the opposite of "+ array[i] + " is " + array[array.length -1-i]
             }
             i = i+1
              syso("the opposite of "+ array[i] +" is undefined"
       }


text:
Q: having chrome extensions pulling data from ruby db I would like to build a chrome extension (CE) that pulls data from a ruby db for a specific user.  So, in a basic example, if an user submits their favorite color as 'red' and sport as 'tennis' into the db from the core website, when they click the CE, 'red' and 'tennis' will show up no matter where they are on the internet.
Any guidance on how to build something like this?  Seems quite simple but am not sure how the CE files fit in with the ruby folder framework.
Also, is it possible to write to a ruby database from a popped out CE? i.e. - submitting 'red' and 'tennis' from the CE to the ruby database to go along with the previous example.  Any guidance?
Cheers

A: This is a very general question so it sounds like you will need to learn a lot. Which can be a good thing :)
Here are the general steps you need:

*

*Look into building an API for your ruby application. This will allow you to get data from your database. For example, you can
make an app where you go to http://yoursite.com/api/favorites and that will return a list of all favorites as JSON. Then in your Chrome Extension you can parse the JSON and display the results to the user. You will probably want to do this using an ajax call (see jquery.ajax for an easy way to use ajax).

*Assuming you want user accounts, your user will need to be logged in. Then you can use your user's cookies to verify that they are logged in and show them custom info. i.e. going to http://yoursite.com/api/favorites will just show the favorites for that user, not for everyone.

*Finally, submitting things to the database...you can have another route where users can send stuff. For example, if you go to http://yoursite.com/api/favorites/add?color=red then it will add the color red to that user's favorites. You will need to write all the logic for adding stuff to the database...again, it might help you to go through a rails tutorial and then look at building an API.
Related to #3, look into RESTful APIs. A good convention is that if you issue a GET request, you're asking for data, but if you issue a POST request, you are adding data (in your case, creating a new favorite).
Finally, for terminology: it's not a "ruby" database, it's just a database. You can access a database using almost any language, and it sounds like you are accessing it using ruby right now :)

A: If you only need to store data for one machine browsing anywhere online, chrome has a storage api that would work great.
If you do need a ruby server, I would recommend looking at sinatra.


text:
Q: Setting cutplanes for polygon shape I am using Autodesk.Viewing.Markupscore extension to draw a polygon in 3D view in top view (orthographic)
I want to see only those elements which are inside the polygon
For which I am using the cutplanes concept because bounding box logic is taking too long to process.
So Please suggest a way to apply cut planes along these lines.

A: Try programmatically cutplanes with an array of vector4s specifying the four sides say:
vectorArray.push(new THREE.Vector4 (0.9999999999999998, 0, 0, 0.06520926952362059)) //x,y,z,w
viewer.setCutPlanes(vectorArray)

See documentation here


text:
Q: Gauge needle for plotly indicator graph I currently have an indicator chart (gauge) from plotly where the value is shown by how far a dark blue center reaches. However, that looks a bit odd to me, so I would like to change it to have a needle/pointer from the center to the value, like a speedometer. Here is my current code:
import plotly.graph_objects as go
fig = go.Figure(go.Indicator(
    mode = "gauge+number",
    number = {'suffix': "% match", 'font': {'size': 50}},
    value = 80,
    domain = {'x': [0,1], 'y': [0,1]},
    gauge = {
        'axis': {'range': [None, 100], 'tickwidth': 1, 'tickcolor': "darkblue"},
        'bar': {'color': "darkblue"},
        'bgcolor': "white",
        'borderwidth': 2,
        'bordercolor': "gray",
        'steps': [
            {'range': [0, 33], 'color': 'red'},
            {'range': [33, 66], 'color': 'yellow'},
            {'range': [66,100], 'color': 'green'}],
        }))

fig.update_layout(font = {'color': "black", 'family': "Arial"})

fig.show()

A: My suggestion would be to add an arrow annotation that overlays the indicator chart.
By setting the range of the chart to [-1,1] x [0,1] we are basically creating a new coordinate system that the arrow will be on, we can approximate where the arrow should go to in order to correspond to the value on your indicator chart. This will also ensure that the point (0,0) is at the center of your chart which is convenient since that will be one of the arrow's endpoints.
When adding an arrow annotation ax and ay are coordinates for the tail of your arrow, so we want that in the middle of our chart which would be at ax=0 and ay=0. I placed the arrow straight up to show that the radius of the indicator chart with respect to the chart is approximately 0.9 units for my browser window. This may be different for yours.
import plotly.graph_objects as go

fig = go.Figure(go.Indicator(
    mode = "gauge+number",
    number = {'suffix': "% match", 'font': {'size': 50}},
    value = 80,
    domain = {'x': [0,1], 'y': [0,1]},
    gauge = {
        'axis': {'range': [None, 100], 'tickwidth': 1, 'tickcolor': "darkblue"},
        'bar': {'color': "darkblue"},
        'bgcolor': "white",
        'borderwidth': 2,
        'bordercolor': "gray",
        'steps': [
            {'range': [0, 33], 'color': 'red'},
            {'range': [33, 66], 'color': 'yellow'},
            {'range': [66,100], 'color': 'green'}],
        }))

fig.update_layout(
    font={'color': "black", 'family': "Arial"},
    xaxis={'showgrid': False, 'range':[-1,1]},
    yaxis={'showgrid': False, 'range':[0,1]},
    # plot_bgcolor='rgba(0,0,0,0)'
    )

## by setting the range of the layout, we are effectively adding a grid in the background
## and the radius of the gauge diagram is roughly 0.9 when the grid has a range of [-1,1]x[0,1]

fig.add_annotation(
    ax=0,
    ay=0,
    axref='x',
    ayref='y',
    x=0,
    y=0.9,
    xref='x',
    yref='y',
    showarrow=True,
    arrowhead=3,
    arrowsize=1,
    arrowwidth=4
    )

fig.show()

Now while we could use trial and error to find where the arrow should end, that's a truly hacky solution which isn't generalizable at all.
For the next steps, I would recommend you choose an aspect ratio for your browser window size that keeps the indicator chart as close to a circle as possible (e.g. an extreme aspect ratio will make your indicator chart more elliptical, and I am making a simple assumption that the indicator chart is a perfect circle).
So, under the assumption that the indicator chart is roughly a circle with radius ≈ 0.9 (in my case, your radius might be different), we can find the x and y coordinates of your circle using polar coordinates: x = r*cos(θ) and y = r*sin(θ). Note that this formula is only valid for a circle centered at (0,0), which is why we centered your chart at this point.
Since the value on the indicator is 80 on a scale of 0-100, we are 80/100 of the way of an 180 angle of rotation, which comes out to 180 degrees*(80/100) = 144 degrees. So you are rotating 144 degrees clockwise from the lower left corner, or 36 degrees counterclockwise from the lower right corner.
Plugging in, we get x = 0.9*cos(36 degrees) = 0.72811529493, and y = 0.9*sin(36 degrees) = 0.52900672706. Updating the annotation:
fig.add_annotation(
    ax=0,
    ay=0,
    axref='x',
    ayref='y',
    x=0.72811529493,
    y=0.52900672706,
    xref='x',
    yref='y',
    showarrow=True,
    arrowhead=3,
    arrowsize=1,
    arrowwidth=4
    )

We get the following image:

So this is pretty close but not an exact science. For my browser window, let's adjust the angle slightly higher to 40 degrees. Repeating the same process x = 0.9*cos(40 degrees) = 0.6894399988, and y = 0.9*cos(40 degrees) = 0.57850884871, and updating the annotation coordinates, I get the following chart:

To make the chart prettier, we can now remove tick labels of the chart for the arrow annotation, and also make the background transparent. And to make this method more easy to adjust, I have made theta and r variables.
from numpy import radians, cos, sin
import plotly.graph_objects as go

fig = go.Figure(go.Indicator(
    mode = "gauge+number",
    number = {'suffix': "% match", 'font': {'size': 50}},
    value = 80,
    domain = {'x': [0,1], 'y': [0,1]},
    gauge = {
        'axis': {'range': [None, 100], 'tickwidth': 1, 'tickcolor': "darkblue"},
        'bar': {'color': "darkblue"},
        'bgcolor': "white",
        'borderwidth': 2,
        'bordercolor': "gray",
        'steps': [
            {'range': [0, 33], 'color': 'red'},
            {'range': [33, 66], 'color': 'yellow'},
            {'range': [66,100], 'color': 'green'}],
        }))

fig.update_layout(
    font={'color': "black", 'family': "Arial"},
    xaxis={'showgrid': False, 'showticklabels':False, 'range':[-1,1]},
    yaxis={'showgrid': False, 'showticklabels':False, 'range':[0,1]},
    plot_bgcolor='rgba(0,0,0,0)'
    )

## by setting the range of the layout, we are effectively adding a grid in the background
## and the radius of the gauge diagram is roughly 0.9 when the grid has a range of [-1,1]x[0,1]

theta = 40
r= 0.9
x_head = r * cos(radians(theta))
y_head = r * sin(radians(theta))

fig.add_annotation(
    ax=0,
    ay=0,
    axref='x',
    ayref='y',
    x=x_head,
    y=y_head,
    xref='x',
    yref='y',
    showarrow=True,
    arrowhead=3,
    arrowsize=1,
    arrowwidth=4
    )

fig.show()


text:
Q: How to join JSONs together using foreign key I need to link a few JSONs using foreign key. For example I have three JSONs:
JSON 1 - user
{
   id: 23,
   name: "Agata"
}

JSON 2 - slide
{
   title: "lalala",
   content: "lalalalalal",
   member: [
      {
        //here I would like to add json user  id: 23
      }
   ]
}

JSON 3 - comments
{
   title: "nanana",
   author: // here I would like to add json user id : 23
}

Do you have any ideas?

A: I'm considering you have three vars that contains each JSON objects, you can do it like this :
JSON 1 - user
var json1 = {
   id: 23,
   name: "Agata"
}

JSON 2 - slide
var json2 = {
   title: "lalala",
   content: "lalalalalal",
   member: [
      json1
   ]
}

JSON 3 - comments
var json3 = {
   title: "nanana",
   author: json1
}


text:
Q: .net 5 project requiring .net core 3.1 to be installed I am attempting to upgrade a MonoGame project I am working on to .net 5. I have upgraded all of my nuget packages. Then I changed the target framework to .net 5. The project compiles fine and runs perfectly. However, when I try to run it through my github actions workflow with only installing the .net 5 tools, the compilation fails with the following message:

It was not possible to find any compatible framework version The
framework 'Microsoft.NETCore.App', version '3.1.0' was not found.
  - The following frameworks were found:
      5.0.0 at [/home/runner/.dotnet/shared/Microsoft.NETCore.App]    You can resolve the problem by installing the specified framework
and/or SDK.

If I try to install .net core 3.1 tools also, it will compile.
The project I'm using is here, this is the particular pull request that is failing. (If you are reading this later the commit I am referring to is a876e47)
I have also tried a pre-release version of Serilog.Sinks.Console thinking that was the issue. That did not work. I don't understand what is requiring the Microsoft.NETCore.App 3.1.0 since under Dependencies I can only see version 5.0.0 being required.

A: As Exploding Kitten pointed out in a comment

probably, it's caused by internal monogames' tools, they require 3.1: https://github.com/MonoGame/MonoGame/issues/7400#issuecomment-725422676

which explains the need for .NET Core 3.1.


text:
Q: Jenkins - Archived symlink doesn't works In my Jenkins pipeline, I generate an APK build of my flutter app.
Instead of copying the APK file generated by the build from my project workspace to the jenkins workspace, I want to generate a symlink of this APK in my jenkins workspace.
Which I can do fine.
The problem start when archive an artifact of this symlink.
Here is the post part of my pipeline script (app_releaseln_3.14.apk is the name of my symlink) :
post{
        always {
            //archivage du zip de l'app web et de l'apk de l'app android se situant dans le dossier build_flutter du workspace jenkins
            archiveArtifacts artifacts: "app_releaseln_3.14.apk", fingerprint: true, followSymlinks: true
        }
    }

The Symlink file is generated as an artifact after the build.

The problem when I click on it from the blue ocean interface to download the APK file he is pointing to I get this :

I can't find this location on my server "job/build_flutter/95/"
I'm pretty new to jenkins and even to working on linux server so may be I'm doing something wrong here.
Any help would be appreciated.

A: By today I've come across this problem as well. Inside the filesystem all is okay. And I don't see any management option which might be related to this change.
To me it looks like this could be a problem of Jetty which is the HTTP server used by Jenkins. See
https://www.eclipse.org/jetty/documentation/jetty-9/index.html#serving-aliased-files
Still analyzing ...


text: Q: How do I start a DevTools user flow recording from a dynamic URL? Google recently released their DevTools user flow recorder and it seems like an interesting and easy-to-use tool. One limitation I'm running into is that replaying a recording will always bring you to the page you initiated the recording on. For example, if I create and save a recording on this array processing question then navigate to this git question, running the recording on the latter will redirect me back to the former. I would like to be able to make a recording, then kick it off from whatever page I'm currently viewing. So far, I've tried both removing the URL from the initial step and replacing the initial URL with a JS IIFE that gets the current URL; neither of these have worked.


text:
Q: Animation add to the Stage I created , as you can see below an Animation , but now , I can not figure out how to add to the Stage . Can anyone tell me how ? I searched online and unclear ideas about it . thank you
TextureRegion tex1 = new TextureRegion(new Texture("play_anim_1"));
TextureRegion tex2 = new TextureRegion(new Texture("play_anim_2"));
TextureRegion tex3 = new TextureRegion(new Texture("play_anim_3"));
TextureRegion tex4 = new TextureRegion(new Texture("play_anim_4"));

Animation playerAnimation = new Animation(0.1f, tex1, tex2, tex3, tex4);

you can do something like
stage.addAnimation ( playerAnimation ) ;

?

A: Just like code of m.antkowicz, create class:
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;

public class AnimeActor extends Actor{

    Animation animation;
    TextureRegion currentRegion;

    float time = 0f;

    public AnimeActor(Animation animation) {
        this.animation = animation;
    }

    @Override
    public void act(float delta){
        super.act(delta);
        time += delta;

        currentRegion = animation.getKeyFrame(time, true);
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);
        batch.draw(currentRegion, getX(), getY());
    }
}

for use:
AnimeActor anim = new AnimeActor(animation);
stage.addActor(anim);

A: The best idea is to create an actor extending Actor class that will be wrapping the Animation object. Then in he's act mathod you are getting current KeyFrame and in the draw method you can render it depending on the actor's position
    class MyAnimation extends Actor
    {
        Animation animation;
        TextureRegion currentRegion;

        float time = 0f;

        //... creating animation etc...

        @Override
        public void act(float delta){
            time += delta;

            currentFrame = animation.getKeyFrame(time, true);
        }

        @Override
        public void draw(Batch batch, float parentAlpha) {
            super.draw(batch, parentAlpha);
            batch.draw(currentRegion, getX(), getY());
        }
    }

Now you can create the actor and just add it to the Stage.

This approach is better because:

*

*You don't need to handle rendering in the render Screen's method

*The Z-index will be kept always - in your example the animation will be always over everything since it is rendered after Stage

*You can wrap more code in the single class and even inherit it creating next animation types or joining animation with body etc...

A: solution
public void render () {
    //qui definisco lo stage
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();

    elapsedTime += Gdx.graphics.getDeltaTime();

    batch.begin();
    batch.draw(seaAnimation.getKeyFrame(elapsedTime,true),100,100);
    batch.end();
}


text:
Q: Mechanism to check whether file downloaded successfully I need to check whether file downloaded successfully. My action result is returning CheckedFileStreamResult. However theOnResultExecutedhandler is executed even before the file download is complete.
I am using the following proposed solution in my program:
public class CheckedFileStreamResult : FileStreamResult
    {
        public CheckedFileStreamResult(FileStream stream, string contentType): base(stream, contentType)
        {
            DownloadCompleted = false;
        }

        public bool DownloadCompleted { get; set; }

        protected override void WriteFile(HttpResponseBase response)
        {
            var outputStream = response.OutputStream;
            response.BufferOutput = false;
            using (FileStream fs = new FileStream("D:\\ABC.pdf", FileMode.Open, FileAccess.Read))
            {
                var buffer = new byte[_bufferSize];
                var count = fs.Read(buffer, 0, _bufferSize);
                while (count != 0 && response.IsClientConnected)
                {
                    outputStream.Write(buffer, 0, count);
                    response.Flush();
                    count = fs.Read(buffer, 0, _bufferSize);
                }
                DownloadCompleted = response.IsClientConnected;
            }
        }
        private const int _bufferSize = 0x200;
    }

Using this mechanism I am unable to achieve the desired effect. The OnResultExecuted handler is executed before the file is fully downloaded and DownloadCompleted flag gives a false impression. Please guide me how to proceed.


text:
Q: Routes and regex in Kohana 3.0 New to Kohana... I was wondering if it's possible to use regex for setting up a route that handles all requests except for one, 'main_page' for example?
Thanks for your time

A: you dont need a regex to do that. its like you would do it in the .htaccess
Route::set('main_page', 'main_page(/<action>(/<id>))')
    ->defaults(array(
        'controller'    => 'main_page',
        'action'        => 'some_action',
    ));

Route::set('default', '(<controller>(/<action>(/<id>)))')
    ->defaults(array(
        'controller' => 'welcome',

    ));


text:
Q: Registry Form appears blank? I'm creating a data base for my company, and I'm trying to make it very simple for my colleagues. I created a registry form that has some buttons to go to search forms (I created 2 different forms to locate different things) but the code that I found doesn't allow to modify the registry when I double click.  The code is this:
   DoCmd.OpenForm "Registo", acNormal, "", "[ID]= [Forms]![PesquisaPorNome]![ListaNomes]", acFormPropertySetting, acWindowNormal
   DoCmd.Close acForm, "PesquisaPorNomes"

It was supposed to open my registry form and put the names and other information on the form, but it appears blank.
I don't know if it's the code or if it's the forms that aren't correct for the code to work.
I hope someone can help me.
I'm sorry for my bad English, it isn't my first language.


text:
Q: TypeScript module types for UMD globals? My TypeScript project is compiled for the browser with AMD modules. I include lodash.min.js myself, along with a bunch of other UMD libraries that all declare global variables, like moment and _. I need to tell my TypeScript about the global _ variable for Lodash. How can I do this with imports? If I install @types/lodash and use import * as _ from "lodash";, it tries to dynamically fetch an AMD Lodash module at runtime, which breaks everything.
If I have one file where I declare the _ global, i.e. export declare const _: LodashStatic;, I cannot even import my declaration in another file, or it tries to load stuff at runtime. What is even the point of the declare keyword if TypeScript treats it like a functioning import. I thought declarations just tell the compiler to shut up and that there will be separately loaded stuff at runtime. Lucky for me, I can use declare const _: LodashStatic; in every single one of my hundreds of files and everything works, but it would be nice if I could just declare it once and then import in other files...

A: The usual way to tell Typescript about the existence of global types is through the types array in your tsconfig.json. If you have @types/lodash installed, then having the following in your tsconfig.json should allow you to reference _ anywhere:
{
  "compilerOptions": {
    "types": ["lodash"]
  }
}


text:
Q: The differential of Gauss' map is zero if and only if $S$ is a plane Assume that the second fundamental form of a surface $S$ is identically equal to zero. It is well-known (and easy to be shown) that the surface is part of a plane!
However, let me think geometrically to this situation. The Gauss' map $N$ is constant in this case, so that the span of $\sigma_u$ and $\sigma_v$ (here $\sigma$ denotes the parameterization of $S$) is always the same vector space. Now, from that, can I deduce that $\sigma_u$ and $\sigma_v$ are constant vectors?


text:
Q: Can't install RVM on Ubuntu Good day!
I try to install RVM on Ubuntu 10.04 LTS.
My steps:
$ bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )

$ echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function' >> ~/.bash_profile

Then i open .bashrc and replace
[ -z "$PS1" ] && return

With that
if [[ -n "$PS1" ]]; then

And that i add in the end of file
if [[ -s $HOME/.rvm/scripts/rvm ]] ; then source $HOME/.rvm/scripts/rvm ; fi

fi

Then i try:
$ rvm notes

And i get:
-bash: rvm: command not found

What is wrong?! I tried my steps 100 times and it still doesn't work!

A: Basically, the .bashrc file is executed when you open a new shell. Even though you changed it, you have to open a new shell or log out and back in for the changes to occur.


text:
Q: Kotlin Hashmap: Change key value and subelement value I am new to Kotlin (and Java) and had a question: I have a Hashmap called data. I would like to change the key values (e.g. "Training Day 1" to "Blablabla") and also the values within the ArrayList (e.g. at trainingDay2 change "Player8" to "Player1"). Furthermore I would like to add elements to trainingDay4. How would I do that?
val data: HashMap<String, List<String>> get() {
    val listData = HashMap<String, List<String>>()

    val trainingDay1 = ArrayList<String>()
    trainingDay1.add("Player1")
    trainingDay1.add("Player2")
    trainingDay1.add("Player3")
    trainingDay1.add("Player4")
    trainingDay1.add("Player5")
    trainingDay1.add("Player6")
    trainingDay1.add("Player7")

    val trainingDay2 = ArrayList<String>()
    trainingDay2.add("Player8")
    trainingDay2.add("Player9")
    trainingDay2.add("Player10")
    trainingDay2.add("Player11")
    trainingDay2.add("Player12")

    val trainingDay3 = ArrayList<String>()
    trainingDay3.add("Player13")
    trainingDay3.add("Player14")
    trainingDay3.add("Player15")
    trainingDay3.add("Player16")
    trainingDay3.add("Player17")
    trainingDay3.add("Player18")

    val trainingDay4 = ArrayList<String>()

    listData["Training Day 1"] = trainingDay1
    listData["Training Day 2"] = trainingDay2
    listData["Training Day 3"] = trainingDay3
    listData["Training Day 4"] = trainingDay4

    return listData
}

I tried using replace and put methods, but they won't do the thing.
data.replace("Training Day 1", listOf("Training Day 4"))
data.keys
res45: kotlin.collections.MutableSet<kotlin.String> = [Training Day 1, Training Day 2, Training Day 3, "Training Day 4"]

data.put("Training Day 1", listOf("Player000"))
res40: kotlin.collections.List<kotlin.String>? = ["Player1", "Player2", "Player3", "Player4", "Player5", "Player6", "Player7"]

A:
I would like to change the key values (e.g. "Training Day 1" to
"Blablabla")

data.remove("Training Day 1")?.let {
  data.put("Blablabla", it)
}

and also the values within the ArrayList (e.g. at trainingDay2 change
"Player8" to "Player1").

data["Training Day 2"] = data.getValue("Training Day 2").map {
  if (it == "Player8") "Player1" else it
}

Furthermore I would like to add elements to trainingDay4

data["Training Day 4"] = data.getValue("Training Day 4") + "Player19"

Given that you need to mutate the list often, I would suggest to change the type of data to HashMap<String, ArrayList<String>>. Then you can perform last two operations as
//replace
data["Training Day 2"]?.let {
  it[it.indexOf("Player8")] = "Player1"
}

// add
data["Training Day 4"]?.add("Player19")


text:
Q: Xml-сериализация атрибутов вложенных узлов в свойства объекта Подскажите пожалуйста, есть ли возможность десериализовать Xml-элемент подобной структуры:
  <Service>
    <Host value="http://domain.com:80" />
    <Username value="user_name" />
    <Password value="password" />
  </Service>

в объект примерно такого класса:
[XmlRoot("Service")]
public class Service
{
    public string Host { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

То есть смысл в том, чтобы не создавать для каждого вложенного узла свой класс, наподобие этого:
public class Host
{
    [XmlAttribute("value")]
    public string Value { get; set; }
}

и затем не городить огород:
[XmlRoot("Service")]
public class Service
{
    [XmlElement("Host")]
    public Host Host { get; set; }
    .
    .
    .
}

...

var host = service.Host.Value;

Хочется верить, что атрибуты "value" всех вложенных узлов можно сразу замапить на string-свойства. Буду благодарен за любой совет.
A: Может быть, пусть Service имплементирует интерфейс IXmlSerializable и реализует ReadXml разумным образом?
Сделать это только при помощи атрибутов невозможно: свойства определяют либо такой:
<Service>
    <Host>http://domain.com:80</Host>
    <Username>user_name</Username>
    <Password>password</Password>
</Service>

либо такой
<Service Host="http://domain.com:80"
         Username="user_name"
         Password="password"/>

синтаксис.
Я тут набросал код:
[XmlRoot]
class Service : IXmlSerializable
{
    string Host;
    string Username;
    string Password;

    XmlSchema IXmlSerializable.GetSchema()
    {
        return null;
    }

    void IXmlSerializable.ReadXml(XmlReader reader)
    {
        if (reader.IsEmptyElement) // проверяем формат
            throw new Exception(); // надо какое-то другое исключение, конечно
        reader.ReadStartElement(); // читаем открывающий тег Service
        while (reader.IsStartElement()) // пока есть вложенные теги...
            processNode(reader);   // читаем их
        reader.ReadEndElement();   // читаем закрывающий тег
    }

    void processNode(XmlReader reader)
    {
        if (!reader.IsEmptyElement) // опять проверяем формат
            throw new Exception();
        if (reader.AttributeCount != 1) // то же самое
            throw new Exception();
        string name = reader.Name;
        string value = reader.GetAttribute(0);
        setField(name, value);
        reader.ReadStartElement(); // переходим к следующему
    }

    void setField(string name, string value)
    {
        switch (name) // ну или reflection, если хотите
        {
        case "Host": Host = value; break;
        case "Username": Username = value; break;
        case "Password": Password = value; break;
        }
    }

    void IXmlSerializable.WriteXml(XmlWriter writer)
    {
        serializeField(writer, "Host", Host);
        serializeField(writer, "Username", Username);
        serializeField(writer, "Password", Password);
    }

    void serializeField(XmlWriter writer, string name, string value)
    {
        writer.WriteStartElement(name);
        writer.WriteStartAttribute("Value");
        writer.WriteString(value);
        writer.WriteEndElement();
    }

}


text:
Q: sass @each loop with multiple lists developing in scss
I have the two variable lists:
$ids: 21, 33, 73;
$colors: #fff, #000, #333;

and the following @each loop.
@each $id, $color in ($ids, $colors) {
    .category--#{$id},
    .post--#{$id} {
       color: #{$color};
    }
}

I want to display the following
.category--21,
.post--21 {
    color: #fff
}

.category--33,
.post--33 {
    color: #000
}

.category--73,
.post--73 {
    color: #333
}

But I'm getting this instead
.category--21,
.post--21 {
    color: 33;
}

.category--#fff,
.post--#fff {
    color: #000;
}

Unsure of my structure. Obviously I have much longer variables lists (just added 3 to each one for demo purposes).
Any constructive feedback welcome. Thanks

A: Based on my understanding, I think @each is not the correct option for you as you don't have the key and value pair as one item.  Below is what the documentation says about @each: (emphasis is mine)

The @each directive can also use multiple variables, as in @each $var1, $var2, ... in <list>. If <list> is a list of lists, each element of the sub-lists is assigned to the respective variable.

As you can see from the above statement, in your case the $ids would be treated as one list and the $colors would be treated as another. It means that

*

*1st iteration $id is 21, $color  is 33 and 73 not assigned

*2nd iteration $id is #fff, $color is #000 and #333 is not assigned.

It might be better for you to use the @for loop like in the below snippet:
$ids: 21, 33, 73;
$colors: #fff, #000, #333;

@for $i from 1 through length($ids) {
  $id: nth($ids, $i);
  $color: nth($colors, $i);
    .category--#{$id},
    .post--#{$id} {
       color: #{$color};
    }
}

A: Hi you misuse it :D @each is iterate list by list see below
$pair: (21, #fff), (33, #000), (73, #333);

@each $id, $color in $pair {
    .category-#{$id},
    .post-#{$id} {
       color: #{$color};
       height: 20px;
    }
}

doc reference: http://sass-lang.com/documentation/file.SASS_REFERENCE.html#each-multi-assign


text:
Q: How do I prevent a cached page from being served when the user clicks the back button? I know this question has been asked multiple times before, but the solutions posted are not working for me.
I have put the following in the <head> tag, to no avail:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">

I also saw some mention about the onunload attribute and the bfcache in browsers, so I added that to the <body> tag, also to no avail.
The response headers from my server contain:
Cache-Control   max-age=0, private, must-revalidate

Would appreciate it if someone could point me in the right direction here - what am I doing wrong?

A: Answering my own question.  As it turns out, setting the following response headers (as opposed to META tags) worked for me:
Cache-Control private, no-store, max-age=0, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma no-cache
Expires Fri, 01 Jan 1990 00:00:00 GMT

If you're working in Rails like I am, you can do this easily by putting the following in an ApplicationController before_filter callback:
response.headers["Cache-Control"] = "private, no-store, max-age=0, no-cache, must-revalidate, post-check=0, pre-check=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"

A: Using the back button will use the cache as @kindall said.  It really depends on what you don't want cached.
Instead of encouraging users from using the back button can you structure the page navigation so that the user can always get to where they want without having to use a back button?
The stuff you don't want cached can you load it dynamically via ajax?

A: You can reload the logged In page with reload() after the session is being terminated in the http() fun, this updates the local cache. Since your session has ended the reload will take you to the login page. Even if you press the browser back button the login page remains, because the local cache is updated.


text:
Q: Ошибка соединения с сервером 1С Предприятия 8.2 Добрый день.
Мои действия:

*

*Поставил ОС Windows Server 2003.

*Поставил MSSQL 2005.

*Установил 1С Предприятие 8.2 (установил все что предлагало - сервер, расширения...) правда выдало ошибку, но тем не менее установило. Кажется, ошибка была связана с сервером предприятия.
3.1. В MSSQL создал пустую базу.

*Узнал имя сервера и его порт (SUPERCOMPUTER/1433)

*В програме  1СV8 Servers добавил свой сервер. Нажал кнопку "обновить" и получил ошибку:

"Ошибка соединения с сервером 1С предприятия 8.2. ..."
Сервер недоступне(не отвечает, завершается аварийно или порт занят другим приложением) line=607 file=SrcDataExchangeTcpClientImpl.cpp

Как обойти ошибку ? Спасибо.
A: А как узнали порт - 1433? Какая версия SQL Server'а?
Попробуйте телнетом постучаться на сервер на этот порт, если все правильно, телнет должен подключиться.


text:
Q: Running an executable on a Windows volume under Ubuntu I have a dual-boot Windows/Ubuntu system. I have a executable file generated from a c++ file in a folder on a Windows volume (which is accessible on Ubuntu) and would like to run it on Ubuntu. The straightforward answer would have been to move the executable file to an Ubuntu volume and run it but this is part of a huge project and I do not have the required space in Ubuntu to move the entire project.
So is it possible to run the executable from my terminal in Ubuntu?
When I try running it from the terminal using the command ./learn, I get the error ./learn: Permission Denied.
I even tried with sudo but it doesn't work.

A: Was your file compiled for Windows? An exe? In that case, copying the file won't help you, since it's using Windows system calls and not Linux's. The fact your file is not on Ubuntu partition makes no difference, even if you copy the file for your Ubuntu partition it won't work.
You may try the following:

*

*Use a virtualization layer such as Wine. Probably the easiest one for you. This will translate the Windows system calls of your software to match Linux ones. Wine should be available through Canonical repository, but I'm not sure.

*Recompile your program for Linux. If you don't have enough space to move your project from one partition to another, you probably don't have space to do a compilation. Also, if your software relies on a lot on Windows-only libraries, you'll have to replace them, which can take time. Porting a software can be complex.

*Install a Windows virtual machine. This is the roughly the same as booting into your Windows partition, so I guess you're not interested in this option. Popular virtualization methods include VirtualBox and VMWare. I personally use VirtualBox.
More on this:

*

*System call

A: The permission denied error is due to ownership and permissions for the files that can be solved by chown and chmod command give the right ownership and right permission. but I donot think that would work because the binary for windows by compiler at windows and for compiler on Linux are different so I suggest to compile on Linux again.

A: Assuming that you compile on Ubuntu and you want to use windows partition as a target of the executable file (which is not a win32 exe!). In this case the most easier solution is to mount your windows partition with umask=000,dmask=000,fmask=000. This will set 777 permission for everything. But if you'd like to be aware of security, then you should not allow this. Depending on your user/group settings you could set e.g: 022
Permissions for ntfs and vfat file systems must be set with the dmask, fmask and umask options. dmask controls permissions for directories, fmask controls permissions for files, and umask controls both. Since these options set masks, they should be the compliment of the permissions you want. For example, rwx for the owner and rw for others is 022 rather than 755.
You can give these options directly to mount command:
sudo mount /dev/your_win_partition /media/drive_c -o remount,umask=000,dmask=000,fmask=000

If you want to make it persistent, then you should add these options to /etc/fstab. More info here.


text:
Q: Struts 2: Send a JSON string with JQuery ajax submit to be mapped into a List of complextypes If a struts 2 action class have a property of
List<User> userList.
And the user class has properties like
username, password, createdDate etc.
Is it possible to make struts populate the list by passing the appropriate JSON string, while submitting a jQuery ajax request pointed at that action.
If it is possible how? Specially how will the JSON string have to look like?
Please ask any clarifications.
EDIT : I'm sorry if I wasn't clear enough. What I want to do is not get data from Action to a JSP, or submit a form to populate the data. I want to submit a AJAX request with JSON data which Struts 2 can use to automatically populate the List in the Action class.
Not submit the form with AJAX.

A: *

*you should define your action result type="json" and check you have json plugin on your classpath, make sure you have
<struts>
    <package name="your_package" extends="struts-default, json default" namespace="/">
    // your action here
    </pacakge>
    ...
</struts>

*edit your action class like this
public class myAction extends ActionSupport {
    private List<User> userlist; // getter and setter
    public String execute() {
       // your moves
       return SUCCESS;
    }
}

*then you can do some on your jsp page to show the result like:
<s:iterator list="userList">
  <s:property value="username"/>
  <s:property value="password"/>
  <s:property value="createdDate"/>
<s:iterator>

I hope this can help you..
UPDATE
if you have already a json object:
{
   "userList" : [
      {"username" : "username", "password" : "afgasdfa", "createdDate" : "date-in-format"},
      {"username" : "username", "password" : "afgasdfa", "createdDate" : "date-in-format"},
      {"username" : "username", "password" : "afgasdfa", "createdDate" : "date-in-format"},
      {"username" : "username", "password" : "afgasdfa", "createdDate" : "date-in-format"}
   ]
}

this should be the format.
then you should get this object from your action class with List<User> userList
just try it and feedback.
UPDATE 2
maybe you should get your json object using String, then convert it to Java Object using:
String stringObject; // which get your string from http
List<User> userList;

userList = (List<User>)JSON.deserialize(stringObject,List<User>.class);

Please feedback again.


text:
Q: Dynamically insert data into an APEX page item when a page item is entered a value I have a form in APEX that is used to add data into a table. Most of the items in the form are free form texts but there few items that are needed to auto filled when you enter a value in on of the page item.
For example.
There is form with Page Items. ID, Name, TitleLevel, Title_prefix, Salalry,
There is a table XYZ with Title_prefix and salary info which
ID    Title_prefix   Salaray
1   Junior         80000
2   Mid-Level      95000
3   Senior         115000
So you enter ID= 1, Name = ABCD, Titlelevel = 6 is entered and Title_prefix and salary should be populated based on the value that is entered in titlelevel. In this case it will be
Title_Prefix = (SELECT Title_Prefix FROM XYZ WHERE ID = (Case WHEN :P1_TitleLevel > 5 THEN 3 CASE WHEN :P1_TitleLevel = 5 THEN 2 ELSE 1 END))
Same thing for Salary as well.
Immediately after entering Titlelevel page item to 6 the Title_prefix and Salary should get refreshed and populate this items. Then the user will submit the form so that the information can be entered into the table.

A: Add a Dynamic Action on titlelevel (Key Release if Text Field, onChange if dropdown etc.)
Add a PL/SQL Action to the dynamic_action, using Items to Submit to pass fields in and Items to Return for the fields you modify.
Dynamic Action:

OR

Action: