text:
Q: Spring Data JPA: org.springframework.beans.factory.UnsatisfiedDependencyException: I am trying to add crossOrigin variable in Application.property file.  and accessing that variable through controller using @value its working for following two end point's but when I am adding @value to third end point I am getting following error message
AccountController.java
@RestController
@RequestMapping("/api.spacestudy.com/SpaceStudy/Admin/Account")
public class AccountController {

    @Autowired
    AccountService accService;

    @Value("${crossOrigin}")
    @GetMapping("/loadAcctLocationList")
    public ResponseEntity<List<Account>> findLocation() {
        return  ResponseEntity.ok(accService.findLocation());
    }

}

TestAccountController
@RunWith(SpringRunner.class)
public class TestAccountController {

    private MockMvc mockMvc;

    @Mock
    private AccountService accountService;

    @InjectMocks
    private AccountController accountController;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
    }

    @Test
    public void findLocationTest() throws Exception {

        Account account = new Account();
        account.setsLocation("Test1");

        List<Account> accountObj = new ArrayList<Account>();
        accountObj.add(account);

        Mockito.when(accountService.findLocation()).thenReturn(accountObj);

        mockMvc.perform(get("/spacestudy/$ InstituteIdentifier/admin/account/loadAcctLocationList"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$[0].sLocation", is("Test1")))
                .andExpect(jsonPath("$.*",Matchers.hasSize(1)));

        for(Account result: accountObj) {

            assertEquals("Test1", result.sLocation);

        }

        }

application.properties
crossOrigin =@CrossOrigin(origins ="http://localhost:4200")
server.port=8086
spring.datasource.url=jdbc:postgresql://localhost/SpaceStudyDB
spring.datasource.username=postgres
spring.datasource.password=postgres

Console
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-05-15 01:59:17.915 ERROR 5240 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountController': Unsatisfied dependency expressed through method 'btnSaveClick' parameter 0; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'com.spacestudy.model.AccountMaintenanceSave'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.spacestudy.model.AccountMaintenanceSave': no matching editors or conversion strategy found
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:667) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.10.RELEASE.jar:1.5.10.RELEASE]
    at com.spacestudy.SpaceStudyAdminAccountMaintenance.main(SpaceStudyAdminAccountMaintenance.java:10) [classes/:na]
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'com.spacestudy.model.AccountMaintenanceSave'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.spacestudy.model.AccountMaintenanceSave': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:74) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1093) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:659) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    ... 19 common frames omitted
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.spacestudy.model.AccountMaintenanceSave': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:307) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:109) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:64) ~[spring-beans-4.3.14.RELEASE.jar:4.3.14.RELEASE]
    ... 23 common frames omitted

Can any one tell me what I am doing wrong in above code ? or tell me any another way to declare variable in application.property file

A: It looks like what Spring is trying to do here is inject the value of ${crossOrigin} into your method.

*

*In findLocation, it's not breaking because there are no method arguments in which to inject the value

*In the btnSearchClick, there's more than one argument and it's not attempting to inject the value

*There's one argument, and it's trying to inject the value of ${crossOrigin} into AccountMaintenanceSave saveObj
You should just inject ${crossOrigin} into a @CrossOrigin at the top of your class? Like so:
@RestController
@CrossOrigin(origins = "${crossOrigin}")
@RequestMapping("/api.spacestudy.com/SpaceStudy/Admin/Account")
public class AccountController {

    @Autowired
    AccountService accService;

    ...
}

And access the variable that way. You'll need to remove the @Value annotations from your controller methods.
You'll also need to just specify the origin name in your application.properties:
crossOrigin=http://localhost:4200


text:
Q: Will the QR codes I create using the qr4office add-in ever expire? @user:678505
I have recently discovered many free QR creators expire the generated QR codes after a period of time.  If I install the qr4office add-in to Microsoft, will the QR codes I generate eventually expire?
I want the QR code to be static.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convergence of a sequence of unit vectors in a Hilbert space Let $E$ be a vector space (over $\mathbb{R}$) with a positive definite hermitian form and let $\{x_{n}\}$ ($x_{n} \not= 0$) be a sequence converging to $x$ in the $L^{2}$ norm $\lvert\cdot\rvert=\sqrt{\langle\cdot,\cdot\rangle}$.  Why does $\left\{x_{n}/\lvert x_{n}\rvert\right\}$ converge to $x/\lvert x \rvert$?

A: What you are really asking is why $|x_n| \rightarrow |x|$ the rest is just the limit theorem of elementary analysis.
Now we can use the inequality, which is an application of the triangle inequality,
$$||x_n|-|x||\leq |x_n-x|$$ to prove the limit.


text:
Q: On a comment by the mathematician George F. Simmons on stages of proof understanding. I came across the quote below on a website. It concerns different stages of proof understanding, and is apparently by George F. Simmons:

It is a basic principle in the study of mathematics, and one too seldom emphasized, that a proof is not really understood until the stage is reached at which one can grasp it as a whole and see it as a single idea. In achieving this end, much more is necessary than merely following the individual steps in the reasoning. This is only the beginning. A proof should be chewed, swallowed, and digested, and this process of assimilation should not be abandoned until it yields a full comprehension of the overall pattern of thought.

Restricting the scope of my question to concern only proofs in standard textbooks at undergraduate level (i.e. not involved research level proofs), I would appreciate some insight from members of the community here on the following open-ended questions:
1. In your experience of mathematics, what is your conception of that which Simmons refers to when he says that a "proof is not really understood until the stage is reached at which one can grasp it as a whole and see it as a single idea."?
2. If question 1 is too "slippery" to answer, then can you say, without answering 1, that you can see proofs as "a single idea"?
3. If so, then can you name a proof, roughly at an introductory 1st year undergraduate level, which you feel appropriately exemplifies the content of Simmons' quotation?
Context and information about my background.
I am relatively inexperienced at writing formal mathematical proofs by myself, by which I mean proofs which require a degree of insight, originality, or "tricks". More concretely, my exposure to proof-writing ranges from high-school level proofs which require minimal insight, and I have just started practising this more in self-study of real analysis using Understanding Analysis by Stephen Abbott (2015). Concerning reading proofs, I have some experience with reading proofs in theoretical statistics and statistical learning theory.
Rationale.
The reason why I have asked the above questions is because I found that his specific comment on being able to grasp a proof "as a whole" and seeing it as a "single idea" is a framing which is new and alien to me; but at the same time, innately appealing to the extent that I would like to know what more experienced mathematicians think about this.
To elaborate a little more on this, I am comfortable with conceiving of the following with reading proofs and writing proofs:

*

*More granular: Seeing a proof as a series of individual deductive steps (what steps are needed).

*Less granluar: Understanding the motivations of how a proof is constructed strategically (what is the broad vision/primary insight/novel idea/trick that motivates the deductive steps). I associate this stage of understanding with being fluent enough with the broad ideas so as to be able to reconstruct, but not recollect verbatim from memory, the proof from first principles.

The Simmon's quotation is also concerning for me. Because it has invited me to re-evaluate whether there exist deficiencies in what I aspire to when I attempt to understand a proof; in that there may be a more abstract, less granular level of understanding that I have previously not conceived of, and which has eluded me:

*

*Least granular: Seeing the proof as a whole, or as a single idea (???)

On the other hand, what tempers my concern is that this may just be Simmons' way of expressing what people might mean when they say "solid understanding". And that it is an intrinsic way of describing solid understanding, rather than a pragmatic one, e.g. is your understanding of the proof at a level where you can fluently communicate its contents to a peer? If that is the case then perhaps there is less of a cause concern. The last possibility I have in mind is that perhaps he might just be describing a stage of understanding of a proof in the vein of Gestalt psychology, where one can grasp a series of elements as a whole (the pictures).
However, I am unsure about this, which is why the receipt of responses from one's own experiences on this, or even reading suggestions in this area, would be warmly welcome. If this question is not closed for being too open-ended, perhaps it could be added to community wiki (I don't know how to do this), because there are no "correct" answers that can be accepted for this.

A: previews  Conics  and Whitney Biography
turns out I have this as a jpeg. About halfway down he talks about Whitney and Bezout's theorem. In the last paragraph on this page, he says

I'd known about that result for at least two years, and I realized
that in 15 or 20 minutes, he'd gained a deeper appreciation of it than
I'd ever had.

half the page, better visibility, except that the search words used are highlighted:


text:
Q: How to customise wp-login.php only for users who are setting a password for the first time? As administrator, if  I make a new user, I can choose to email my new users a link which they click to go to wp-login.php where they are invited to set their password for the first time. (Wordpress used to email out a password, but I can see why they changed that!)
Users arrive at wp-login which records the username in a hidden field, and shows a suggested password which they can customise.
Some of my more easily boggled users are confused by this.  They find the generated password incomprehensible, and do not understand that they can click on the suggested password in the box and change it to something they can remember.  I would like to add some help text and maybe automatically select the suggested password too at this point.
I am not sure which hooks will allow me to do stuff that only appears to users setting their password, and not to anyone else who is logging in.
How can I do that?

A: You can add an extra help message box, on the reset password screen:

with the following:
 /**
  * Display an extra help message box on the 'reset password' screen
  *
  * @link http://wordpress.stackexchange.com/a/204429/26350
  */
 add_action( 'validate_password_reset', function( $errors )
 {
    add_action( 'login_message', function( $message )
    {
        // Modify this help message box to your needs:
        $mybox = sprintf(
            '

%s
',
            __( 'Some help text here!' )
        );

        return $message . $mybox;
    } );
 } );

Here we add the extra message box by using the login_message filter. It should only show up on the reset password screen, because we hook it into the  validate_password_reset action.

A: I ended up using this.
It's definitely a hack... if someone else knows how better to modify what's happening in wp-admin/js/user-profile.js without hacking core, please let me know. I don't want to deregister the entire script because I like all of the password strength checking, etc that's in there.
// add some js to the login page
function squarecandy_login_stylesheet() {
    wp_enqueue_script( 'custom-login-js', get_stylesheet_directory_uri() . '/js/login.js' );
}
add_action( 'login_enqueue_scripts', 'squarecandy_login_stylesheet' );

login.js
jQuery(document).ready(function($){
  // wait half a second so WP can fill the suggestion first
  setTimeout( function(){
    // Switch to the non-visible entry mode
    $('.wp-hide-pw').click();
    // clear the password fields, put the cursor in the field
    $('#pass1, #pass1-text').val('').focus();
  }, 500 );
});


text:
Q: "Extended" depth-first search in C++ I know how to implement depth-first search algorithm in C++, but I need an "extended version". So, I have a map
map<int, map<int,int> > tree;

that for any vertex it returns a map with adjacent vertices as keys and (important for my program) edge indexes as values. The root of the tree is first (1) vertex. So, here is my code:
stack<int> s;
for(const auto &pair : tree[1]) s.push(pair.first);
while(!s.empty()) {
    if(!visited[s.top()]) {    //it's just bool array
        roads[s.top()] = {0}; // ???
        for(const auto &pair : tree[s.top()]) s.push(pair.first);
    }
    s.pop();
}

What I need to do is create a vector of vectors in which, for every vertex, I'll have a complete path (expressed as edge indexes).
For example for graph like that:
       1
      /  \
(i=2)/    \(i=1)
    /      \
   2       3
           /\
          /  \
    (i=3)/    \(i=4)
        /      \
       4        5

I would like to have something like this:
vector< vector<int> > roads = {{},{},{2},{1},{1,3},{1,4};

because roads[0] does not exist, roads[1] too, and for every other we have path expressed as edge indexes.
EDIT
In other words what I want to do:
For every vertex in a given tree I want to know a path from root to this vertex. Every edge in this tree has its own number, so path would be expressed as a vector or set (for simplicity's sake, I don't care at all about the order of edges).

A: "graph with no cycles" is also known as a tree.
You want to have a list with all the sequences of edge labels that represent a path from root to some vertex?
Pseudocode for a traversal (I guess this would qualify as a preorder traversal):
void collect(node, //current node
    labels, //labels of edges leading to node
    &paths //all the paths collected so far, writeable, contains results
) {
    paths.add(labels);
    foreach ((neighbor_node, edge_name) in (unvisited neighbors of node)) {
        labels.add(edge_name);
        collect(neighbor_node, labels, paths);
        labels.remove(edge_name);
    }
}

start with collect(root, empty_list, empty_list);


text:
Q: How To Send a Message From Popup.js to Content Script in Chrome Extension on Active Tab? When I click on the toolbar icon from my chrome extension, it brings up the default popup.html along with popup.js.  From that popup.js, I want to send a message to the current active tab. I can't figure out how to get the active tab.
My code in the popup.js looks like this:
window.onload = function() {
  console.log(`popup.js:window.onload`);
  const timeNow = document.getElementById("timeNowId");
  timeNow.innerText = new Date().toLocaleTimeString();
  var resultsButton = document.getElementById("buttonId");
  resultsButton.onclick = () => {
    chrome.runtime.sendMessage(
      "FromPopupToBackgroundToContent:" + timeNow.innerText,
      function(response) {
        response === undefined
          ? alert("popup.js:return from sendMessage:undefined")
          : alert("popup.js:return from sendMessage:", response);
      }
    );
  };
};

The full, non-working example is in this github repo at this branch linked to.
https://github.com/pkellner/chrome-extension-message-popup-to-content/tree/feature-popup-to-content-directly-getcurrent

A: Example:
popup.js
 function popup() {
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
   });
}

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("button1").addEventListener("click", popup);
});

content.js
chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        if( request.message === "start" ) {
         start();
             }
      }
    );

    function start(){
        alert("started");
    }

popup.html
<!DOCTYPE html>
<html>
    <head></head>
    <script src="popup.js"></script>
    <body>
        <input id="button1" type=button value=clickme>
    </body>
</html>


text:
Q: How do I deploy a PHP website without use of web IDEs? I would like to deploy a PHP website. The problem is, I use Netlify, and it only supports static sites.
I plan to make my website in my own PC, and not in any web IDEs (e.g. Replit, Heroku etc)
Is there a way to deploy a website without needing any fees (subscriptions, plans etc)?


text:
Q: Why I cannot import transformations after installation in python using pip? I am running python 3.8 and using pip to install many packages and inporting it. But when I try to install transforms and import it I get the following messages. Any help would be appreciated.
C:\Users\r.acharyya.CI\AppData\Local\Programs\Python\Python38>pip install transforms
Requirement already satisfied: transforms in c:\users\r.acharyya.ci\appdata\local\programs\python\python38\lib\site-packages (0.1)
C:\Users\buy.rtharyya.CI\AppData\Local\Programs\Python\Python38>pip install transforms
Requirement already satisfied: transforms in c:\users\r.acharyya.ci\appdata\local\programs\python\python38\lib\site-packages (0.1)
C:\Users\buy.rtharyya.CI\AppData\Local\Programs\Python\Python38>python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

import transforms
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\r.acharyya.CI\AppData\Local\Programs\Python\Python38\lib\site-packages\transforms_init_.py", line 1, in
from .safe_html import safe_html, bodyfinder
File "C:\Users\r.acharyya.CI\AppData\Local\Programs\Python\Python38\lib\site-packages\transforms\safe_html.py", line 1, in
from sgmllib import SGMLParser, SGMLParseError
ModuleNotFoundError: No module named 'sgmllib'

A: transforms, the only version is 0.1  released Aug 21, 2014. The code is obviously Python2-only. sgmllib was a module in the standard library https://docs.python.org/2.7/library/sgmllib.html, deprecated since version 2.6.

A: I used the command pip install sgmllib3k and it solve my issues.


text:
Q: Error Code: 1442. Can't update table 'ArgentineWine' in stored function/trigger because it is already used by statement I have read the 4 cases in this forum reg.

Error Code: 1442. Can't update table 'tablename' in stored  function/trigger because it is already used by statement

Those cases are way more complex than my situation. I created an ArgentineWines table with 5 columns, loaded 10 rows, and created a trigger:
CREATE TRIGGER Trigger_Before_An_ArgentineWines_update
AFTER UPDATE ON ArgentineWines
FOR EACH ROW
    INSERT INTO ArgentineWines
    SET action = 'update',
        RankingId = OLD.RankingId,
        WineName = OLD.WineName,
        Description = OLD.Description,
        RecordDate = NOW();

The problem arises when I try to test out the trigger by making a change to the table. I attempted to update the table in two different ways
First attempt:
USE Sakila;

UPDATE ArgentineWines
SET WineName = REPLACE(WineName,'GRAFFIGNA RESERVE','GRAFFIGNA RESERVE Grandiose')
WHERE RankingId = 6;

Second attempt:
USE Sakila;

UPDATE ArgentineWines
SET WineName = 'GRAFFIGNA RESERVE Grandiose'
WHERE RankingId = 6;

No matter what I try, I get this error:

Error Code: 1442. Can't update table 'argentinewines' in stored function/trigger because it is already used by statement which invoked this stored function/trigger

I have used BEFORE I have used AFTER, no matter what the error keeps popping up.
Questions: which other statement is invoking my stored procedure? What is already using what? The error description is not that clear.
Please, any thoughts or a solution to this mystery will be great. DH


text:
Q: Breadcrumb in rails What's the best way to include breadcrumbs in Rails?

A: Gretel is a very good gem for making breadcrumb in rails. It is very easy to use, you can find the tutorial on the same page.
Hope this helps.


text:
Q: pycuda: Memory allocation in gpu for a list I want to run a simple pycuda program to update a list on the gpu. Following is my list.
dm_count = [[0], [1, 2], [3, 4, 5], [6, 7, 8, 9]].
I have this list as the input and expected to update the input list in parallel.
 It throws an exception when I tries to allocate memory in the gpu using mem_alloc().
It give the Attribute Error saying the "'list' object has no attribute 'nbytes'".  When I search for answers some says to convert the list in the form of an array and nbytes otherwise cannot be applied. It seems to support for the arrays in format [[1,1],[1,1],[2,4]] only. But I doesn't want to change the list. What is the way to allocate memory in gpu while keeping the list in its original format?
I am not aware whether the memcpy_dtoh() also work correctly. How can I correct this program to yield the expected outcome?
import pycuda.driver as cuda
import pycuda.autoinit
from pycuda.compiler import SourceModule
import numpy

dm_count = [[0], [1, 2], [3, 4, 5], [6, 7, 8, 9]]
length = len(dm_count)

mod = SourceModule("""
__global__ void UpdateMatrix(int **dm_count, int length)
    {
       int row = threadIdx.x + blockIdx.x*blockDim.x;
       int col = threadIdx.y + blockIdx.y*blockDim.y;
       if( (row < length) && (col< row)){
            dm_count[row][col] = 0 ;
       }
    }
        """)

dm_gpu = cuda.mem_alloc(dm_count.nbytes)
cuda.memcpy_htod(dm_gpu, dm_count)
func = mod.get_function("updateMatrix")
func(dm_gpu, block=(length, length, 1))
result = numpy.empty_like(dm_count)
cuda.memcpy_dtoh(result, dm_gpu)
print(result)

Expected Result: result = [[0], [0, 2], [0, 0, 5], [0, 0, 0, 9]]
Error Message: Traceback (most recent call last):   File
  "test_pycuda.py", line 55, in
      dm_gpu = cuda.mem_alloc(dm_count.nbytes)
  AttributeError: 'list' object has no attribute 'nbytes'

A:
I want to run a simple pycuda program to update a list on the gpu

It is not possible to manipulate a python list in PyCUDA. In general, PyCUDA can only deal with numpy arrays with a limited set of dtypes, and similar types which support the Python buffer protocol.
As a result, you could potentially re-write your code to use a numpy array of a suitable dtype as input to the kernel, although you would have to devise a representation of the jagged array which would be compatible with a contiguous numpy array. You would then need to write the CUDA kernel to use the format you devise (Note your current kernel is broken in a number of ways which mean that is would not work even if the list was accepted as an inout by PyCUDA).


text:
Q: Chrome debugger stops at a function even without a DOM break point Hi I have a angular js application. And  when I run my application and hit F12 and open the debugger, for each and every page it continuously calling following function and stops there just like it has a break point.
Here is the stopping point
TagCanvas.NextFrameRAF = function() {
  requestAnimationFrame(DrawCanvasRAF);
};

But this function doesn't have any break points.

A: It sounds like you have a Request Animation Frame breakpoint set:

You can find that in dev tools on the Sources tab on the right-hand side under Event Listener Breakpoints > Animation.


text:
Q: How does ternary operator use 3 operands? Ternary operators look like this
m = (a > b) ? a : b;

My teacher says that ternary operators use 3 operands
which here are m, a and b...
even if m is actually the variable where we store the data...
But when we are writing
m = a + b;

Here as well we are writing m as the storing variable so why isn't this a ternary statement?

A: m is not an operand of either of the two operators (the ternary conditional operator and the + operator) whose number of operands you were asking about. It's just the variable two which you assign the result of these two operators.
The expression in your example is just (a > b) ? a : b, and the operands are (a > b), a and b.
In a + b, the operands are a and b, so there are just two operands.
Note that my answer says nothing about the assignment operator =, which the question did not ask about.

A: If you look at the abstract syntax tree of
m = (a > b) ? a : b;

It would be something like:
ExpressionStatement       // m = (a > b) ? a : b;
  Assignment              // m = (a > b) ? a : b
    Identifier            // m
    ConditionalExpression //     (a > b) ? a : b
      Parenthesized       //     (a > b)
        BinaryOperator >  //      a > b
          Identifier      //      a
          Identifier      //          b
      Identifier          //               a
      Identifier          //                   b

The "ternary" refers to the fact that ConditionalExpression has 3 direct children in the tree (the parenthesized tree and the two identifiers).
The assignment is a binary tree, because it has two direct children (the identifier and the conditional expression).
The tree for m = a + b; would be:
ExpressionStatement  // m = a + b;
  Assignment         // m = a + b
    Identifier       // m
    BinaryOperator + //     a + b
      Identifier     //     a
      Identifier     //         b

Again (and always), the assignment is a binary operator, with two direct children: the identifier and the addition. The addition is a separate binary operator, with two direct children.

A: The word operands does not refer to the variable used, but to the different part of the ternary operator. They are

*

*result1 will be returned if the confition is evaluated to True

*condition1 the condition to determine the result

*result2 will be returned if the confition is evaluated to False
result1 if condition1 else result2

Then you use this in a print, or save it, but that is not a part of the ternary operator itself
print('Win' if value==15 else 'Loose') # print it
res = 55 if value%5==6 else 33         # save it

A: The arity of an operator is determined by the number of operands / arguments. There are unary operators which take one operand like i++ (post-increment), binary operators like a + b which take two arguments, and there is the ternary operator a ? b : c which takes three operands.
Operands can use the same variable or expression. For example, in the expression a + a, the + operator is still a binary operator that takes two arguments - it just takes the same argument twice.
m = <expression> is an assignment. The assignment operator is also a binary operator that takes two arguments. On the left-hand side you have the target of the assignment, which is the variable m in your case, and on the right hand side you have the (complex) expression that gives the value.
This leaves you with (a > b) ? a : b. There are still three operands - the conditional is (a > b), the a is the true expression, and the b is the false expression.
This operator is defined in §15.25 of the JLS:

The conditional operator has three operand expressions. ? appears between the first and second expressions, and : appears between the second and third expressions.
  (Highlight mine).


text:
Q: Is there a language that is designed with one-way translation into more than one other popular language? CoffeeScript gets converted to JavaScript, Groovy to Java.
Is there a language that was designed to allow its functions to be converted into multiple languages?
One could write string manipulation or HTML snippet generation that could be used as a library, but if a similar requirement is found in another language, the functions of that library would need to be translated.
Is there such a language that includes two or more translation targets already?
I am mostly interested in Java, JavaScript, Perl.
I would be interested in C/C++, but only if there were safeguards to prevent buffer overflow vulnerabilities from being created.

A: What about Haxe? C++, Flash, JavaScript, and more.

A: UML - Unified Modeling Language, has several tools that can translate into C++, Java, and others.  That's not really a "language" like C or Java, however.  It's all diagrams.
I don't know much about other languages, but the Java bytecode, when the compiled with the right flags in javac, contains debugging information like line numbers, variable names, and (I think) comments.  Unobfuscated Java bytecode can be decompiled into pretty readable source code.

A: I think what you're looking for is LLVM.  Also, this similar question may be relevant.


text:
Q: Starting with Calico network policy in Kubernetes I have a application running with kubernetes orchestrator. I want to implement calico network policy on the basis of CIDR so that I can control the pod's traffic (incoming and outgoing). I am looking for prerequisite installation (any plugin) and what changes (calico yaml file or manifest file) are required to achieve this.
Some explanation about steps that need to be implemented will be appreciated.

A: well, prerequisites depend on whether you want to use plain Kubernetes NetworkPolicies or Calico NetworkPolicies.
You will need to have a CNI Plugin deployed which implements the NetworkPolicy Specification either way. Calicao supports plain NetPols as well as its own NetPol implementation.

*

*check your deployed CNI plugin

*check if your deployed CNI plugin implements network policies

*create NetworkPolicy kubernetes ressources and deploy them

A: By default as explained here K3s is running with flannel CNI, using VXLAN as default backend.
To change the CNI you need to run K3s with --flannel-backend=none. For more information please visit custom-CNI section of the docs.
Please note that besides calico you can run canal CNI which in fact is flannel with calico network policies available.


text:
Q: How to remove Windows border from WPF UserControl? To preface this question, I am working on coding the back end of an application whose UI was put together by someone else (I believe using Blend).  The application consists of a series of "Screens," whose root element in XAML is "UserControl".  There is no use of the "Window" tag anywhere in the source.
What I want to do is remove the Windows border that is added to the outside edge of the application when I run the program.  The border currently consists of forward/backward buttons like a web browser, and an X button to close.
All I can find from searches are instructions to add
WindowStyle="None"

to the
<Window>

element.  But of course, I don't have one of those, and WindowStyle is not a property of UserControl.  Anyone know how to accomplish this with UserControl root elements?
Edit:  The StartupUri for the application is
this.StartupUri = new Uri(@"pack://application:,,,/WpfPrototype1.Screens;Component/Screen_1.xaml");

the file it points to does not have a Window tag.

A: Based on the comments above it seems your MainWindow is created dynamically somewhere, however you can use the Application class to get the applications MainWindow.
var mainWindow = Application.Current.MainWindow;

And you can then set your border style from there
Example:
private void RemoveBorder()
{
    var mainWindow = Application.Current.MainWindow;
    if (mainWindow != null)//should never be
    {
        mainWindow.WindowStyle = System.Windows.WindowStyle.None; // removes top bar (icon, title, close buttons etc)
        mainWindow.AllowsTransparency = true; //removes the border around the outside
    }
}


text:
Q: Refresh the data on the webpart without entire Page refresh The data from the list is displayed on the page using content editor webpart as a scrolling text. The requirement is whenever the list is updated with new items, the data displayed on the page using CEWP should be updated automatically without a entire page refresh.
The script to display the scrolling text is in a text file uploaded into the library and linked to the webpart.
I tried using SetTimeout and SetInterval, but nothing is working.
Please suggest with available options
Thank You

A: SharePoint 2010 introduces a new Ajax option has been added to  many webparts to enable auto refresh of webpart without refreshing the entire web page. This feature is available out of the box in SharePoint 2010 and no additional development is required.
How to use Auto Refresh Web parts in SharePoint 2010:
In SharePoint 2010, web parts have a new section in their tool panes - Ajax Options:

The key option is the Enable Asynchronous Automatic Refresh. Checking this will enable the Auto Refresh feature on the webpart. The Auto Refreshing Interval is the time interval in which webpart will get refreshed automatically.
Thanks,

A: Set "Show Manual Refresh Button" setting from previous post and call from Your js script:
jQuery('#MSOZoneCell_WebPartWPQ3').find('#ManualRefresh').click();

Took this solution from another thread.

A: It works for me:
function RefreshWebpart(webpartId)
{
    var webpart = document.querySelector("div[webpartid='" + webpartId + "']");
    var listviewtable = webpart.querySelector("table.ms-listviewtable");
    __doPostBack(listviewtable.id, "cancel");
}


text:
Q: getting an error " jQuery is not defined" after using variable parts in a URL -flask framework This is my WEB architecture
Web
|-->static
   |-->css
   |-->js
   |-->img
|-->templates
   |-->test1
   |-->test2
|-->modfunctions
   |-->test1
         |-->main.py
   |-->test2
         |-->main.py

If I use any unique URLs like @app.route('/test2', methods=['GET','POST']), My JQuery part is working fine, but when I tried to add variable parts to a URL like @app.route('module/<data>', methods=['GET','POST']), its throwing error saying 'jQuery is not defined' .
Here I have attached my code
from flask import Flask
from flask import render_template, request, redirect

app = Flask(__name__, template_folder='/home/web/templates', static_folder='/home/web/static')

@app.route('module/<data>', methods=['GET','POST'])
def mod_data(data):
    if request.method == 'GET':
        return render_template('test1/page1.html')

    if request.method == 'POST':
        return render_template('test1/page2.html')

if __name__ == "__main__":
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

Please help me in finding my mistake bysharing some solution

Final HTML page
{% extends "base.html" %}

{% block content %}

{% endblock content%}

{% block js %}

    {% block js %}{% endblock js %}

A: I think on your block JS, you might be overwriting your jquery grab. Try doing a {{ super() }} at the top of your {% block js %}. Although, this is really only a guess as I have made this mistake a few times
Alternatively, from what your comments suggest, jquery was loaded AFTER your javascript ran. On the template it inherits from, does the block where jquery is defined come before, or after, the {% block js %}?

A: The problem is in the way you reference the jQuery library:
window.jQuery || document.write("


text:
Q: Meshlabserver : Cannot connect to X server error I have meshlab installed in my machine running Ubuntu 14.04 OS. I can access it from command line using meshlabserver command. But problem arises whenever I try to call it from a php script using the command
<?php
system('meshlabserver 2>&1');
?>

It shows the error meshlabserver: cannot connect to X server. After going through a few websites I did the following things:
I moved the meshlabserver executable from /usr/bin to /usr/local/bin and gave it executable permissions using
sudo chmod a+x meshlabserver

But when I ran the whoami command from my php script (calling the meshlabserver), it showed www-data. So I gave executable permissions for all users to the meshlabserver using
sudo chmod 777 /usr/local/bin/meshlabserver

But still it is showing the same meshlabserver: cannot connect to X server error. meshlabserver comamnd is working fine when ran from the command line.
I really need to call meshlab from the php script for my website. Thus any help would be highly appreciated. Thanks in advance.

A: It seems the php script can't access your display variable. If you logged in via ssh remember to tunnel your X-server via 'ssh -X ...' Your second option is to create a virtual frame buffer using Xvfb and redirect the display variable to it:
export DISPLAY=:100.0
Xvfb :100 &

Note the ampersand for the second command as Xvfb needs to be running in the background.

A: a combo of prior answers works for me:
ssh -X, as well as export DISPLAY=:0.0 (on remote)


text:
Q: Fading in container elements in Knockout.js after image has loaded I have an images and some text that is being generated by Knockout.js. The text shows up immediately while the images takes longer to load.
I want to have a class on the container that houses each image/text pair and when the image finishes loading then toggle that class and have the image/text pair fade in at the same time.
I know there is an afterRender callback, I'm having difficulty writing the function that gets called to target the element and manipulate the class.
http://jsfiddle.net/ClydeGrey/mfjv5j2c/4/

function SomeModel() {
  this.Firstname = ko.observable();
  this.Lastname = ko.observable();
  this.fadeIn = ko.observable();
}

function SomeViewModel() {
  var self = this;

  this.ArrayOfModels = ko.mapping.fromJS([]);
  this.dataArray = new Array;

  this.GetModelsByAjax = function() {
    $.ajax({
      type: 'POST',
      url: '/echo/json/',
      data: {
        json: JSON.stringify([{
            loaded: false,
            img: "https://source.unsplash.com/random",
            Firstname: "Bob",
            Lastname: "Smith"
          },
          {
            loaded: false,
            img: "https://source.unsplash.com/user/erondu",
            Firstname: "Ted",
            Lastname: "Smith"
          },

          {
            loaded: false,
            img: "https://source.unsplash.com/user/erondu/1600x900",
            Firstname: "Jim",
            Lastname: "Gump"
          }
        ]),
        delay: 0
      },
      context: this,
      success: function(data) {
        for (var x = 0; x < data.length; x++) {
          self.dataArray.push(data[x]);
        }
        /* self.dataArray.push(data); */
        console.log(self.dataArray);
        console.log(typeof(self.dataArray));
        console.log(data);
        console.log(typeof(data));
        self.SuccessfullyRetrievedModelsFromAjax(self.dataArray);
      },
      dataType: 'json'
    });
  };

  this.SuccessfullyRetrievedModelsFromAjax = function(models) {
    ko.mapping.fromJS(models, self.ArrayOfModels);
  };
}

ko.applyBindings(new SomeViewModel());

<button data-bind="click: GetModelsByAjax">Go</button>

A: You already have a loaded property that is initialized as false and observable. We'll use this property in two ways:

*

*In a css binding, to add an is-visible class to the img + label wrapper that we can style

*In an event binding, to set the value when the  tag fires a load event.

Your new template, without any other changes:

The css for the fade, that you can change to your liking:
.Img {
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

.Img.is-visible { opacity: 1; }

In an updated version of your fiddle: http://jsfiddle.net/L7cn6y5r/


text:
Q: Same Name to Parent and Child Tag in JSX gives undefined class Button extends Component
{
    changeHandler = (event)=>{
        console.log(event.target.name);
    }
    render() {
        return (

                <button type="button" name="text" className="btn btn-primary" onClick={(event)=>this.changeHandler(event)}>
                    this.changeHandler(event)}>
                </button>

        );
    }
}

I have given same name to Button(Bootstrap) and icon (using font Awesome) and when I click on icon the console gives the value as undefined, but gives the value of name in case of button click.

A: The name property only exists for certain DOM elements. <button> has a name property but  does not.
https://developer.mozilla.org/en-US/docs/Web/API/Element/name
If you want to get the name attribute for , you'll have to use getAttribute("name").
In your case it would be event.target.getAttribute("name").


text:
Q: Image processing in android I am trying to build an image processing application in android.
I want the application to function just like the barcode application where the scanning happens automatically; so the poster on the wall or the image will be scanned and a particular intent will be fired to do some task.
I dont know which approach to follow?? some guide me to use ndk while some say there are libraries out there.
Please help me
Thanks

A: You may take a try with the Android port of OpenCV.
Since the brand new version 2.3.1 it is relatively easy to compile and deploy native (C++) and Java-based image processing programs to an Android device.
You need an Eclipse IDE, the JDK 6, Android SDK, and ADT plugin for Eclipse and you should follow the long tutorial step by step. After that the examples should work and you can start to extend them to your needs.


text:
Q: Serialized object to mysql database in R If I have serialized data like:
> a <- 1:5
> a
[1] 1 2 3 4 5
> b <- serialize(a,NULL)
> b
[1] 58 0a 00 00 00 02 00 02 0f 02 00 02 03 00 00 00 00 0d 00 00 00 05 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05
> b[1]
[1] 58
> b[8]
[1] 02

How can I put that serialized data into a MySQL table? I have other info there also. I read that it can be done as blob, but I don't know how it works. I am using RMySQL. I have tried:
dbGetQuery(con, "INSERT INTO table(",b," info, moreInfo, otherStuff, more, date )")

but it won't work.
If I use
query <- paste ("INSERT INTO table(",b," info, moreInfo, otherStuff, more, date )")
dbGetQuery(con,query)

it still won't work.

A: try this:
library(RODBC)
dt=data.table(a=sample(10),b=sample(10)*10)
sqlSave(con, dt, tablename='sampletablename') # overwrites existing sampletablename table
sqlSave(con, dt, tablename='sampletablename', append=TRUE) # append instead of overwrite


text:
Q: Is it possible to download and install multiple versions of Safari on macOS? Is it possible to download and install multiple versions of Safari on macOS?
I need to test something out on my MacBook with the latest version of Safari (13), but I don't want to update my current Safari browser to the latest version. I want to be able to keep my current older version of Safari UNTOUCHED and the newest version of Safari both installed and usable on my Mac computer. Is this possible?

A: Updates to Safari tend to include updates to the WebKit system framework on which Safari relies. (The WebKit framework is separate from the app, and is then available to other apps.)
Executing an app that was built for a different framework from the last one you installed is likely to cause problems.

A: No, it is probably not possible because Safari is a part of macOS. New versions of Safari come with macOS but you can try finding the Safari downloads at https://support.apple.com/downloads. Double click the .dmg file and complete the installation.


text:
Q: Can I use Siri on my iPhone without having to speak? I have Hey Siri enabled and really love it! But sometimes when I want to use Siri I don't want to speak out loud. Is there a way for me to manually use Siri with a keyboard instead of having to speak? I do not want to turn Hey Siri off. I just want the extra option.

A: You can do what you want with the Type to Siri option.
On your iPhone do as follows:

*

*Open Settings

*Tap on General > Accessibility

*Swipe up until you see the Siri label

*Tap on Siri and enable the Type to Siri option at top of screen

*Exit Settings

Now when you hold your Home button down you'll get a keyboard pop up from the bottom allowing you to type directly to Siri (see screenshot below):


text:
Q: JTable height calculation Solution
jtable.getHeight does not include header element
jtable.getRowHeight include margin
and the example has 15px actual height, not 14px
More clear example
RO 16
R1 16
R2 16
HEIGHT 48
INTERCELL java.awt.Dimension[width=1,height=1]
MARGIN 1

I have JTable with 3 rows. Each row is 16px. And each row margin 1px.
So I suspect that table height should be 16 + 1 + 16 + 1 + 16 = 50px
BUT getHeight returns 48px
Also I did streenshot. Each row has 14px height actually.
How how is it possible????
Source code

    //headers for the table
    String[] columns = new String[] {
        "Id", "Name", "Hourly Rate", "Part Time"
    };

    //actual data for the table in a 2d array
    Object[][] data = new Object[][] {
        {1, "John", 40.0, false },
        {2, "Rambo", 70.0, false },
        {3, "Zorro", 60.0, true },
    };

    //create table with data
    JTable table = new JTable(data, columns);

    //add the table to the frame
    this.add(table);

    this.setTitle("Table Example");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.pack();
    this.setVisible(true);
    System.out.println("RO " + table.getRowHeight(0));
    System.out.println("R1 " + table.getRowHeight(1));
    System.out.println("R2 " + table.getRowHeight(2));
    System.out.println("HEIGHT " + table.getHeight());
    System.out.println("INTERCELL " + table.getIntercellSpacing());
    System.out.println("MARGIN " + table.getRowMargin());
}

Original question
I have simple test frame with jtable in the scroll pane.
The table minimum height is less than actual height.
header + rows < actual size
It is nonsense.
  val jtable = view.tableControl
  val headerHeight = jtable.getTableHeader.getHeight
  val rowsHeight = (0 until jtable.getRowCount()).foldLeft(0) { (heightAccumulator, counter) ⇒
    println("Row " + counter + " height " + jtable.getRowHeight(counter))
    jtable.getRowHeight(counter) + heightAccumulator
  }
  val rowsMargin = jtable.getRowMargin() * (jtable.getRowCount() - 1)
  println("Actual height " + jtable.getHeight())
  println("Header height " + headerHeight)
  println("Margin height " + jtable.getRowMargin())
  println("PreferredScrollableViewportSize" + jtable.getPreferredScrollableViewportSize())
  println("Rows height " + rowsHeight)
  println("Should be at least: " + (rowsHeight + headerHeight + rowsMargin))

and I got
Row 0 height 16
Row 1 height 16
Row 2 height 16
Row 3 height 16
Row 4 height 16
Actual height 80
Header height 19
Margin height 1
PreferredScrollableViewportSizejava.awt.Dimension[width=450,height=400]
Rows height 80
Should be at least: 103

The JTable lays inside the frame without any scroll bars. It is fully visible and there is a lot of space bellow.
How? How jtable.getHeight() of fully visible table may returns height less then (rows * rowHeight + header)?

A: You can substitute your own implementation of Scrollable to get a variety of effects. In particular, override getPreferredScrollableViewportSize() and return a suitable multiple of the row height. Let N be the number of rows after which you want the scrollbar to appear.
JTable table = new JTable(tableModel) {

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        return new Dimension(SOME_WIDTH, N * table.getRowHeight());
    }
};

Add the table to a scroll pane:
JScrollPane sp = new JScrollPane(table);

Add the pane to a panel having a layout that respects preferred size:
JPanel p = new JPanel(new GridLayout());
p.add(sp);

A table having more than N rows will display scroll bars, as shown here.

I just want to find the actual table height [in the context of] unit tests from the huge project.

I don't know exactly how your total height calculation fails, but the result will inevitably change based on the user's platform, the chosen look & feel, and the component validation state; an erroneous approach is suggested here. Instead, attempt to meet the test requirement by ensuring that a paricular number of rows is visible using the approach outlined above.

A:
How? How jtable.getHeight() of fully visible table may returns height less then (rows * rowHeight + header)?

A JTable has a default preferred size that is hardcoded when the table is created because a table is typically added to the viewport of a JScrollPane. As you can see the preferred viewport size is much larger that you need for a small table which would account for the extra space.
If you have a small table and you want it to be fully displayed at it minimum size then you can use code like:
JTable table = new JTable(...);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );


text:
Q: Convert SAV into CSV I tried to convert a SAV file into CSV by using the following code
data = pd.io.stata.read_stata("C:/Users/Nicola/Desktop/Relevant projects activities ACF/BRACED Final Evaluation/Evaluations/CSI_compil_2017.sav")
writer = pd.ExcelWriter('C:/Users/Nicola/Desktop/Baseline.xlsx')
data.to_excel(writer, 'data')
data.to_csv('changed_to_csv.csv')
writer.save()

The output I am getting is the following

ValueError: Version of given Stata file is not 104, 105, 108, 111
  (Stata 7SE), 113 (Stata 8/9), 114 (Stata 10/11), 115 (Stata 12), 117
  (Stata 13), or 118 (Stata 14)

Is there a better snippet I could use to perform this conversion more efficiently? Thanks

A: Please see the following answer :
https://stackoverflow.com/a/20873154/5999386
In short, using import pandas.rpy.common as com to use R capabilities to parse .sav file into Pandas's data frame.

A: I just managed to convert it with this snippet (R Kernel):
library(foreign)
write.table(read.spss("C:/Users/Nicola/Desktop/Relevant projects activities ACF/BRACED Final Evaluation/Evaluations/CSI_compil_2017.sav"), file="from_sav_data.csv", quote = FALSE, sep = ",")

A: import pandas as pd
import pyreadstat as py

df, meta = py.read_sav('file.SAV')
writer=pd.ExcelWriter ("file2.xlsx")
df.to_excel(writer, 'df')
df.to_csv('file2.csv')
writer.save()

A: Here is my class that finds all .sav files in subfolders and converts them to the .csv format. The class successfully coped with files up to 2 GB in size. If you only need to convert one file, just use the convert_sav_to_csv(file_path, dir_to_save=None) function. I used this answer a lot.
import glob
import pandas as pd
import os
import enum
import errno
import pyreadstat

# Enum for size units
class SizeUnit(enum.Enum):
    BYTES = 1
    KB = 2
    MB = 3
    GB = 4

class ConverterSavCsv:
    @staticmethod
    def convert_unit(size_in_bytes, unit):
        """ Convert the size from bytes to other units like KB, MB or GB"""
        if unit == SizeUnit.KB:
            return size_in_bytes / 1024
        elif unit == SizeUnit.MB:
            return size_in_bytes / (1024 * 1024)
        elif unit == SizeUnit.GB:
            return size_in_bytes / (1024 * 1024 * 1024)
        else:
            return size_in_bytes

    @staticmethod
    def get_file_size(file_name, size_type=SizeUnit.BYTES):
        """ Get file in size in given unit like KB, MB or GB"""
        size = os.path.getsize(file_name)
        return ConverterSavCsv.convert_unit(size, size_type)

    @staticmethod
    def find_all_sav_files(upper_dir_path):
        if not os.path.isdir(dir_path):
            raise NotADirectoryError(dir_path)
        files = glob.glob(upper_dir_path + '/**/*.sav', recursive=True)
        files_and_sizes = []
        for elem in files:
            elem_size = ConverterSavCsv.get_file_size(elem, SizeUnit.MB)
            files_and_sizes.append((elem, elem_size))
        result_df = pd.DataFrame(files_and_sizes, columns=['Path', 'Size'])
        result_df = result_df.sort_values(by=['Size'], ascending=False)
        result_df.to_excel(os.path.join(upper_dir_path, r'spss_files_sizes.xlsx'), index=False)
        return result_df

    @staticmethod
    def _dir_filepath_prepare_before_conversion(file_path, dir_to_save=None):
        if not os.path.isfile(file_path):
            raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), file_path)
        base_filename = os.path.basename(file_path)
        base_filename = os.path.splitext(base_filename)[0]
        if dir_to_save is None:
            current_dir = os.path.dirname(file_path)
            dir_to_save = os.path.join(current_dir, r'ready_csv')
            os.makedirs(dir_to_save)
        path_to_save = os.path.join(dir_to_save, base_filename+r'.csv')
        return path_to_save

    @staticmethod
    def convert_sav_to_csv(file_path, dir_to_save=None):
        path_to_save = ConverterSavCsv._dir_filepath_prepare_before_conversion(file_path, dir_to_save)
        _, meta_start = pyreadstat.read_sav(file_path, metadataonly=True)
        number_of_rows = meta_start.number_rows
        reader = pyreadstat.read_file_in_chunks(pyreadstat.read_sav, file_path, chunksize=1000)
        cnt = 0
        for df, meta in reader:
            if number_of_rows is not None:
                print('Processing rows', cnt * 1000, '-', (cnt + 1) * 1000, 'of', number_of_rows)
            if cnt > 0:
                write_mode = "a"
                header = False
            else:
                write_mode = "w"
                header = True
            df.to_csv(path_to_save, mode=write_mode, header=header)
            cnt += 1
        return ConverterSavCsv.get_file_size(path_to_save, SizeUnit.MB)

    @staticmethod
    def convert_all_sav_files_to_csv(sav_files_df, dir_to_save=None):
        if sav_files_df.empty \
                or 'Path' not in sav_files_df.columns \
                or 'Size' not in sav_files_df.columns:
            raise ValueError('Problems with input Pandas dataframe in convert_all_sav_files_to_csv function')
        if dir_to_save is not None:
            if not os.path.isdir(dir_to_save):
                os.makedirs(dir_to_save)
                # raise NotADirectoryError(errno.ENOENT, os.strerror(errno.ENOENT), dir_to_save)
        counter = 1
        files_total = sav_files_df.shape[0]
        for index, row in sav_files_df.iterrows():
            base_filename = os.path.basename(row['Path'])
            base_filename = os.path.splitext(base_filename)[0]
            print('Converting file', base_filename, '-', counter, 'of', files_total, ', with size', row['Size'], 'MB')
            ConverterSavCsv.convert_sav_to_csv(row['Path'], dir_to_save)
            counter = counter + 1
            print()
        return files_total

if __name__ == "__main__":
    dir_path = r'C:\Job\sav_files'
    dir_to_save_path = r'C:\Job\sav_files\csv_ready_files'
    # if dir_to_save_path is None,
    # it creates subdirectory ready_csv and saves there

    # find all SAV files in the directory and convert them to CSV
    converter = ConverterSavCsv()
    df_sav_files_path_size = converter.find_all_sav_files(dir_path)
    num_of_files = converter.convert_all_sav_files_to_csv(df_sav_files_path_size, dir_to_save_path)
    print(num_of_files, '.sav files converted to .csv and saved')

    # for single file
    # use function convert_sav_to_csv(file_path, dir_to_save=None)


text:
Q: Difference between NFC Forum Tag 2 and Mifare Ultralight from developers perspective? I read someplace that Mifare ultralight was ALMOST the same as NFC Forum Tag 2, but not quite. So what is the difference between them?
Can I use the same libnfc commands to access them for example?

A: NFC Forum are specification.
Mifare Ultralight is a product.
Mifare Ultralight is compatible with NFC Forum Type 2 Tag.
Here a usefull document to summarize:
http://open-nfc.org/documents/PRE_NFC_0804-250%20NFC%20Standards.pdf


text:
Q: How to avoid keep double clicking continuously? $('#element').dblclick(function(e){
    console.log("event");
});

When I click the element at a very fast click, it shows the event many times. But I want the user prevent double clicking continuously, maybe skip it for 1 second, how can I do so?

A: var click_allowed = true;
$('#element').dblclick(function(e){
  if (!click_allowed) return;
  console.log("event");
  click_allowed = false;
  window.setTimeout(function() {
    click_allowed = true;
  }, 1000);
}

A: You can use .one to ensure that your event handler runs only once, and then you can rebind it once enough time has elapsed (live demo):
function dblclickHandler(e){
    console.log("event");
    setTimeout(setHandler, 1000);
}

function setHandler() {
    $('#element').one('dblclick', dblclickHandler);
}

setHandler();

A: I would use the doTimeout plugin, specifically the debounce feature: http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/. Try the first example on the second link I posted. Then, just modify it for double clicking instead of keyup.

A: var lastClick = 0;
$('#element').dblclick(function(e){
  var time = (new Date()).getTime();
  if(time > lastClick + 1000) {
    lastClick = time;
    console.log("event");
  }
}


text:
Q: Use explicitly the POST request values in Spring MVC I have some code to generate crypto-currency wallet using a Spring MVC project.
@RequestMapping(value = "/generateAddress", method = RequestMethod.POST)
public ResponseEntity<WalletInfoWrapper> generateAddress(@RequestParam("walletName") String walletName,
                                                         @RequestParam("currencyName") String currencyName, HttpServletRequest request) {

    String wallet_Name = request.getParameter("walletName");
    String currency_Name = request.getParameter("currencyname");

    System.out.println("wallet_Name = " + wallet_Name + " , currency_Name = " + currency_Name);

    // return if the wallet name or the currency is null
    if (Objects.isNull(wallet_Name) || Objects.isNull(currency_Name)) {
        return new ResponseEntity<WalletInfoWrapper>(HttpStatus.NOT_ACCEPTABLE);
    }

    WalletInfo walletInfo = walletService.generateAddress(wallet_Name);

    if (Objects.isNull(walletInfo)) {
        return new ResponseEntity<WalletInfoWrapper>(HttpStatus.NOT_ACCEPTABLE);
    }

    WalletInfoWrapper walletInfoWrapper = new WalletInfoWrapper();
    walletInfoWrapper.setName(walletInfo.getName());

    return new ResponseEntity<WalletInfoWrapper>(walletInfoWrapper, HttpStatus.CREATED);
}

Now, I make this POST request,
curl -X POST -d "walletName=zyx&currencyName=bitcoin" http://localhost:8080/rest/generateAddress

I would like to have the wallet_Name and currency_Name separated and printed as provided in the code. However, after I make the POST request, I see nothing in the console.
        String wallet_Name = request.getParameter("walletName");
        String currency_Name = request.getParameter("currencyname");

        System.out.println("wallet_Name = " + wallet_Name + " , currency_Name = " + currency_Name);

I also tried to POST using the JSON format of data and I get no change. What's the issue here?

A: First of all, I would advice you to switch from using System.out.println and use a proper logger, such as slf4j, since you will probably want at one point to have all your output statements to a file.
There is something not right on how you use spring mvc.
Since you already have @RequestPArams declared for your two fields, why not use them directly instead of doing request.getPrameter("blah"). So I would recommend either removing the @RequestParam and use the HttpServletRequest or vice versa.
Another thing that I saw here String currency_Name = request.getParameter("currencyname"); you made a mistake. You should be doing request.getParameter("currencyName") (observe the N uppercase).
Here is my example for your request. I added both using @RequestParam and making use of request.getParameter(). It's your choice what you want to use. Recommendation nowadays is to use the @RequestParam.
@RestController
public class WalletController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/generateAddress", method = RequestMethod.POST)
    public ResponseEntity<String> generateAddress(@RequestParam("walletName") String walletName,
                                                  @RequestParam("currencyName") String currencyName, HttpServletRequest request) {
        logger.info("walletName {} and currencyName {}", walletName, currencyName);
        String wallet_Name = request.getParameter("walletName");
        String currency_Name = request.getParameter("currencyName");
        logger.info("walletName {} and currencyName {}", wallet_Name, currency_Name);

        // DO other Stuff
        return ResponseEntity.ok(null);
    }
}

testing out the request:
curl -X POST -d "walletName=my-cool-wallet&currencyName=ETH" http://localhost:8080/generateAddress

watching the logs:
2017-08-14 10:11:29.972  INFO 29228 --- [nio-8080-exec-1] c.s.s.controller.WalletController        : walletName my-cool-wallet and currencyName ETH
2017-08-14 10:11:29.972  INFO 29228 --- [nio-8080-exec-1] c.s.s.controller.WalletController        : walletName my-cool-wallet and currencyName ETH

A: I think you should do a POST with a query parameter directly in the URL like the one below since you are trying to pass multiple parameters.
curl -X POST http://localhost:8080/rest/generateAddress?walletName=zyx&currencyName=bitcoin


text:
Q: Dual representations of fundamental representations of a Lie algebra. Let $g$ be a Lie algebra. Let $V(\omega_i)$, $i=1,\ldots,n$, be the fundamental representations. Are the dual representations $V(\omega_i)^*$ highest weight representations?
The dual representation $(\pi^*, V^*)$ of $(\pi, V)$ is defined as $\pi^*(X) = - \pi(X)^T$, $X \in sl_n$.
If yes, how to compute the $\lambda$ in $V(\omega_i)^* = V(\lambda)$? Thank you very much.

A: Let $V\cong \mathbb{C}^n\cong V(\omega_1)$ be the natural representation of $\frak{sl}_n$. $V(\omega_k)\cong \wedge_{i=1}^{k}V$. Taking dual will make all the weight space into its negative weight space. Hence negative of the lowest weight of $\wedge_{i=1}^{k}V$ is the highest weight of $V(\omega_k)^*$.  Hence, $\omega_{n-k}$ is the higest weight of $V(\omega_k)^*$.


text:
Q: Laravel 5.4 - Insertar datos de Droplist y Checkbox en BD Ya tengo las migraciones de tres tablas, TABLA1: 'names' que contiene 'id' y 'name'.
TABLA2: 'sports' que contiene 'id' y 'name', estas dos tablas ya contienen nombres y deportes.
TABLA3: 'ids' contiene 'id', 'names_id' y 'sports_id', pero está vacía ya que quiero llenarla con los ids de las otras dos tablas.
Aquí está mi código.
SelectController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Sport;
use App\Name;

class SelectController extends Controller
{
public function index()
{

  $sports = Sport::all();
  $names = Name::all();
  return view('select', ['sports'=> $sports], ['names'=>$names]);

}
public function store(Request $request)
{

    //
}
}

select.blade.php
<!DOCTYPE html>

  <title>Select name and sports</title>
<form action="/table" method="post">
  {{ csrf_field() }}
  Elija un nombre:

  <select name="names">
    <option value="">Nombre</option>
  @foreach($names as $name)
    <option value="{{ $name->id }}">{{ $name->name}}</option>
  @endforeach
  </select>

  Elija los deportes que practica:

  @foreach($sports as $sport)
  <input type="checkbox" class="form" name="sports" value="{{ $sport->id }}">{{ $sport->name }}

  @endforeach

<input type="submit" name="save" value="Guardar">
</form>

Migraciones
Tabla 'names'
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateNamesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('names', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('names');
}
}

Tabla 'sports'
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSportsTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('sports', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('sports');
}
}

Tabla  'ids'
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateIdsTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('ids', function (Blueprint $table) {
        $table->increments('id');
        $table->string('names_id_');
        $table->string('sports_id');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('ids');
}
}

A: bueno te tengo una forma de hacerlo... no se si fuera la correcta pero te salva por lo pronto.
<!DOCTYPE html>

  <title>Select name and sports</title>
<form action="/table" method="post">
  {{ csrf_field() }}
  Elija un nombre:

  <select name="names">
    <option value="">Nombre</option>
  @foreach($names as $name)
    <option value="{{ $name->id }}">{{ $name->name}}</option>
  @endforeach
  </select>

  Elija los deportes que practica:

  @foreach($sports as $sport)
  <input type="checkbox" class="form" name="sports[]" value="{{ $sport->id }}">{{ $sport->name }}

  @endforeach

<input type="submit" name="save" value="Guardar">
</form>

solo cambie el name de sports a un array.
Ahora en el la ruta:
Route::post('table','TuControlador@laFuncion')

Y dentro del controlador haces esto:
public function laFuncion(Request $request){
    $names_id=$request->names;
    $sports_ids=$request->sports;
    foreach($sports_ids as $id){
        $ids=new TuModeloIds();
        $ids->names_id_=$names_id;
        $ids->sports_id=$id;
        $ids->save();
    }
    //hasta aqui todo guradado en adelante depende de ti
    return redirect()->back();
}

espero haber sido claro, y si te sirve no olvides marcar como respondida


text:
Q: Error while Running ztemyapp MTS Mblaze modem in Ubuntu 14.04 My Ubuntu version is
E7440:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.1 LTS
Release:    14.04
Codename:   trusty

~$uname -a
      Linux ss-Latitude-E7440 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

I have installed MTS Mblaze application.
But I get the following error while running application.

~# ztemtapp
  /usr/local/bin/ztemtApp/bin/App: error while loading shared libraries: libQtGui.so.4: cannot open shared object file: No such file or directory

I tried to install Qt.
apt-get install libQtGui.so.4
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package libQtGui.so.4
E: Couldn't find any package by regex 'libQtGui.so.4'

A: Reason: In 64 bit system , 32 application missing shared libraries.
Solution:
Found the missing libraries usingldd
added foreign architecture:
sudo dpkg --add-architecture i386

Installed i386 version of missing libraries one by one.
Now it is working.


text:
Q: Minimization of two variables
*

*(General) How can I find $$\min\limits_{\phi\leq x\leq \alpha , \ \beta \leq y \leq \delta}\{a+bx,c+dy\}$$ given values of $a,b,c,d,\phi, \alpha, \beta, \delta \in \mathbb{R}?$

*(Specific) How can I find $$\min\limits_{0 \leq x , \ y \ \leq 1}\{.4664048+(2147.0588450)x,0.0313096+(91.2500009)y\}?$$

Thanks.

A: Each of the two terms is linear, so will be minimized at an endpoint, so there are at most four items to check.
For the specific question, since $b,d$ are each positive, they will be minimized when $x=y=0$, so the minimum is $$\min\{.4664048,0.0313096\}=0.0313096$$


text:
Q: Laravel 4 Internal Server Error 500 and TokenMismatchException in a HTML Table to update the database with ajax I have a table where I show basic information. It's basically a two-column table with n rows.
In the second column I show a select tag where the user should choose an option (in this case, a country). The corresponding value of the chosen option will be updated in the database through an ajax call.
The problem is that i always get this 500 internal server error and TokenMismatchException. Do i have to use both a form and make use of the {{ Form::token() }} ???
My code so far that still have this problem is as follows:
The HTML Table (The view):

                        Printed Media
                        Country

                        @foreach($medios as $medio)
                            {{$medio->medio}}
                            <select class="select2 req_place" placeholder="Elija" data-select-search="true"
                                id="medio-{{$medio->id}}" name="medio-{{$medio->id}}"
                                style="background-color: gray;">
                                    <option selected disabled hidden value=''></option>
                                @foreach($paises AS $pais)
                                    <option value="{{$pais->CLAVE}}">{{$pais->PAIS}}</option>
                                @endforeach
                            </select>

                        @endforeach

{{ Form::token() }}

I added {{ Form::token() }}
The Javascript code is:
$('select').change(function(e){
    var id_c = jQuery(this).attr("id");
    var result = id_c.split('-');
    var id = result[1];
    var value = $('#'+id_c).val();
    var url_route = "{{URL::action('DifusionController@post_update_medio')}}";
    var _token = $("input[name=_token]").val();
    var datos = { id: id, value: value, _token: _token };
    alert('A country was selected! id: '+id_c + '. Value: '+ value + '. id: '+id);
    alert(url_route);

    $.post(url_route, datos, function(data,status){
        if(data=='success'){
            alert('Success gotten');
        }
    });
});

And my routes inside the csrf group:
/**** CSRF protection group ****/
Route::group(array('before'=>'csrf'),function(){
    /*Update medios*/
    Route::post('/pendientes/medios',array(
        'as'    =>  'post-update-medio',
        'uses'  =>  'DifusionController@post_update_medio'
        ));
    /*Update reporteros*/
    Route::post('/pendientes/reporteros',array(
        'as'    =>  'post-update-reportero',
        'uses'  =>  'DifusionController@post_update_reportero'
        ));
...
}

Inside the controller:
public function post_update_medio()
{
    if (Request::ajax())
    {
        $token=Request::header('X-CSRF-Token');// : Input::get('_token');
        $id=Input::get('id');
        $value=Input::get('value');

        if(Input::has('id') && Input::has('value'))
        {
            echo 'Medio Posted ☺. ID: '.$id.'. Value: '.$value.' Token: '.$token.' . ';
            /*Update database here*/
            return 'success';
        }
        else
        {
            return 'error';
        }
    }
    else
    {
        return 'No ajax request';
    }
}

And the Chrome inspector returns the following error:
error: {type: "Illuminate\Session\TokenMismatchException", message: "",…}
file: "\MY\PATH\app\filters.php"
line: 179
message: ""
type: "Illuminate\Session\TokenMismatchException"

Must i add a form with token?
How can i fix this?
But now it works after editing both the jquery code and the controller.
References:

*

*CSRF tokens when using jQuery Ajax

*Generating a CSRF token

A: You may add a token in your HTML as a hidden field like
<input type="hidden" id="token" value="{{csrf_token()}} >

And then pass it to your ajax post request as _token


text:
Q: There is Trac, there is Babel, but I don't see "language" I've installed on a Debian system Trac 0.12 (thanks to easy_install install Trac 0.11, but I want 0.12 ) and know I want to get the localization (for French).
So I've installed Babel, but that doesn't work. I've uninstalled and re-installed Trac, but that doesn't work: I don't see "Language" in the preference panel.
I do the same thing on a mandriva system, and that works like a charm.
What's happend? How can I resolve that?

A: Make sure you have Babel installed before installing Trac. Only this way you enable the i18n-related functions.
Btw, Trac 0.12 is the first version with translated web-UI, with 0.11 and before you'd never see it, because it's simply not there.


text:
Q: 16 colors for background in MCGA BIOS text mode (AL = 03h) MCGA supports 4-bits color depth, that is 16 colors. But when I try to print all of these colors, I get only first 8 of them and the rest 8 simply duplicate them as on the pic below. Can it be that I'm doing something wrong here or it is all because of DOSBox?

The code (MASM, under DOSBox 0.74):
TITLE   PROGRAM193
;----------------------------------------------------------
        .MODEL      SMALL
        .STACK      64
        .DATA
;----------------------------------------------------------
        .CODE
MAIN    PROC    FAR
    MOV     AX, @DATA
    MOV     DS, AX

    MOV     AX, 0600h    ;AH = 06h (scroll up window)
    ; black (0)
    MOV     BH, 0Fh      ;0 (black) background, F (white) text
    MOV     CX, 0000h    ;upper line, left column
    MOV     DX, 004Fh    ;finishing line, right column
    INT     10h

    ; blue (1)
    MOV     BH, 1Fh
    MOV     CX, 0100h
    MOV     DX, 014Fh
    INT     10h

    ; green (2)
    MOV     BH, 2Fh
    MOV     CX, 0200h
    MOV     DX, 024Fh
    INT     10h

    ; cyan (3)
    MOV     BH, 3Fh
    MOV     CX, 0300h
    MOV     DX, 034Fh
    INT     10h

    ; red (4)
    MOV     BH, 4Fh
    MOV     CX, 0400h
    MOV     DX, 044Fh
    INT     10h

    ; magenta (5)
    MOV     BH, 5Fh
    MOV     CX, 0500h
    MOV     DX, 054Fh
    INT     10h

    ; brown (6)
    MOV     BH, 6Fh
    MOV     CX, 0600h
    MOV     DX, 064Fh
    INT     10h

    ; light gray (7)
    MOV     BH, 7Fh
    MOV     CX, 0700h
    MOV     DX, 074Fh
    INT     10h

    ;  -------------------------------
    ; | The problem starts up here... |
    ;  -------------------------------
    ; dark gray (8)
    MOV     BH, 8Fh
    MOV     CX, 0800h
    MOV     DX, 084Fh
    INT     10h

    ; light blue (9)
    MOV     BH, 9Fh
    MOV     CX, 0900h
    MOV     DX, 094Fh
    INT     10h

    ; light green (A)
    MOV     BH, 0AFh
    MOV     CX, 0A00h
    MOV     DX, 0A4Fh
    INT     10h

    ; light cyan (B)
    MOV     BH, 0BFh
    MOV     CX, 0B00h
    MOV     DX, 0B4Fh
    INT     10h

    ; light red (C)
    MOV     BH, 0CFh
    MOV     CX, 0C00h
    MOV     DX, 0C4Fh
    INT     10h

    ; light magenta (D)
    MOV     BH, 0DFh
    MOV     CX, 0D00h
    MOV     DX, 0D4Fh
    INT     10h

    ; yellow (E)
    MOV     BH, 0EFh
    MOV     CX, 0E00h
    MOV     DX, 0E4Fh
    INT     10h

    ; white (F)
    MOV     BH, 0F1h
    MOV     CX, 0F00h
    MOV     DX, 0F4Fh
    INT     10h

    MOV     AX, 4C00h
    INT         21h
MAIN    ENDP
        END     MAIN

A: By default, there are 16 colors for text and only 8 colors for background.
There is a way to get all the 16 colors for background, which requires turning off the "blinking attribute".
Here is how it can be done:
MAIN    PROC    FAR
    MOV     AX, @DATA
    MOV     DS, AX

    ; turn-off blinking attribute
    MOV     AX, 1003h
    MOV     BL, 00
    INT     10h

    MOV     AX, 0600h    ;AH = 06h (scroll up window)
    ; black (0)
    MOV     BH, 0Fh      ;0 (black) background, F (white) text
    MOV     CX, 0000h    ;upper line, left column
    MOV     DX, 004Fh    ;finishing line, right column
    INT     10h

    ; the rest of the magic...

The result is shown below:

A: Ooh - ancient technology indeed!
16 colours are available in the foreground, but only 8 for the background. The top bit was used for blink, and was sometimes not implemented.


text:
Q: toggleClass on slide up I am toggling li with the same class name. When one li is clicked open, the other li slide up.
Each li has a plus sign next to it and when clicked an li is click to expand the plus sign becomes a minus by toggling the class fa-plus to be fa-minus.
However, when the open li automatically slide up because another li is clicked, the icon stays as a minus doesn't change back to be a plus.
Here is my jsfiddle: http://jsfiddle.net/a3mn8yoo/

        Refine by 1

Silverstone

Prestwold Hall

        Refine by 2

£25

£50

        Refine by 3

London

South West

Any ideas?

A: You code held an idea already, in a similar way you slideUp other divs, you can toggle the "-"
$(".has_submenu a").not(this).find(" .fa-minus").toggleClass('fa-plus fa-minus');

http://jsfiddle.net/a3mn8yoo/1/

A: You had:
$(this).closest(".has_submenu").find(".fa-plus, .fa-minus");

I added:
$(this).closest(".has_submenu").find(".fa-plus, .fa-minus").end().siblings().find('.fa-minus').toggleClass('fa-plus fa-minus');

Try this updated fiddle:
http://jsfiddle.net/a3mn8yoo/6/


text:
Q: Why does my shadow dom break my custom element? Here is a JSFiddle demonstration of the custom element: https://jsfiddle.net/c4bLo097/5/
Here is the code from the fiddle:
JavaScript:
window.customElements.define('test-element', class TestElement extends HTMLElement {
    constructor() {
    super()

    let contents = `
      `

    // convert string to nodes
    let template = document.createElement('template')
    template.innerHTML = contents

    // create shadow
    this.attachShadow({mode: 'open'})

    // insert nodes
    this.shadowRoot.appendChild(template.content.cloneNode(true))
  }
})

HTML:
<test-element>
    This element should have a natural height.

    I should be able to see this text on a green background.
</test-element>

CSS:
test-element {
  width: 200px;
  background: green;
}

If you inspect <custom-element> with your developer tools, you should see that the shadow is there. But my element will not render its height correctly.
Here is an example JSFiddle of what I'm trying to achieve: https://jsfiddle.net/9483s1qb/2/

A: When you add shadowDOM the content of your element becomes "lightDOM"..
It is no longer displayed in the main DOM and not part of your shadowDOM.
As Supersharp explained in 2017:

The Light DOM is simply the plain old DOM tree inside a HTML element.
The term is only used in context of Web Components (Custom Elements WITH Shadow DOM)
I suppose the normal DOM was redefined as Light in contrast with Shadow.
The WHATWG specs call it the shadowroot host's node tree, or light tree:

The Shadow DOM is the added DOM that recovers, masks, or replaces the normal DOM,
as explained in the article from Google.

You have to transfer lightDOM content to shadowDOM yourself:

*

*with SLOTs:
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots

*or with code

customElements.define('my-element', class extends HTMLElement {
    constructor() {
    //create shadowDOM (thus creating lightDOM) and append Template
    super() /* return this */
        .attachShadow({mode: 'open'}) /* SETs and RETURNs this.shadowRoot */
        .append(document.getElementById(this.nodeName).content.cloneNode(true))
  }
  connectedCallback(){
    //append content from lightDOM
    this.shadowRoot.append(...this.querySelectorAll('DIV'));
  }
})
my-element{
  border: 1px dashed blue;
}
<template id="MY-ELEMENT">

<slot name="title"></slot>

</template>

<my-element>

  whole SPAN is slotted

I am appended

appended too

I remain (invisible) in lightDOM

</my-element>

<my-element>

  slotted too

appended again

  I remain (invisible) in lightDOM

</my-element>

Snippet Notes:

*

*The template is cloned

*the append in the connectedCallback moves the content,
if you want to leave the original in lightDOM (eg. use it as a datastore)
you have to clone it like done with the template.

*the slot="title" reflects the whole span(including the span!) to its slot in shadowDOM
See: ::slotted CSS selector for nested children in shadowDOM slot

*Do try yourself:
In the JSFiddle playground: https://jsfiddle.net/CustomElementsExamples/bzvLcxfe/

*What happens with an unnamed: <slot></slot>?

*What happens if you change the  to a


text:
Q: low latency data link pc to android can anyone recommend a method for low latency bi-directional com link between my pc app and android slave app. the app i have works now via wifi but the latency is too slow (about 300mS), i'm looking to get it down to 10mS or so.
the android is acting like a glorified remote control to the game on the pc. the apk displays a low res image and sends button presses back to the game and the round trip need to be quick
i'm thinking the only option beside the network, is to connect a usb cable but i don't see a lot of support for that path and not even sure it would be lower latency than wifi
any ideas please?

A: USB would have much lower latency, and there's plenty of USB support in Android.  Check out http://developer.android.com/guide/topics/connectivity/usb/accessory.html  Bluetooth may also be an option, but I'm not sure if it will get you to the latency you want-  USB can.


text:
Q: Why my Checkbox change to text Why my checkbox change to text?
How to make it we tick whatever checkbox the result change? Can anyone fix my coding? In addition, I want my checkbox more tidy. I don't want it so close with each other checkbox.

    <input type="checkbox" id="Animal" onclick="ShowHideDiv(this)" value="Animal"/> Animal

<form>

    <input type="checkbox" id="subAnimal1" onclick="fungsi()"/>123

   <input type="checkbox" id="subAnimal2" onclick="fungsi()"/>456

   <input type="checkbox" id="subAnimal3" onclick="fungsi()"/>789

    <input type="checkbox" id="subAnimal4" onclick="fungsi()"/>101112

   <input type="checkbox" id="subAnimal5" onclick="fungsi()"/>KIV

A: You have duplicate id subAnimal in the page.

...

here is the modified version:

<input type="checkbox" id="Animal" onClick="ShowHideDiv(this)" value="Animal"/> Animal

<form>

<input type="checkbox" id="subAnimal1" onclick="fungsi()"/>123

  <input type="checkbox" id="subAnimal2" onclick="fungsi()"/>456

  <input type="checkbox" id="subAnimal3" onclick="fungsi()"/>789

<input type="checkbox" id="subAnimal4" onclick="fungsi()"/>101112

  <input type="checkbox" id="subAnimal5" onclick="fungsi()"/>KIV

</form>

A: In Both id is duplicate so try below code

    <input type="checkbox" id="Animal" onclick="ShowHideDiv(this)" value="Animal"/> Animal

<form>

    <input type="checkbox" id="subAnimal1" onclick="fungsi()"/>123

   <input type="checkbox" id="subAnimal2" onclick="fungsi()"/>456

   <input type="checkbox" id="subAnimal3" onclick="fungsi()"/>789

    <input type="checkbox" id="subAnimal4" onclick="fungsi()"/>101112

   <input type="checkbox" id="subAnimal5" onclick="fungsi()"/>KIV


text:
Q: How do I move my main git directory (.git directory) to another folder in my Windows C drive? When Git was set up in my Windows system, the root folder selected was /c/Users/anita. I want to change this location as there are my other files in this location that have nothing to do with my Git projects. I've created a new folder named Git projects inside c/Users/. How do I make this new location the .git directory?

A: well in theory you should be able to cut and paste those files to the new folder without problems, what i recommend you is: copy the git related files to the new dir and then update the global enviroment variable heading to the old folder anita to the new folder you choose

A: Technically, you could move the .git folder (that contains all git data) wherever you want (even if it is highly recommended to move it in an empty folder).
A good advice I could give you before moving the folder is to run a git gc to pack all the git objects and make the copy quicker (especially if the repository history is big).
Your biggest concern will be what to do with the files in the working directory.
To solve this issue, the easier is to commit and after, if needed, stash all the uncommitted remaining changes.
That way, you not necessarily need to copy all the working directory files (and so the copy is quicker) and, if needed, you could recover all the files with the 2 commands:
git reset --hard Head # restore all files
git stash pop # restore uncommitted changes (if you have created a stash)


text:
Q: Python: rename duplicates based on different conditions I have the following dataframe in python:
With different companies and different investment rounds with only undisclosed investors. Based on some other calculations, we have managed to get a "dummy" for if we have a "new" of either type A or B undisclosed investor for one of the companies. The rule being if the sum of undisclosed investors of type A or B is more than the sum in round t, then the new investor of type A or B gets a dummy.
Company_ID  Customer_ID  Investor_type  Round      Dummy
    amazon  Undisclosed       A          1          1
    amazon  Undisclosed       B          2          1
    amazon  Undisclosed       B          3          0
    amazon  Undisclosed       A          3          0
    amazon  Undisclosed       B          4          0
    amazon  Undisclosed       B          4          1
    amazon  Undisclosed       B          4          1
    amazon  Undisclosed       B          5          0
    amazon  Undisclosed       B          5          0
    amazon  Undisclosed       B          5          0
    amazon  Undisclosed       B          5          1
    Apple   Undisclosed       A          1          1
    Apple   Undisclosed       B          2          1
    Apple   Undisclosed       B          3          0
    Apple   Undisclosed       A          3          0
    Apple   Undisclosed       B          4          0
    Apple   Undisclosed       B          4          1
    Apple   Undisclosed       B          4          1

What we want to do is to is to change the names of the undisclosed firms to reflect this. I.e. everytime the dummy = 1, then this will reflect a new firm name, for example like this:
Company_ID  Customer_ID  Investor_type  Round      Dummy
    amazon  Undisclosed_1     A          1          1
    amazon  Undisclosed_2     B          2          1
    amazon  Undisclosed_2     B          3          0
    amazon  Undisclosed_1     A          3          0
    amazon  Undisclosed_2     B          4          0
    amazon  Undisclosed_3     B          4          1
    amazon  Undisclosed_4     B          4          1
    amazon  Undisclosed_2     B          5          0
    amazon  Undisclosed_3     B          5          0
    amazon  Undisclosed_4     B          5          0
    amazon  Undisclosed_5     B          5          1
    Apple   Undisclosed_6     A          1          1
    Apple   Undisclosed_7     B          2          1
    Apple   Undisclosed_7     B          3          0
    Apple   Undisclosed_6     A          3          0
    Apple   Undisclosed_7     B          4          0
    Apple   Undisclosed_8     B          4          1
    Apple   Undisclosed_9     B          4          1

The main problem is getting it to do this correctly with "jumps" back and forth, as well as when company id switches continuing from Undisclosed_5 to Undisclosed_6 once Company_ID changes to Apple. It would also work without this rule, i.e. it just starts over from Undisclosed_1.
Have tried several codes with multiple loops etc but cant get it to work, any help is greatly appreciated!


text: Q: Flutter-Firebase Document Entry for First Time Login I want a Flutter Code for Writing Google Sign in and Making Entry in Database in Firebase also for first time he  be able to edit His username and Profile Pic?


text:
Q: Localization for ENG/AR language is inconsistent I have been working on a bilingual site which shows Arabic and English content. I have stored value arabic and english values in App_GlobalResources >> Resource file with following names

*

*Messages.ar-LB.resx

*Messages.resx

Syantax for fetching data from global resource
Syntax for Jquery-->
"<%= Resources.Messages.userName %>"

or
<%= GetGlobalResourceObject("Messages", "userName ") %>

Aspx Codebehind -->
Resources.Messages.userName

Every page I use is inherits basepage in which i have overridden InitializeCulture() in which i set current culture to EN-US or AR-LB depending on user preference.
Problem :-  some of the pages render Arabic lables properly using jquery as well codebehind but fails to do in other pages. I am not able to find any significance difference between these pages.
Am i missing something here?
UPDATE:
This is how i set culture.
protected override void InitializeCulture()
    {
         SetCulture("ar-LB","ar-LB"); // Example
    }
protected void SetCulture(string name, string locale)
    {
          // parameters passed here-> (, ar-LB)
          Thread.CurrentThread.CurrentUICulture = new CultureInfo(name);
          Thread.CurrentThread.CurrentCulture = new CultureInfo(locale);
    }


text:
Q: kie server response handling I'm getting below error when I tried to hit kie server from java application

Exception in thread "main"
  org.kie.server.client.KieServicesException:    Error while creating
  service  response!   The actual result type class
  org.kie.server.api.model.KieContainerResourceList     does not match
  the         expected type class
  org.kie.server.api.model.KieServerInfo!

Can anyone please help me in resolving this
    Getting error at below location in my code :
 KieServicesClient client = KieServicesFactory.newKieServicesClient(config);

A: I suppose that you are using REST transport protocol in Kie server client.
It seems that you put wrong server URL parameter to your instance of KieServicesConfiguration. Correct URL looks like this:

http://<server>:<port>/<context>/services/rest/server

Your server URL seems to be:

http://<server>:<port>/<context>/services/rest/server/containers

Which is actually URL of endpoint for retrieving containers list in Kie server.


text:
Q: How to handle thousands of legacy urls in Django, Varnish, Nginx? We are building a Django app to replace a legacy system which used custom URLs for almost every resource. No pattern to the URLs at all. There are about 350,000 custom URLs that we now need to 301 redirect to a correct URL in the new system.
Our new system will use Django, but will also have Varnish and Nginx in front of it, so we could use any of these tools for the solution.
In Django, I think we could either make a very very large custom urls.py file, or maybe make a middleware that does a database lookup against a table with all the redirects.
Or perhaps there's a way to handle this in Varnish or Nginx so the requests never even hit Django.
My question: what's the most performant way to handle thousands of custom URL redirects?

A: It all depends on the load actually... if you have a lot of requests going to the old urls than it might be useful to have some caching. But in general I would say that doing it in Django, adding all of the urls to a database model and querying (optionally caching the results in Django or even Varnish) should do the trick.
These things are not impossible to do in Varnish or Nginx but Django will be far easier to link up to a database so that would have my vote.


text:
Q: Update values of an array in Pyspark Dataframe I want to check if last two values of the array in PySpark Dataframe is [1, 0] and update it to [1, 1]
Input Dataframe
Column1    Array_column
abc        [0,1,1,0]
def        [1,1,0,0]
adf        [0,0,1,0]

Output Dataframe
Column1    Array_column
abc        [0,1,1,1]
def        [1,1,0,0]
adf        [0,0,1,1]

A:  >>> def udf1(i):
      if (i[2]==1) & (i[3]==0):
       i[3]=1
      else:
        i[3]=i[3]
      return i

>>> udf2=udf(udf1)
df1.withColumn("Array_Column",udf2(col("Array_Column"))).show()

+-------+------------+
|Column1|Array_Column|
+-------+------------+
|    abc|[0, 1, 1, 1]|
|    def|[1, 1, 0, 0]|
|    adf|[0, 0, 1, 1]|
+-------+------------+

A: You can slice the array, do a case when for the last two elements, and combine the two slices using concat.
import pyspark.sql.functions as F

df2 = df.withColumn(
    'Array_column',
    F.expr("""
        concat(
            slice(Array_column, 1, size(Array_column) - 2),
            case when slice(Array_column, size(Array_column) - 1, 2) = array(1,0)
                 then array(1,1)
                 else slice(Array_column, size(Array_column) - 1, 2)
            end
         )
    """)
)

df2.show()
+-------+------------+
|Column1|Array_column|
+-------+------------+
|    abc|[0, 1, 1, 1]|
|    def|[1, 1, 0, 0]|
|    adf|[0, 0, 1, 1]|
+-------+------------+

A: You can combine array functions with when expression :
from pyspark.sql import functions as F

df1 = df.withColumn(
    "Array_column",
    F.when(
        F.slice("Array_column", -2, 2) == F.array(F.lit(1), F.lit(0)),
        F.flatten(F.array(F.expr("slice(Array_column, 1, size(Array_column) - 2)"), F.array(F.lit(1), F.lit(1))))
    ).otherwise(F.col("Array_column"))
)

df1.show()

#+-------+------------+
#|Column1|Array_column|
#+-------+------------+
#|    abc|[0, 1, 1, 1]|
#|    def|[1, 1, 0, 0]|
#|    adf|[0, 0, 1, 1]|
#+-------+------------+