text:
Q: Java 8 Streams peek/map without collecting is not giving output The below code is not printing any values. None of the System.out.println() statements are getting printed. I assumed peek deals with modifying data. Surprisingly the logic inside the peek() is not even getting executed.
If I collect the stream using Collectors I see the desired behavior.

*

*Why at least the print statement 1 isn't getting executed?

*Why isn't the external object (output list) is not getting appended with the desired values?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class HelloWorld {
    public static void main(String[] args) {
        List<String> input = new ArrayList<>(Arrays.asList("hello", "bye", "vacation"));
        List<String> output = new ArrayList<>();
        input.stream().peek(x -> {
            System.out.println(x+"inside"); // print statement 1
            if (x.length() > 3) {
                output.add(x.toUpperCase());
            }
        });

        output.forEach(System.out::println); // print statement 2
    }
}

A: There are several issues in the code:

*

*The Stream is not closed with a terminal operation, therefore no pipeline operation is invoked.

*Stream::peek is an intermediate operation used mainly for debugging.

*You should never use any side-effect or stateful operation inside the stream - calling output.add(x.toUpperCase()); is not good.

*The output is empty so nothing is printed out as long as the Stream is not closed (see the no. 1).

All you need to understand Stream API is at the package description. Finally, you can conclude into something like:
List<String> output = input.stream()              // Stream<String>
    .peek(x -> System.out.println(x + " inside")) // print each value
    .filter(x -> x.length() > 3)                  // filter Strings longer than 3 chars
    .map(x -> x.toUpperCase())                    // make them uppercase using map
    .collect(Collectors.toList());                // to List - a terminal operation

A: When Stream#peek(Consumer) is referenced, a new StatelessOp object is created from the existing Stream. However, the method from the StatelessOp object called opWrapSink is only called when the Stream elements are consumed. You are not consuming the elements of the Stream at any point. In the documentation the reasoning is that intermediate operations are done lazily.

Laziness-seeking. Many stream operations, such as filtering, mapping,
or duplicate removal, can be implemented lazily, exposing
opportunities for optimization. For example, "find the first String
with three consecutive vowels" need not examine all the input strings.
Stream operations are divided into intermediate (Stream-producing)
operations and terminal (value- or side-effect-producing) operations.
Intermediate operations are always lazy.

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

A: You lack a terminal operator on your stream, so nothing will happen with it.
See https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html:

Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.

The .collect is a terminal operator which explains why it works when you replace close with collect.


text:
Q: ibus input method doesn't work in code-OSS I could write multilingual LaTeX document in Arch using Visual Studio Code or Code-OSS and ibus-m17n BUT in Void ibus-m17n input method seems to work in libreoffice, kate kwrite, etc.! In Code-OSS, it outputs only English!
Anyway to fix this issue?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uncaught Error: Module parse failed: Unexpected token (3:9) File was processed with these loaders: am new in programming. trying to follow a tutorial  on a Crypto wallet that displays real charts, but error message 1   I got these errors below.
Thanks in advance for your help.
my dependencies
This is the error message on my console:
wrapNativeSuper.js:42 Uncaught Error: Module parse failed: Unexpected token (3:9)
File was processed with these loaders:
 * ./node_modules/@expo/webpack-config/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| import "./reanimated2/js-reanimated/global";
| export * from "./reanimated2";
> export * as default from "./Animated";
    at ./node_modules/@rainbow-me/animated-charts/node_modules/react-native-reanimated/lib/index.web.js (wrapNativeSuper.js:42:1)
    at __webpack_require__ (bootstrap:789:1)
    at fn (bootstrap:100:1)

These are my dependencies:
"dependencies": {
    "@rainbow-me/animated-charts": "^1.0.0-alpha.6",
    "@react-navigation/bottom-tabs": "^6.4.0",
    "@react-navigation/native": "^6.0.8",
    "@react-navigation/stack": "^6.1.1",
    "axios": "^0.27.2",
    "expo": "^46.0.10",
    "expo-font": "^10.0.5",
    "expo-updates": "^0.14.5",
    "express": "^4.18.1",
    "moment": "^2.29.4",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "react-native": "0.69.5",
    "react-native-reanimated": "~2.9.1",
    "react-native-safe-area-context": "4.3.1",
    "react-native-svg": "12.3.0",
    "react-native-web": "~0.18.7",
    "react-navigation-tabs": "^2.11.2",
    "react-redux": "^8.0.2",
    "redux": "^4.2.0",
    "redux-thunk": "^2.4.1",
    "request": "^2.79.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@expo/webpack-config": "^0.16.19"
  },


text:
Q: Regular expresion gets really confusing when involving "r" and "/" In order to better understand how r and / work, I did some testing within Python's IDLE. The results are as follows:
    >>> 11111111111111111111111111111111111111111
    11111111111111111111111111111111111111111
    >>> re.sub(r'\?', r'\?', '?ttt?')
    '\\?ttt\\?'
    >>> re.sub('\?', r'\?', '?ttt?')
    '\\?ttt\\?'
    >>> re.sub('\\?', r'\?', '?ttt?')
    '\\?ttt\\?'
    >>> re.sub(r'\\?', r'\?', '?ttt?')
    '\\??\\?t\\?t\\?t\\??\\?'
    >>> 222222222222222222222222222222222222222
    222222222222222222222222222222222222222
    >>> re.sub(r'\?', r'\?', '?ttt?')
    '\\?ttt\\?'
    >>> re.sub(r'\?', '\?', '?ttt?')
    '\\?ttt\\?'
    >>> re.sub(r'\?', '\\?', '?ttt?')
    '\\?ttt\\?'
    >>> re.sub(r'\?', r'\\?', '?ttt?')
    '\\?ttt\\?'
    >>> 333333333333333333333333
    333333333333333333333333
    >>> re.sub(r'(\?)', r'\1\1', '?ttt?')
    '??ttt??'
    >>> re.sub(r'(\?)', '\1\1', '?ttt?')
    '\x01\x01ttt\x01\x01'
    >>>

For the first argument of re.sub():

*

*How come r'\?', '\?', '\\?'work the same, while r'\\?' works differently?

*And why does re.sub(r'\\?', r'\?', '?ttt?') get such a weired result?
For the second argument of re.sub():

*

*Why is that r'\?', '\?', '\\?' and  r'\\?' all work the same?

*When numbers are involved, the r is almost always necessary, such as r'\1\1' and '\1\1'. But I don't see why '\1' is the same as '\x01'.

A: The first thing to understand is how Python treats escape sequences:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character

For example, in '\\?', the fist backslash escapes the second backslash to produce just \?.

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the result. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals.

So in '\?', because \? isn't a valid escape sequence, Python leaves it as just \?. However, style checkers like Pylint will flag an "Anomalous backslash in string" warning.
When working with strings that contain lots of backslashes, you can use Python's raw string syntax to avoid the need to escape them:
>>> r'\?' == '\\?' == '\?' # These are all equivalent
True
>>> r'\?' == r'\\?'        # But r'\\?' is different
False
>>> r'\\?' == '\\\\?'
True

Numbers also have a special meaning when escaped (they are treated as octal):
>>> '\141' == 'a'
True

The second thing to understand is how Python treats the backslash in regular expressions:

Perhaps the most important metacharacter is the backslash, \. As in Python string literals, the backslash can be followed by various characters to signal various special sequences. It's also used to escape all the metacharacters so you can still match them in patterns; for example, if you need to match a [ or \, you can precede them with a backslash to remove their special meaning: \[ or \\.

For example, in re.sub(r'\?', r'\?', '?ttt?'), the first argument r'\?' tells the regular expression library that we want to search for the ? character rather than treating ? as a qualifier. If we didn't use raw strings, we would need to write re.sub('\\?', '\\?', '?ttt?').
In contrast, in re.sub(r'\\?', r'\?', '?ttt?'), the first argument r'\\?' tells the regular expression library that we want to search for a \ character, and ? is a special regex qualifier that treats the previous character as optional (in this case, causing the pattern to always match). If we didn't use raw strings, we would need to write re.sub('\\\\?', '\\?', '?ttt?').

In short, to match a literal backslash, one has to write '\\\\' as the RE string, because the regular expression must be \\, and each backslash must be expressed as \\ inside a regular Python string literal.

Yes, regular expressions with raw strings and \ get really confusing, but it's even more confusing without raw strings!

Additional details: The way backslashes are treated in the second argument to re.sub is a bit different to the first argument. The regular expression library still needs to provide a way to escape backslashes, else there would be no way to distinguish between between backreferences such as r'\1', and literally wanting to replace matches with a backslash followed by a one. However, other regular expression syntax such as ? doesn't need to be escaped, because it has no special meaning in the second argument. According to the documentation for the second argument of re.sub:

... any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \& are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern.

So the regular expression library treats re.sub(r'\?', r'\?', '?ttt?') the same as re.sub(r'\?', r'\\?', '?ttt?'), because \? is an unknown regular expression escape sequence for the second argument (even though it is a recognised regular expression escape sequence for the first argument). This is kind of similar to how Python treats '\?' the same as '\\?', but is to do with how the regular expression library chooses to treat backslashes rather than anything to do with the Python syntax itself.


text:
Q: Load different views depending on the category of data on tap of tableview cell iPhone sdk In my aplication, I want a tableview with different cell structure depending upon the category of data that's getting loaded in it [I have different categories like video, editorial etc with different structure of data like video has a single label, editorial has 3 labels etc]. I can load different nib files based on the data coming from xml parser.
Now when the cell is tapped, I want to show its detailed view on a new viewController. So my question is is it possible to use only 1 viewController show different fields depending upon the category of data in the cell. Or do I need to create different viewControllers for each of the categories?

A: It depends on what kind of data you have in each of your categories. If the format of the data in each categories is different and you already know it, design viewControllers such that they directly read the data and display it however necessary. The viewController should itself handle the displaying logic.
On the other hand, if all categories are of the same type, you can create multiple instances of the same viewController, use them and release them as necessary.
In your case, it sounds like the second option can be preferred.
Edit: It would be wise to go with different sub-classes of viewControllers keeping design pattern in mind - "Closed for modification and open for extension".

A: You can write code to do whatever you like.  But using the same object to display multiple object types wouldn't be considered good practice, assuming that the elements you will be displaying are different.
In OOP, we normally create different classes to simplify code, and share code using various strategies, of which subclassing is would seem appropriate to this case.
Meaning: create a class to handle the general cases applicable to all the object types you want to display, and subclass for the specific requirements for each type.

A: You can use single view controller. Only thing is you need to feed the data to be displayed in that view controller.
But keeping separate controllers for different functionality will make your code pretty neat and easy to handle. So It would be better if you keep separate controller for handling the data.


text:
Q: Techniques for calculating adjective frequency I need to calculate word frequencies of a given set of adjectives in a large set of customer support reviews. However I don't want to include those that are negated.
For example suppose my list of adjectives was: [helpful, knowledgeable, friendly]. I want to make sure "friendly" isn't counted in a sentence such as "The representative was not very friendly."
Do I need to do a full NLP parse of the text or is there an easier approach? I don't need super high accuracy.
I'm not at all familiar with NLP. I'm hoping for something that doesn't have such a steep learning curve and isn't so processor intensive.
Thanks

A: It depends on the source of your data. If the sentences come from some kind of generator, you can probably split them automatically. Otherwise you will need NLP, yes.
Properly parsing natural language pretty much is an open issue. It works "largely" for English, in particular since English sentences tend to stick to the SVO order. German for example is quite nasty here, as different word orders convey different emphasis (and thus can convey different meanings, in particular when irony is used). Additionally, German tends to use subordinate clauses much more.
NLP clearly is the way to go. At least some basic parser will be needed. It really depends on your task, too: do you need to make sure every one is correct, or is a probabilistic approach good enough? Can "difficult" cases be discarded or fed to a human for review? etc.

A: If all you want is adjective frequencies, then the problem is relatively simple, as opposed to some brutal, not-so-good machine learning solution.
Wat do?
Do POS tagging on your text. This annotates your text with part of speech tags, so you'll have 95% accuracy or more on that. You can tag your text using the Stanford Parser online to get a feel for it. The parser actually also gives you the grammatical structure, but you only care about the tagging.
You also want to make sure the sentences are broken up properly. For this you need a sentence breaker. That's included with software like the Stanford parser.
Then just break up the sentences, tag them, and count all things with the tag ADJ or whatever tag they use. If the tags don't make sense, look up the Penn Treebank tagset (Treebanks are used to train NLP tools, and the Penn Treebank tags are the common ones).
How?
Java or Python is the language of NLP tools. Python, use NLTK. It's easy, well documented and well understood.
For Java, you have GATE, LingPipe and the Stanford Parser among others. It's a complete pain in the ass to use the Stanford Parser, fortunately I've suffered so you do not have to if you choose to go that route. See my google page for some code (at the bottom of the page) examples with the Stanford Parser.
Das all?
Nah, you might want to stem the adjectives too- that's where you get the root form of a word:
cars -> car
I can't actually think of a situation where this is necessary with adjectives, but it might happen. When you look at your output it'll be apparent if you need to do this. A POS tagger/parser/etc will get you your stemmed words (also called lemmas).
More NLP Explanations
See this question.


text:
Q: How to install Clang 11 on Debian I am trying to compile a C++ project on a PC with "Debian GNU/Linux 10". The project requires clang, so I installed it with:
sudo apt-get install clang

But I run into the following error:
Clang version must be at least 11, the version used is 7.0.1

How can I install clang 11?
Note: I do not want to install the entire LLVM package again. Just want to upgrade Clang from version 7 to 11, preferably via command-line.

A: I found the solution after some searching. Here is what I did to make it work:

*

*Add the following lines to your /etc/apt/sources.list:

deb http://apt.llvm.org/buster/ llvm-toolchain-buster main
deb-src http://apt.llvm.org/buster/ llvm-toolchain-buster main
deb http://apt.llvm.org/buster/ llvm-toolchain-buster-10 main
deb-src http://apt.llvm.org/buster/ llvm-toolchain-buster-10 main
deb http://apt.llvm.org/buster/ llvm-toolchain-buster-11 main
deb-src http://apt.llvm.org/buster/ llvm-toolchain-buster-11 main

*Add signatures for these repos (otherwise apt-get update will complain in the next step)

wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -

*Run apt-get update to add these new repos to the apt-get:

sudo apt-get update

*Install clang-11:

sudo apt-get install clang-11

*Make sure now "clang-11" is used by the compiler and not the older "clang":

export CMAKE_C_COMPILER=clang-11
export CMAKE_CXX_COMPILER=clang++-11

*Compile your project.

*Enjoy!

For documentation: https://apt.llvm.org/

A: I would suggest installing the latest stable 15

*

*Add the following lines to your /etc/apt/sources.list:

deb http://apt.llvm.org/bullseye/ llvm-toolchain-bullseye main
deb-src http://apt.llvm.org/bullseye/ llvm-toolchain-bullseye main
# 15
deb http://apt.llvm.org/bullseye/ llvm-toolchain-bullseye-15 main
deb-src http://apt.llvm.org/bullseye/ llvm-toolchain-bullseye-15 main

*Add signatures for these repos (otherwise apt-get update will complain in the next step)

wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -

*Run apt-get update to add these new repos to the apt-get:

 sudo apt update && sudo apt upgrade

*To install all key packages

sudo apt-get install libllvm-15-ocaml-dev libllvm15 llvm-15 llvm-15-dev llvm-15-doc llvm-15-examples llvm-15-runtime

*Install clang-15

 sudo apt-get install clang-15 lldb-15 lld-15

*Make sure now "clang-15" is used by the compiler and not the older "clang" and done just compile your project

export CMAKE_C_COMPILER=clang-15

export CMAKE_CXX_COMPILER=clang++-15

Doc https://apt.llvm.org/


text:
Q: How do I scale a div and then reverse the transform all in the same click using css and jQuery? I am working on a memory game. When the player matches two cards, after clicking on the 2nd card of the matched pair, both cards animate by scaling up 130% while completing a full 360% rotation in 500 milliseconds. What I'd like the animation to do at that point is pause for 1 second and then reverse itself (scale down to 100% and rotate -360% in another 500 milliseconds. I can't seem to find the right callback function or use of keyframes or other alternative to create a smooth transform effect through the whole process.
Because of cross-browser compatibility issues, I've been asked to use jQuery instead of relying solely on css. I've included my code for the project below. Right now, I have minimal html, some css and some javascript. I also use jQuery. Please, if anyone can point me in the right direction, I would be sincerely grateful. I'm still new to all code languages so simple explanations are preferred.
Thanks in advance!
<!DOCTYPE html>

ADE Memory Game

Click or touch the squares to match the cards.

A: *

*Use .animate() to animate your CSS changes.

*

*Use the duration argument to make the animation take 500ms each time.

*Use the complete argument to animate to reverse the animation after it's completed.
So like
$(tile_1).animate({
  transform: "scale(1.3) rotate(360deg)"
}, 500, function() {
  $(this).animate({
    transform: "scale(1.0) rotate(0deg)"
  }, 500);
});

for tile_1.  Use similar code (or better, a function that takes the tile to animate as a parameter) for tile_2 or any other tiles you want to animate.


text:
Q: Getting arrayindexoutofbounds when reading from file I have this small problem of mine, where I would be getting arrayindexoutofboundsexception when trying to read from file. I don't know of a better or more detailed way of explaining it, so I will paste the code and the error below.
This is all in the mainmethod of my program.
    File fila;
    String[] innlesningsarray=new String[500];

    try{
        Scanner innFil=new Scanner(new File("/uio/hume/student-u77/makrist/Downloads/akronymer.txt"));

        while(innFil.hasNext()){
        for(int i=0; i<500; i++){

        // String innLest=br.nextLine();
            innlesningsarray=innFil.nextLine().split("\t");
            System.out.println(innlesningsarray[i]);
            System.out.println(innFil.nextLine());
        }
        System.out.println("test");
        }
        System.out.println("Test2");

    } catch(Exception e){
        System.out.print(e);
    }
    }
}

After this part I have an object of Acronyms and stuff, but no errors there...
The error:

AA        Auto Answer
AAB  All-to-All Broadcast
java.lang.ArrayIndexOutOfBoundsException: 1

A: You do nextLine() twice in the loop. This will read 2 lines in your file.
while(innFil.hasNext()) can return true if you have 1 line left. Next thing you do is reading 2 lines in that while-loop. Since there is only 1 line left, you'll get your exception.
You have it placed in a for-loop as well. That means you do 500*2 times the readLine() method, while you only check for 1 line.
Try the following:
try{
    Scanner innFil=new Scanner(new File("/uio/hume/student-u77/makrist/Downloads/akronymer.txt"));

    while(innFil.hasNext()){
        for(int i=0; i<500; i++){
            String theReadLine = innFil.nextLine();
            innlesningsarray=theReadLine.split("\t");
            System.out.println(innlesningsarray[i]);
            System.out.println(theReadLine);
        }
        System.out.println("test");
    }
    System.out.println("Test2");

    } catch(Exception e){
        System.out.print(e.printStackTrace);
    }
}

This solves a possible error with the nextLine() method. You should be sure innlesningsarray actually has 500 or more entries, else you will receive your exception. Make sure that your akronymer.txt file has the string \t 500 or more times in it!
I also changed your catch-code. Instead of print(e) you should write e.printStackTrace(). This will print a lot of useful information about the exception. Thanks to Roland Illig for that comment!


text:
Q: Atomically download a CVS file in .NET core I am making a dynamic CVS report file in my controller in the format of StringBuilder. I have tried this code to return the file:
public async Task GetCvsAsync(....)
{
....
//making the file
        using (MemoryStream stream = new MemoryStream())
        {
            StreamWriter objstreamwriter = new StreamWriter(stream);
            objstreamwriter.Write(res.ToString());
            objstreamwriter.Flush();
            objstreamwriter.Close();
            return File(stream.ToArray(), "application/octet-stream", "test.csv");
        }

    }

it makes the correct result but in the console response header (nothing happens in the front) like this:

if I right-click on the console and click open in a new tab, it will start to download the file. I have tried this way as well:
var f = File(Encoding.UTF8.GetBytes(res.ToString()), "text/csv", "authors.csv");
return f;

res is in the type of StringBuilder.
I want to download automatically begins after the file is ready, I have no idea what should I do.
note:
this action called by a href tag onClick event on my razor page:
function cvs(meID, oID, tID) {
        $.get("/Dashboard/GetCVS?meID=" + meID
            + "&oID=" + oID+ "&tID=" + tID);
    }

A: I couldn't solve my problem with jquery I just change my code to direct calling my action instead of ajax call and my problem solved!


text:
Q: How to fix editable index problem in angular I have two ngFor in a div and in same table, one ngFor array holds some existing data while the second one holds new data that I want to edit before pushing the data to the first array that olds thedefault/existing data.
My problem is, when I click edit button on a row in the second array, the same index/row of the array one also get aktivated for editing. I want the indexes of each array to be independent, that is, when I clicked the edit button on index of either of the array only the index should be activated, how to I fix that? below is my code:
html

//.....

         // olds existing data, in which the data in the "newData" array with later land

      <button type="button" class="btn btn-danger"
          (click)=remove(i) [disabled]="disabled">

          </button>
      {{list.type}}<input type="test" *ngIf="enableEdit && enableEditIndex == i">
      <button type="button"
        *ngIf="i != enableEditIndex || enableEditIndex == null"
        (click)="enableEditMethod($event, i )">

      </button>

               // here is the second tr

      <button type="button" class="btn btn-danger"
          (click)=remove(i)>

          </button>
      {{list1.type}}<input type="test" *ngIf="enableEdit && enableEditIndex == i">
      <button type="button"
        *ngIf="i != enableEditIndex || enableEditIndex == null"
        (click)="enableEditMethod($event, i )">

      </button>

// this is array from which data is push to "newData" array

//.....

      <button type="button" class="btn btn-secondary"
          (click)=addObj(i)>

          </button>
      {{allData.type}}

Why I am have the two array is that "existingData" has cancel button disabled while "newData" is not.
ts
.....//some declarations

enableEditMethod( e, i ) {
   this.enableEdit = true;
   this.enableEditIndex = i;
}

I am using the same function on both button. In case of questions, please ask!

A: I'm pretty sure that's because you haven't initialized a second index variable for the second *ngFor.
Doing that would fix the issue:

//.....

      <button type="button" class="btn btn-danger" (click)=remove(i) [disabled]="disabled">

          </button>
      {{list.type}}<input type="test" *ngIf="enableEdit && enableEditIndex == i">
      <button type="button" *ngIf="i != enableEditIndex || enableEditIndex == null" (click)="enableEditMethod($event, i )">

      </button>

      <button type="button" class="btn btn-danger" (click)=remove(newIndex)>

          </button>
      {{list1.type}}<input type="test" *ngIf="enableEdit && enableEditIndex == newIndex">
      <button type="button" *ngIf="newIndex != enableEditIndex || enableEditIndex == null" (click)="enableEditMethod($event, newIndex )">

      </button>

// this is array from which data is push to "newData" array

//.....

      <button type="button" class="btn btn-secondary" (click)=addObj(newIndex)>

          </button>
      {{allData.type}}


text:
Q: dojo dijit menubar submenu hover problems I'm using dojo menubar and I want the submenus to pop-up onmouseover and disappear onmouseout.
Right now the hiding and showing behavior is based on a click.
Is there anyway to get it to hover on mouseover, stop hovering on mouseout?
I found that a javascript click() on the menu item will start the hover behavior, and another javascript click will end it, so I could add an onmouseover and onmouseout listener to each menubar item as a workaround, but maybe someone knows of an easier way to get the same behavior by changing some dijit settings?
The documentation says this but I'm not sure how to use it.

The Menu/MenuBar domNode has a dijitMenuPassive/dijitMenuActive class so that CSS rules for hover can be customized based on whether or not the menu has focus.

I tried to add class="dijitMenuActive" but didn't notice any changes.


text:
Q: Need to update the input value on keyup I tried with this
HTML
<input type="hidden" class="change-txt">
<div class="dtmp">
    <input type="text" value="Rachael Senders">
</div>

JS
$(function(){
   var $input =  $('.dtmp input');
   $input.on('click', function(e){
        e.preventDefault();
        $('.change-txt').val($input.val());
    });
   $input.on('keyup', function(){
        $('.change-txt').val($input.val());
        //need to update the input value here
   });
});

I need to update the input value according to the value of hidden input.
Any help will be highly appreciated. Thanks

A: Try only this code:
$(function(){
  var $input = $('.dtmp input');
  $input.on('keyup', function(){
     $('.change-txt').val($input.val());
  });
});

A: $('.dtmp input').on('keyup', function(e){
                $('.change-txt').val($(this).val());
            });

A: Each time you change the value of your hidden input element you need to trigger the "change" event like this:
$('.change-txt').val('...').trigger('change');

And then use:
$('.change-txt').change(function(e) {
  $('.dtmp input').val($(this).val());
  // do other stuff if necessary ...
});

OTHERWISE
You can set an interval for checking the value of the hidden input and updating the other.
setInterval(function(){
   if ($('.change-txt').val()!=$('.dtmp input').val()){
       $('.dtmp input').val($('.change-txt').val());
   }
}, 100);


text:
Q: Filter a given List based on external List in Linq in one query I've a list :
List<Student> lstStudents = GetConditionalStudents();

I've another list:
List<School> allSchools  = dbContext.Schools.ToList();

Every School has list of Students
public class School
{
   ///other properties
   public List<Student> {get;set;}
}

I'am forced to do this:
List<School> schools = from p in allSchools
                       where p.LocationId==this.LocationId
                       where p.Students.Any(d=>lstStudents.Contains(d))
                       select p;

but it doesn't work: gives error
unable to create a constant value for .. only primitive types

Edit
I can make it work by doing this:
List<int> integers = lstStudents.Select(s=>s.Id).ToList();
List<School> schools = from p in allSchools
                       where p.LocationId == this.LocationId
                       where p.Students.Any(d=>integers.Contains(d.Id))
                       select p;

but I don't want to use it, coz I hav situations where I have to compare more than 2 Ids, so that implies, I will have to make more than 2 separate primitive datatype List and use them in the query,which I don't want.
how to directly use the external list in the linq query.??
I cannot use this:
allSchools.Where(s=>s.LocationId==this.LocationId ||
lstStudents.Contains(s)).ToList();

Please help...
I went through this and this..but they are no help to me..

A: The problem is that the Entity Framework is unable to translate your list of students into a valid SQL statement - obviously the database server knows nothing about you Student class and therefore the Entity Framework can not translate the LINQ query into something the database server could understand. There are three solutions.

*

*Get rid of your method GetConditionalStudents() and directly include the query building this list in the main query if possible.

*Fetch both lists - lstStudents and allSchools - into memory by calling ToList() on the respective queries and process both lists using LINQ to Objects.

*Use object IDs instead of the objects because the Entity Framework is able to translate lists of integers, strings and so on into a IN statement.
To me it looks like you are already doing option two but obviously you are not because the code fails but I am unable to pin the exact flaw.

A: Try:
var schools = from p in allSchools
              where (p.LocationId==this.LocationId && p.Students.Any(s => lstStudents.Contains(s)))
              select p;


text:
Q: Lottery Game in java I am having issues writing a java program for a lottery game the program that i have written works but i cant get the sum part to work right. i need it to add each and every single digit for example if the result prints 234,456,345 I need to add 2+3+4+4+5+6+3+4+5 and then return the sum but what i get is 234+456+345 any help will be good.
import java.util.Scanner;
public class LotteryDraw {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int game;
        int times;
        int randNum;
        int lotNum;
        int sum = 0;
        System.out.println("Which lottery game do you want to play!");
        System.out.println("Enter 3 for Pick 3");
        System.out.println("Enter 4 for Pick 4");
        System.out.println("Enter 5 for Pick 5");
        game = input.nextInt();

        System.out.print("How many games would you like to play? ");
        times = input.nextInt();
        System.out.println("Thank you! The numbers selected were: ");
        for(int i = 0; i < times; i++) {
            lotNum = 0;
            for(int j = 0; j < game; j++)
            {
                randNum = (new java.util.Random()).nextInt(10);
                lotNum = (lotNum * 10) + randNum;
                System.out.print(randNum);
            }
            System.out.println();
            sum += lotNum;
        }
        System.out.println("Sum of the numbers of all games: " + sum);
    }
}

A: UNTESTED CODE:
Try this
import java.util.Scanner;
public class LotteryDraw {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int game;
        int times;
        int randNum;
        int lotNum;
        int sum = 0;
        System.out.println("Which lottery game do you want to play!");
        System.out.println("Enter 3 for Pick 3");
        System.out.println("Enter 4 for Pick 4");
        System.out.println("Enter 5 for Pick 5");
        game = input.nextInt();

        System.out.print("How many games would you like to play? ");
        times = input.nextInt();
        System.out.println("Thank you! The numbers selected were: ");
        for(int i = 0; i < times; i++) {
            lotNum = 0;
            for(int j = 0; j < game; j++)
            {
                randNum = (new java.util.Random()).nextInt(10);
                lotNum = (lotNum * 10) + randNum;
                System.out.print(randNum);
                sum+=randNum;
            }
            System.out.println();
        }
        System.out.println("Sum of the numbers of all games: " + sum);
    }
}


text:
Q: Makefile generating multiple instances of a library What is the best way to generate multiple instances of library files.
For instance, considering the following example:
Lib.h (Inst1)        Lib.h (Inst2)
    ¦                     ¦
    ----------------------
              ¦
            Lib.c
              ¦
      ----------------
      ¦              ¦
   FolderA       FolderB
   (Lib.a)       (Lib.a)     -> Here are 2 different instances of the library

NB: Both versions of Lib.a will have the same name but different contents.
This could happen for instance when includes contain different #define values:
#define VAR1 0 -> Defined in Lib.h (Inst1)
#define VAR1 5 -> Defined in Lib.h (Inst2)

=> several versions of Lib.a
I thought about having a main makefile containing all the possible combination needed, but that will quickly become unmanageable.
Can this be done in a structured way? What is the typical approach to do something like that?

A: Assuming that you want to generate lib.a based on the contents of an existing lib.h (there's one copy of the file, but it can have different contents...), you could do something like:
target_dir = $(shell some commands to figure out desired target dir from lib.h)

all: ${target_dir}/lib.a

%/lib.a: common/lib.h
     @echo doing some commands to build lib.a

Which would build lib.a in the correct directory based on the contents of the lib.h.
If, on the other hand, you have multiple copies of lib.h, then you want something to the effect of:
%/lib.a: %/lib.h
     @echo doing some commands to build lib.a from $^

Finally, if the directory names don't line up, you could map it using a bunch of rules:
FolderA/lib.a: Inst1/lib.h
FolderB/lib.a: Inst2/lib.h

%/lib.a:
    @echo doing some commands to build lib.a from $^

If you want to generate multiple versions of lib.h based on some array or something like that, then that's another story...

A: Considering your comment, maybe you can do like this:

*

*Define the rules for compiling libVar1Eq0.a with VAR1 == 0

*Define the rules for compiling libVar1Eq5.a with VAR1 == 5

*Define the rule for target FolderA/lib.a as ln -s libVar1Eq0.a FolderA/lib.a

*Define the rule for target FolderB/lib.a as ln -s libVar1Eq5.a FolderB/lib.a
If you have a lot of different lib.h, it can easily be automated.

A: You can pass variable at make invocation.
Imagine your makefile is:
all: $(DIR)/lib.so

$(DIR)/lib.so: lib.c
    $(CC) -shared -I$(DIR) -o $@ $<

You can call it with: make DIR=Inst1
So you can generate all your library in one call:
#! /bin/sh
for I in Inst*; do
    make DIR=$I
done


text:
Q: Getting database connection fail issue, after site migration to php 5.6 and mysql 5.6 Guys getting a database error, after website migration.
<?php

final class MySQL {
    private $connection;
public function __construct($hostname, $username, $password, $database) {
    if (!$this->connection = mysql_connect($hostname, $username, $password)) {
        exit('Error: Could not make a database connection using ' . $username . '@' . $hostname);
    }

if (!mysql_select_db($database, $this->connection)) {
        exit('Error: Could not connect to database ' . $database);
    }

    mysql_query("SET NAMES 'utf8'", $this->connection);
    mysql_query("SET CHARACTER SET utf8", $this->connection);
    mysql_query("SET CHARACTER_SET_CONNECTION=utf8", $this->connection);
    mysql_query("SET SQL_MODE = ''", $this->connection);
}

public function query($sql) {
    $resource = mysql_query($sql, $this->connection);


text:
Q: Merging 2 Dataframes does not give me the expected number of rows I'm trying to merge 2 DataFrames following Pandas Merging 101 .
To train, I tried on 2 smalls Dataframe:
df1
    A   B    C
0   4   64   51
1   7   1    6
2   47  21   56
3   96  16   4
4   2   6    4

df2
    A    B    C    D
0   8    6    8    7
1   7    1    14   5
2   8    8    8    8
3   96   16   32   4

I want to check all values of columns A and B of df1, if they correspond to columns A and B of df2, then I create a new column D in dataFrame df2 that correspond to the value of D. If the values does not correspond to any rows in df2 then I store Nan.
I used this:
df3= df1.merge(df2[['A', 'B','D']], on= ['A', 'B'], how= 'left')

And this give me the expected output
OUTPUT:
df3

   A   B   C   D
0  4   64  51  NaN
1  7   1   6   5.0
2  47  21  56  NaN
3  96  16  4   4.0
4  2   6   4   NaN

Now I tried the same procedure but on real world datasets:
df1.shape  -> (1000, 92)

df2.shape  -> (1744, 22)

df3= df1.merge(df2[['NUM_WB', 'WB','TENSION', 'COURANT']], on= ['NUM_WB', 'WB','TENSION'], how= 'left')

df3.shape  -> (72162, 93)

I expected df3 to have the same number of rows as df1. How to explain this?


text:
Q: Improvements to "review" for a tablet device I review Stack Overflow questions on my tablet. For the most part, the new interface works great, but I have a few suggestions which I think may improve usability when working with a tablet:

*

*The different options under "close" have links in them. It's easy to click these instead of the text around it which navigates away from the review page. Maybe these links could be moved out of the radio button text and e.g. to a list under the options.

*On a device like a tablet, it's easy to click the wrong button (I mean the "close", "do not close" etc. buttons). It would be great if the page after e.g. clicking the "do not close" button (which doesn't ask for confirmation) would show an "undo" option. Currently there is no way (I can easily find) to undo a review action.


text:
Q: Create Ebay Connector using Syncari SDk i'm trying to create a connector inside Syncari SDK to get Orders from Ebay using this SDK
https://pypi.org/project/syncari-sdk/
in ebay am using Production environment using Auth'n'Auth

and with this Token am using:
 1. Trading API
 2.API CALL : GetOrders
 3.API VERSION : 967

HTTP headers
X-EBAY-API-SITEID:0
X-EBAY-API-COMPATIBILITY-LEVEL:967
X-EBAY-API-CALL-NAME:GetOrders

Request Body
   <?xml version="1.0" encoding="utf-8"?>
<GetOrdersRequest xmlns="urn:ebay:apis:eBLBaseComponents">
  <RequesterCredentials>
    <eBayAuthToken></eBayAuthToken>
  </RequesterCredentials>
    <ErrorLanguage>en_US</ErrorLanguage>
    <WarningLevel>High</WarningLevel>
  <OrderIDArray>
    <!-- Enter one or more of the seller's Order IDs in separate OrderID fields. Only legacy Order IDs are supported in GetOrders and not the ExtendedOrderIDs that are supported in eBay REST APIs calls like the Fulfillment API. The legacy Order ID values are actually the concatenation of ItemID and TransactionID, with a hyphen in between these two values. In legacy API calls, the OrderLineItemID and OrderID values are the same for single line item orders. Note that the TransactionID for an auction listing is always '0', which is demonstrated below -->
    <OrderID>XXXXXXXXXXXX-XXXXXXXXXXXXX</OrderID>
    <OrderID>XXXXXXXXXXXX-0</OrderID>
  </OrderIDArray>
  <OrderRole>Seller</OrderRole>
</GetOrdersRequest>

Inside SDK we have a method called : synapse_Info() to connect to ebay using token
Read the document here : https://support.syncari.com/hc/en-us/articles/4580013102868-Custom-Synapse-SDK-Documentation
i want to know how to add Headers, Toekn , Body to get Orders From Ebay API and add all of this here
def synapse_info(self):
    return SynapseInfo(
    name='lysiSynapse', category='other',
    metadata=UIMetadata(displayName='Lysi Synapse'),
    supportedAuthTypes=[AuthMetadata(authType=AuthType.BASIC_TOKEN, label='API Key', fields=[AuthField(name='token', label='API Key', dataType=DataType.PASSWORD)])],
    configuredFields=[AuthField(name='endpoint', label='Endpoint URL', dataType=DataType.STRING)])

we can see response usning Method : Test() in the SDK
def test(self, connection: Connection):
 self.client.get("/users",headers=self.__auth_headers())
 if not connection.metaConfig:
     connection.metaConfig={}
 return connection

A: The synapse_info info method is meant to be used to declare the Synapse's UI elements and authentication options and not to add headers and tokens directly. The method returns a SynapseInfo object that defines fields in the Syncari's UI. It is possible later in the framework to access those defined fields from the connection object, which persist through the framework.
We recommend first is to define the Syncari rest client in the Synapse class:
def __init__(self, request: Request) -> None:
    super().__init__(request)
    self.client = SyncariRestClient(self.connection.authConfig.endpoint, self.connection.authConfig)

This way it's possible to use the Syncari client that will have access to the endpoint and authentication data that the user inputs in the UI of Syncari.
Since Ebay's API uses XML queries we'd recommend creating helper methods to assist with constructing the queries. For this particular example:
def xmlQueryConstructorGetOrderByID(eBayAuthToken, Orders):
    return f"<?xml version=\"1.0\" encoding=\"utf-8\"?><GetOrderRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\"><RequesterCredentials><eBayAuthToken>{eBayAuthToken}</eBayAuthToken></RequesterCredentials><ErrorLanguage>en_US</ErrorLanguage><WarningLevel>High</WarningLevel><OrderIDArray>{Orders}</OrderIDArray><OrderRole>Seller</OrderRole></GetOrderRequest>""

Additionally, we recommend to hardcode the required headers in a constant:
HEADERS = {"Content-Type":"application/xml", "x-ebay-api-call-name": "GetOrders", "x-ebay-api-compatibility-level" : "967", "X-EBAY-API-SITEID" : "0"}

We can now use all of this to make a call in the test method, which is used to test the credentials a user imputed in the UI of Syncari application:
def test(self, connection: Connection):
    self.client.get("", headers=HEADERS, data=self.client.post("",headers=HEADERS,
    data=xmlQueryConstructorGetOrderByID(self.connection.authConfig.token,"<OrderID>XXXXXXXXXXXX-XXXXXXXXXXXXX</OrderID>")))
    return connection

In an actual use case the  would be replaced with an actual existing order's ID and the authentication data is accessed from the connection object.
We also recommend using a python library like xmltodict to convert the received XML data into JSON, so it is easier to pass it to Syncari.
We hope this answers the question but if you need any further assistance please reach out to our support at developers@syncari.com.


text:
Q: Flutter TextButton splashColor property I was using FlatButton and passed the properties
FlatButton(
      splashColor: Colors.transparent,
      highlightColor: Colors.transparent,
      child: ...,
)

The documentation says that FlatButton will become obsolete, and to use TextButton instead, but it does not take splashColor or highlightColor properties
TextButton(
    splashColor: Colors.transparent,
    highlightColor: Colors.transparent,
    child: ...,
)

does not work. it is not allowed
I also tried like this
TextButton(
  style: ButtonStyle(
    splashColor: Colors.transparent,
    highlightColor: Colors.transparent,
  ),
  child: ...,
)

How can I do this? Thank you

A: Colors.transparent will deny any effects, simply it is transparent so it will appear as nothing happens... in ButtonStyle, it goes something like this with colors.
ButtonStyle(
   overlayColor: MaterialStateColor.resolveWith((states) => Colors.red),
),

A: For Flutter over 3.1.0, where primary is deprecated, I change the spash color using:
style: TextButton.styleFrom(
   backgroundColor: Colors.green,  // Button color
   foregroundColor: Colors.lime,   // Splash color
),
child:Text(...)

In case it helps!

A: For someone who is not familiar to MaterialStateProperty setting in TextButton (use resolveWith to customize the button effect):
TextButton(
  style: ButtonStyle(
    overlayColor: MaterialStateColor.resolveWith((states) {
      if(states.contains(MaterialState.hover){
        return Colors.transparent; // <- hover color
      }else if(states.contains(MaterialState.pressed){
        return Colors.transparent; // <- ripple color
      }
      ...
    },
    backgroundColor: MaterialStateColor.resolveWith((states) {
      if(states.contains(MaterialState.pressed){
        return Colors.transparent; // <- clicked color
      }
      ...
    }),
  )
)

A: Using theme, it will be applied to all TextButtons in your project
Put this inside themeData:
textButtonTheme: TextButtonThemeData(
    style: ButtonStyle(
      splashFactory: NoSplash.splashFactory,
      overlayColor: MaterialStateProperty.all(Colors.transparent),
    ),
  ),

A: As Flat button is depricated, you have to use TextButton instead of it, but in text button there is no direct property to change splash color. So if you want to change splash color to transparent you can do it like this.
TextButton(
  style: ButtonStyle(
    overlayColor: MaterialStateProperty.all(Colors.transparent),
  ),
)

A: You can also use like this
 TextButton( onPressed: () {},
                style: TextButton.styleFrom(
                              backgroundColor: AppColors.primaryColor,
                              primary: Colors.black12),//ripple color
                          child:Text(AppLocalizations.of(context).startAdventure,
                          ));

You can Set primary color to create ripple color

A: You can define your desired color somewhere like inside constants.dart like so:
const kPrimaryColor = Color(0xfffbba3d);

Then you can use ButtonStyle with opacity/transparency using .withOpacity() like so:
TextButton(
     style: ButtonStyle(
          overlayColor: MaterialStateColor.resolveWith(
            (states) => kPrimaryColor.withOpacity(0.3))),
                    onPressed: () => {},
                    child:
                        Text(
                          'My Button',
                          style: TextStyle(
                              fontSize: 16,
                              color: kPrimaryColor,
                              fontWeight: FontWeight.w400),
                        ),
                  ),

A: There is an alternative to using resolveWith and providing an anonymous function like this:
ButtonStyle(
   overlayColor: MaterialStateColor.resolveWith((states) => Colors.red),
)

Instead, you can just use the named constructor all of MaterialStateProperty, which is syntactic sugar for the same effect:
ButtonStyle(
   overlayColor: MaterialStateProperty.all(Colors.red)
)

This is cleaner and has a better readability.


text:
Q: Twitter bot deployed with Heroku shuts down I'm quite new to the Heroku platform, I don't understand why my Twitter bot deployed gets shut down after some time. I don't know if it's the dyno or something else.
bot.py
import time
import json
import requests
import tweepy
from os import environ

consumer_key = environ['api_key'] #API key
consumer_secret = environ['api_key_secret'] #API key scret
key = environ['access_token'] #Access token
secret = environ['access_token_secret'] #Access token secret

auth = tweepy.OAuthHandler(consumer_key, consumer_secret) # Authentication
auth.set_access_token(key, secret) # Grant access to API

api = tweepy.API(auth) # Connect to API

def get_quote():
    url = 'https://programming-quotes-api.herokuapp.com/Quotes/random'
    response = requests.get(url)
    data = json.loads(response.text)
    data = data['en']+'\n--'+data['author']
    return data

def tweet_quote():
    interval = 60 * 20 # 20 minutes

    while True:
        quote = get_quote()
        api.update_status(quote)
        time.sleep(interval)

if __name__ == "__main__":
    tweet_quote()

Procfile
web: python server.py
worker: python bot.py

dyno info here

A: Your Procfile shows that you have a web process and a worker process.
Assuming you are using free dynos, this behaviour is expected (bold added):

If an app has a free web dyno, and that dyno receives no web traffic in a 30-minute period, it will sleep. In addition to the web dyno sleeping, the worker dyno (if present) will also sleep.

Free worker dynos on apps that do not have a web dyno do not sleep, but of course they'll consume roughly 720 free dyno hours every month (24 hours per day × 30 days in the month).
You have a few options:

*

*Run your worker regularly (but not constantly) via the Heroku Scheduler

*

*E.g. maybe run it once an hour for a limited amount of time / tweets

*Upgrade to paid dynos

*Move your free worker dyno to another app that has no web dynos to prevent it from sleeping...

*

*...though that might not make a lot of sense for your application

*Keep your web dyno alive by pinging it at least once every 30 minutes...

*

*...but then you'll run out of free dyno hours roughly 20 days into each month (or sooner, if your account is not verified)


text:
Q: Locked black screen after upgrading from 14.04 to 14.10 I have just done the upgrade from 14.04 to 14.10. After restarting i get a black screen, with the cursor blanking, but i cant type anything on the screen. I am using Think-pad T400. How should i proceed?

A: You should hit Shift during boot and get to the terminal and update everything:
sudo apt-get update
sudo apt-get upgrade


text:
Q: POST - While Posting - Jquery - Not AJAX I have a typical post on my website.
It is not an ajax post. But do to the complexity, and number of var being posted, it is very slow. (Which is a problem in itself). However, for the time being, I want to create a loading window. Normally, with AJAX, I would use ajaxStart/ajaxStop and make something. Is there similar function for a standard post?

A: Can try something like this. The idea is to prevent a jQuery submit event, show a loader and after short delay to give time for loading indicator to be displayed,  trigger the native submit event
The submit process normally blocks the UI which is why the delay is added
$('#myForm').on('submit', function(e){
     e.preventDefault();//prevent jQuery event
     var form = this;
     $('#loader').show();
     setTimeout(function(){
         form.submit();// submit native method
     },10);//minimal delay to allow browser to paint
});


text:
Q: How to implement the Jacccard macro in a data step for a matching problem? I tried implementing a solution into my sas code but with no luck. I'm trying to add a jaccard distance column. to my dataset.
I keep getting errors :
variable name & is not valid
invalid value for the keep option
The idea is to solve a matching problem between two datasets and to take into consideration the typing errors.
data table_test;
    input nom1 $3. nom2 $3.;
cards;
abcade
vdenfr
azfefs
;
run;

%macro kshingling
(string
,k=5
,out=&sysmacroname.
)
;

data &out.;
   string = strip(prxchange('s#\s# #',-1,symget('string')));
   do _n_ = 1 to lengthn(string)-&k.+1;
      ngram = substr(string,_n_,&k.);
      output;
   end;
run;

%mend;

%macro jaccard
(string1
,string2
)
;

%kshingling(&string1.,k=2,out=s1)
%kshingling(&string2.,k=2,out=s2)

proc append base=s1 data=s2; run;

proc freq data=s1 noprint;
   tables string*ngram / out=s2;
run;

proc transpose data=s2 out=s1(drop=_name_ _label_);
by string notsorted;
var count;
id ngram;
run;

proc stdize data=s1 out=s2 missing=0 reponly;
var _numeric_;
run;

proc distance data=s2 method=jaccard absent=0 out=s1;
var anominal(_numeric_);
id string;
run;

data t(keep=&string1.);
set s1(firstobs=2);
run;

data _null_;
set t;
call symput('Jaccard',&string1.);
%put Distance de Jaccard = &Jaccard;
run;

%mend;

data test;
set table_test;
call symput('n1',nom1);
call symput('n2',nom2);
%jaccard(&n1,&n2);
run;

data Jacc;

Dist_Jacc=&Jaccard;
run;

data Final; merge table_test Jacc; run;

A: You are mixing DATA step and macro in ways that are incorrect.
The SYMPUT occurs at runtime and the direct macro call %jaccard is processed at compilation time that occurs before runtime.
For instance:
data test;
set table_test;
call symput('n1',nom1);
call symput('n2',nom2);
%jaccard(&n1,&n2);
run;

Running jaccard for each record in table_test should be accomplished using something like the following DATA step that computes source code and then tells the session to execute it.
data _null_;
  set table_test;
  macro_call = '%nrstr(%jaccard)' || cats('(' , n1, ',', n2, ')');
  call execute (macro_call);
run;

A: Looks to me like the OUTPUT of your macro is the dataset T.  You can use PROC APPEND to aggregate the results of multiple macro calls into a single dataset.  You can then combine that data with your input dataset of ngrams.
data _null_;
  set table_test;
  call execute(cats('%nrstr(%jaccard)(',nom1,',',nom2,');'));
  call execute('proc append base=result data=t; run;');
run;

data want;
   set table_test;
   set result;
run;

BUT you will need to make sure the generated T dataset has THE EXACT SAME STRUCTURE each time.
So change the ending steps of the macro to this single step so that the dataset T always consists of ONE observation and ONE variable and the variable is named Jaccard.  You can also use the %GLOBAL statement to make sure that the value of JACCARD macro variable is available after the macro finishes.
%if not %symexist(jaccard) %then %global jaccard;
data t ;
  set s1(keep=&string1. rename=(&string1.=Jaccard) obs=2 firstobs=2);
  call symputx('Jaccard',Jaccard);
run;
%put Distance de Jaccard = &Jaccard;


text:
Q: g++ external reference error I have issue that is reproduced on g++. VC++ doesn't meet any problems.
So I have 2 cpp files:
1.cpp:
#include <string>
#include <iostream>

extern const std::string QWERTY;

int main()
{
    std::cout << QWERTY.c_str() << std::endl;

}

2.cpp:
#include <string>
const std::string QWERTY("qwerty");

No magic, I just want place string constants into separated file. At link time ld produces an error: "undefined reference to `_QWERTY'"
The first think to wrap both declarations into "extern "C"" - didn't help. Error and non c++ _QWERTY is still there.
Thanks in advance for any suggestions

A: It looks like you are probably running into this bit of the standard:

In C, a const-qualified object at file
  scope without an explicit storage
  class specifier has external linkage.
  In C++, it has internal linkage.

Make this change to 2.cpp:
#include <string>
extern const std::string QWERTY("qwerty");

There is some more detail on what "linkage" means in this question - What is external linkage and internal linkage in C++.

A: I'd have to look it up but I think const global variables have internal linkage in C++, don't use const and it'll compile fine.
1.cpp

...
extern std::string QWERTY;
...

2.cpp
#include <string>
std::string QWERTY("qwerty");

Or you could declare/define it as a const string in a common header of course.
Adding a superfluous extern to the 2.cpp will get it to compile too, but I'm not sure that's standard or some g++ 'extra'


text:
Q: What is purpose of blank.html in js directory? In Magento CE 1.7.0.2 in js directory there is file blank.html
What is purpose of this file exactly?

A: It's used by some Magento modules like Authorizenet as a fallback page for iframes. Other uses I have't found for it yet.
The actual URL will be set with javascript most likely, the blank html page is just to give it something to initially load.


text:
Q: Java untyped generic classes, removing their functions generics types Ok Question about javas generics, iterable, and for-each loop.  The problem being that, if I declare my 'Test' class untyped,  I lose all generic information on all my functions and for-each is not likeing that at all.
Example
public class Test<T> implements Iterable<Integer>{

    public Test() {}

    public Iterator<Integer> iterator() {return null;}

    public static void main(String[] args) {
        Test t = new Test();

        //Good,
        //its returning an Iterator<object> but it automatically changes to  Iterator<Integer>
        Iterator<Integer> it = t.iterator();

        //Bad
        //incompatable types, required Integer, found Object
        for(Integer i : t){
        }
    }Untyped generic classes losing
}

When 'Test t' is untyped, the 'iterator()' function returns 'iterator' instead of a 'iterator < Integer >'.
I'm not exactly sure for the reason behind it, I know a fix for that is just use a wild card on 'Test < ? > t = new test()'.  However this is a less than ideal solution.
Is their any way to only edit the class declaration and its functions and have the for each loop work untyped?

A: You should just do the following:
public class Test implements Iterable<Integer>{

Remove the generic type all together.
Your Test class is not generic at all.  It is simply implementing a generic interface.  Declaring a generic type is not necessary.  This will also have the benefit of remove that generic warning you were getting.
@Eugene makes a good point.  If you actually wanted a generic Test type, you should declare Test as a generic iterator:
You should just do the following:
public class Test implements Iterable<Integer>{

Remove the generic type all together.
Your Test class is not generic at all.  It is simply implementing a generic interface.  Declaring a generic type is not necessary.  This will also have the benefit of remove that generic warning you were getting.
public class Test<T> implements Iterable<T>{

And then, make sure you make Test generic when you instantiate it.
Test<Integer> t = new Test<Integer>;

Then calls to for(Integer i: t) will compile.

A: You should either write this:
public class Test implements Iterable<Integer>{
  ...

or actually generify your class:
public class Test<T> implements Iterable<T> {

    public Iterator<T> iterator() {return null;}

    public static void main(String[] args) {
        Test<Integer> t = new Test<Integer>();

        Iterator<Integer> it = t.iterator();

        for(Integer i : t){
        }
    }
}


text:
Q: Python regex negative lookbehind not failing match I'm writing a regex to match phone numbers. One of the problems I've encountered is that some postcodes look like phone numbers. For example, in Brazil, postcodes look like this:
30.160-0131

So a simple regex will capture them as false positives:
In [63]: re.search(r"(?P<phone>\d+\.\d+-\d+)", "30.160-0131")
Out[63]: <_sre.SRE_Match at 0x102150990>

Luckily, such postcodes often come with a prefix which generally means "postcode", like this:
CEP 30.160-0131

So, if you see CEP in front of something that looks like a phone number, then it's not a phone number - it's a postcode. I've been trying to write a regex to capture that using negative lookbehind, but it's not working. It still matches:
In [62]: re.search(r"(?<!CEP )(\d+\.\d+-\d+)", "CEP 30.160-0131")
Out[62]: <_sre.SRE_Match at 0x102150eb8>

Why does it still match, and how can I get the negative look-behind to fail the match?

A: The expression matches because you are not doing anything to anchor the number. For example:
"CEP 11.213-132"

will match 1.213-132 since it does not immediately follow CEP. But you can force a whitespace, or start of line anchor, to be right before the first digit:
re.search(r"(?<!CEP)(?:\s+|^)(\d+\.\d+-\d+)", s)

A: You can avoid negative lookaheads if you allow the matching of those postcodes, and still extract only the phone numbers:
m = re.search(r"CEP \d+\.\d+-\d+|(\d+\.\d+-\d+)", s)

And then check if you got something in m.group(1) for the phone numbers.

Little demo with re.findall:
>>> import re
>>> s = "There is a CEP 30.160-0131 and a  30.160-0132 in that sentence, which repeats itself like there is a CEP 30.160-0131 and a  30.160-0132 in that sentence."
>>> m = re.findall(r"CEP \d+\.\d+-\d+|(\d+\.\d+-\d+)", s)
>>> print(m)
['', '30.160-0132', '', '30.160-0132']

And from there, you can filter out the empty strings.


text:
Q: Why is runat="server" required for controls in skin files? Like the title says.. why ?
I know why its required on the normal ASP.NET controls, there are numerous questions on SO about that.
But since you can only define .NET controls (no normal HTML markup) in the skin files, why is the runat="server" still required for every control in the skin file?
It has nothing to do with styles or themes.
Is there any reason why I still need ot add it to all controls in my skin files? Does anyone know what happens with it 'behind the scenes'?

A: Again, you have to understand how server side languages work.
All ASP.NET tags are transformed to browser-understandable HTML (a browser has no notion of what an <asp:button> is, for instance) by a server side pre-processor before the page is rendered. This means that all controls/modules/anything served by ASP.NET that's not just HTML needs to have these attributes.
I venture that the pre-processor was written originally to know what it needed to operate on based on the presence of that attribute. Otherwise it would have to process every tag even if it did nothing. It could've been written to just look for the  namespace, but that would require extra processing.
A skin file is a special ASP.NET concept, for tags defined within the framework. Hence, it makes sense that these tags have to have the "runat=server". MS could've written a special rule into their pre-processor such as "if it's a skin file, assume it's all ASP tags"...but such rules really don't scale. Plus they're bad documentation.
As a web developer, you should understand which of your tags are actually HTML and which are convenience tags provided by the framework. The "runat=server" attribute makes that delineation explicit.
You can add runat="server" to plain HTML tags such as <input> but generally there's little reason to and it's a bad practice.
For portability moving forward, you may want to consider moving away from skin files and leveraging CSS. Attributes are very verbose for setting styles, which makes the end rendered pages larger (taking longer to load, providing poor user experience) and un-semantic.


text:
Q: How to get the body before uploading file in multer? In my project the admins have the ability to upload MP3 files and submit parameters to it like song name.
I decided using multer middleware for handling multipart/form-data.
My problem is req.body.gender returns always undefined, because I have to use it inside the uploadSong listener. I want to upload the song when the gender is zero.
index.ejs
<form method="post" action="/acp" role="publish" enctype="multipart/form-data">
    <div class="form-group">
        <input type="file" name="song" id="song" accept="audio/mpeg">
    </div>

    <input type="checkbox" name="gender" checked data-toggle="toggle" data-on="Male" data-off="Female">
</form>

app.js
var uploadSong = upload.single('song');
app.post('/acp', isLoggedIn, function (req, res) {

    console.log(req.body.gender); // returns "undefined"

    if(req.body.gender == 0) { // returns "undefined"

        uploadSong(req, res, function (err) {
            if (err) {
                res.send('uploaded');
                return;
            }
            res.redirect('/');

        });

    }
});

A: (A) Not possible with multer.
(B) Use busboy. It uses streams to parse the form data and so you can get form elements values before the file upload and the fields are made available as events.
(C) Another solution (if you prefer using multer) is to use multer but add a header to send the value of the parameter to check before file upload. Headers are available as soon as the request reaches the server.

A: by using multer form-data parser you can parse form and access req.body before multer starts just register this app middle-ware:
import * as multer from "multer";

// parse form-data
app.use(multer().any());

A: This is my sample code, it is woking fine, if you need further explanation please let me know. hope helpful.
var Hotel = require('../models/hotel');
    var path = require('path');
    var multer = require('multer');
    var uplodedImages = [];

    var storageHotelGallery = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './uploads/hotelGallery');
      },
      filename: function (req, file, cb) {
        console.log(req.body);
        var newFileName = Date.now() + path.extname(file.originalname);
        req.newFileName = newFileName;
        cb(null, newFileName);
        uplodedImages.push(newFileName);
      }
    });
    var uploadHotelGallery = multer({ storage: storageHotelGallery}).fields([{ name: 'imgArr', maxCount: 8 }]);

    module.exports = function(router) {
        // ADD HOTEL BASIC DATA TO CREATE HOTEL OBJECT
        router.post('/createHotelStep1', function(req, res) {
            if( req.body.name == null || req.body.name == '' ) {
                res.json({ success: false, message: "Hotel name required" });
                res.end();
            }
            else if( req.body.addressline1 == null || req.body.addressline1 == '' ) {
                res.json({ success: false, message: "Address line 1 is required" });
                res.end();
            }
            else if( req.body.city == null || req.body.city == '') {
                res.json({ success: false, message: "City is required" });
                res.end();
            }
            else {
                var hotel = new Hotel();
                hotel.name = req.body.name;
                hotel.addressline1 = req.body.addressline1;
                hotel.addressline2 = req.body.addressline2;
                hotel.phone = req.body.phone;
                hotel.city = req.body.city;
                hotel.email = req.body.email;
                hotel.save(function(err) {
                    if (err) {
                        res.json({ success: false, message: "Unable to Complete Hotel Step 1" });
                    } else {
                        res.json({ success: true, message: 'Create Hotel Step 1 Complete', _id : hotel._id });
                    }
                });
            }
        });

        router.post('/createHotelGallery', function (req, res, next) {
            uplodedImages = [];
            uploadHotelGallery(req, res, function(err) {
                if(err) {
                    res.json({ success: false, message: 'Could not upload images'});
                    res.end();
                }
                else {
                    Hotel.findOne({ _id:req.body._id }).populate('users').exec(function (err, hotel) {
                    if (err) {
                        res.json({ success: false, message: 'Could not save uploaded images to database'});
                        res.end();
                    }
                    else {
                        for(var x=0; x<uplodedImages.length; x++)
                            hotel.images.push(uplodedImages[x]);
                        hotel.save();
                        res.json({ success: true, message: 'Gallery image uploaded' });
                        res.end();
                    }
                    });
                }
            });
        });

        return router;
    }

A: This is my sample code, it is woking fine
const upload = multer({
  storage,
  fileFilter(req, file, cb) {
    if(req.body.name===''){
      return cb(new Error('Invalid name'), false)
    }
    const extname = path.extname(file.originalname).toLowerCase() === '.gz'
    const mimetype = file.mimetype === 'application/x-gzip'
    if (mimetype && extname) {
      return cb(null, true)
    } else {
      return cb(new Error('Invalid mime type'), false)
    }
  },
})


text:
Q: unresolved external symbol "void __cdecl boost::tss_cleanup_implemented(void)" I was very surprised when I tried to search this error as I got only 4 results, two of which seem to be in Chinese. I am getting this error when compiling my project and boost sources alltogether. I searched the boost library and found this:
namespace boost
{
    /*
    This file is a "null" implementation of tss cleanup; it's
    purpose is to to eliminate link errors in cases
    where it is known that tss cleanup is not needed.
    */

    void tss_cleanup_implemented(void)
    {
        /*
        This function's sole purpose is to cause a link error in cases where
        automatic tss cleanup is not implemented by Boost.Threads as a
        reminder that user code is responsible for calling the necessary
        functions at the appropriate times (and for implementing an a
        tss_cleanup_implemented() function to eliminate the linker's
        missing symbol error).

        If Boost.Threads later implements automatic tss cleanup in cases
        where it currently doesn't (which is the plan), the duplicate
        symbol error will warn the user that their custom solution is no
        longer needed and can be removed.
        */
    }

}

My question is what's tss cleanup, why is it needed and how do I implement it.

A: I don't know about TSS, but to fix this linker error, you need to define
BOOST_THREAD_WIN32

and
BOOST_THREAD_BUILD_LIB

so boost/thread/src/win32/tss_pe.cpp implements the missing function (empty).
I assume there are few results on the Internet for this question, because the build scenario is rare. Most people do not build boost within their own project, but build boost with b2.


text:
Q: $A'B=I \rightarrow B'B \geq (A'A)^{-1}$ Could anyone please help me show that for general matrices it holds that $$A'B=I \rightarrow B'B \geq (A'A)^{-1}$$
Thanks.

A: We have
$$\left[\array{A'\\B'}\right]\left[\array{A &B}\right]=\left[\array{A'A & I\\I &B'B}\right]\succeq 0.$$ Thus for all $u,v$
$$u'A'Au+v'B'Bv+2u'v\geq 0.$$
With $u=-\left(A'A\right)^{-1}v$  we get
$$v'\left(A'A\right)^{-1}v+v'B'Bv-2v'\left(A'A\right)^{-1}v\geq 0\\
\iff v'\left(B'B-\left(A'A\right)^{-1}\right)v\geq 0\iff B'B\succeq\left(A'A\right)^{-1}.$$


text:
Q: Pm2 unable to access SSL cert and Key files even though I have permission to access those files When I deployed my mern app on our server it throwed me a EAccess error saying unable to access my cert and key files of ssl however then I created a group for me and my root with adequate permissions so that my node server can access those files and it did worked when im running it saying either node server.js or npm start however when I do the same with pm2 start server.js its unable to access those files,Can someone help what should I do so that pm2 can access my ssl files.

A: if(cluster.isMaster) {
console.log('Master has been started');
cluster.fork();
cluster.fork();} else {
console.log(`Worker process started ${process.pid}`)}

Use this code. Most of the time pm2 problem.


text:
Q: MySQL wampserver database date format
how do i change the format in my database like this format 04-Oct-2016?

A: You can save the date into the table as DATETIME format and while retrieving back use the below query to format in a right way
SELECT DATE_FORMAT(datetime, '%d/%b/%Y') datetime FROM table

or after you get the actual value you can convert to the format like
$php_timestamp_date = date("d F Y", $php_timestamp);

or
$php_timestamp_date = date("d F Y H:i:s", $php_timestamp);


text:
Q: How to make a proper mysqli extension class with prepared statements? I am trying to extend the mysqli class to make a helper class that will abstract away some of the complexities. One of the main things I want to accomplish is to make use of prepared statements.
I don't really know where to start, or how to handle input and output properly in one class. Another problem is that I am unable to output data as an array while using prepared statements.
I could really use a simple example to point me in the right direction.

A: Check out the implementation of Zend_Db, and in particular, Zend_Db_Select. In fact, you might just opt to use that instead of developing your own. Examples:
 //connect to a database using the mysqli adapter
 //for list of other supported adapters see
 //http://framework.zend.com/manual/en/zend.db.html#zend.db.adapter.adapter-notes
$parameters = array(
                    'host'     => 'xx.xxx.xxx.xxx',
                    'username' => 'test',
                    'password' => 'test',
                    'dbname'   => 'test'
                   );
try {
    $db = Zend_Db::factory('mysqli', $parameters);
    $db->getConnection();
} catch (Zend_Db_Adapter_Exception $e) {
    echo $e->getMessage();
    die('Could not connect to database.');
} catch (Zend_Exception $e) {
    echo $e->getMessage();
    die('Could not connect to database.');
}

//a prepared statement
$sql = 'SELECT * FROM blah WHERE id = ?';
$result = $db->fetchAll($sql, 2);

//example using Zend_Db_Select
$select = $db->select()
             ->from('blah')
             ->where('id = ?',5);
print_r($select->__toString());
$result = $db->fetchAll($select);

//inserting a record
$row = array('name' => 'foo',
             'created' => time()
            );
$db->insert('blah',$row);
$lastInsertId = $db->lastInsertId();

//updating a row
$data = array(
    'name'      => 'bar',
    'updated'   => time()
);

$rowsAffected = $db->update('blah', $data, 'id = 2');

A: Assuming you're actually wanting to write your own version (as opposed to utilizing one of the existing libraries other answers have suggested - and those are good options, too)...
Here are a couple of functions which you may find it useful to examine. The first allows you to bind the results of a query to an associative array, and the second allows you to pass in two arrays, one an ordered array of keys and the other an associative array of data for those keys and have that data bound into a prepared statement:
function stmt_bind_assoc (&$stmt, &$out) {
    $data = mysqli_stmt_result_metadata($stmt);
    $fields = array();
    $out = array();

    $fields[0] = $stmt;
    $count = 1;

    while($field = mysqli_fetch_field($data)) {
        $fields[$count] = &$out[$field->name];
        $count++;
    }
    call_user_func_array(mysqli_stmt_bind_result, $fields);
}

function stmt_bind_params($stmt, $fields, $data) {
    // Dynamically build up the arguments for bind_param
    $paramstr = '';
    $params = array();
    foreach($fields as $key)
    {
        if(is_float($data[$key]))
            $paramstr .= 'd';
        elseif(is_int($data[$key]))
            $paramstr .= 'i';
        else
            $paramstr .= 's';
        $params[] = $data[$key];
    }
    array_unshift($params, $stmt, $paramstr);
    // and then call bind_param with the proper arguments
    call_user_func_array('mysqli_stmt_bind_param', $params);
}


text:
Q: Rsync errors on windows with DeltaCopy Previously I got this working on my workstation, but since I formatted it, rsync stopped to work.
I already reinstalled git and deltacopy a couple of times.
Also had registered rsync as a service on windows.
Every time I ran the command, I got these errors.
If I type a wrong password, I get access denied, so the connection is ok.
C:\\> rsync -v -rlt -z --chmod=a=rw,Da+x --delete
      "/cygdrive/C/P21 Sistemas/web/apache/local.sdt21/sdt21/"
      "root@sdt21.com.br:/home/sdt21/homologacao/www/sdt21/"

root@sdt21.com.br's password: *********

dup() in/out/err failed
rsync: read error: Connection reset by peer (104)
rsync error: error in rsync protocol data stream (code 12) at
      /home/lapo/packaging/rsync-3.0.4-1/src/rsync-3.0.4/io.c(791)  [sender=3.0.4]**

A: The problem is with the ".
The quote is a known issue on Windows.
In order to override the problem install cygwin & rsync:
See: Using rsync and cygwin to Sync Files from a Linux Server to a Windows Notebook PC
And then write your command in a shell script and execute it.


text:
Q: SQL SERVER 2008 - Returning a portion of text using SUBSTRING AND CHARINDEX. Need to return all text UNTIL a specific char I have a column called 'response' that contains lots of data about a person.
I'd like to only return the info after a specific string
But, using the method below I sometimes (when people have <100 IQ) get the | that comes directly after the required number..
I'd like any characters after the'PersonIQ=' but only before the pipe.
I'm not sure of the best way to achieve this.
Query speed is a concern and my idea of nested CASE is likely not the best solution.
Any advice appreciated. Thanks
substring(response,(charindex('PersonIQ=',response)+9),3)

A: Assuming there's always a pipe, you could do this:
substring(stuff(reponse,1,charindex('PersonIQ=',reponse)-1,''),1,charindex('|',stuff(reponse,1,charindex('PersonIQ=',reponse)-1,''))-1)

Or, you could convert your string to xml and reference PersonIQ directly, e.g.:
--assuming your string looks something like this..
declare @s varchar(max) = 'asdaf=xxx|PersonIQ=100|xxx=yyy'

select convert(xml, '<x ' + replace(replace(@s, '=', '='''), '|', ''' ') + '''/>').value('(/x/@PersonIQ)[1]','int')

A: This is my suggestion:
declare @s varchar(200) = 'aaa=bbb|cc=d|PersonIQ=99|e=f|1=2'
declare @iq varchar(10) = 'PersonIQ='
declare @pipe varchar(1) = '|'

select substring(@s,
        charindex(@iq, @s) + len(@iq),
        charindex(@pipe, @s, charindex(@iq, @s)) - (charindex(@iq, @s) + len(@iq))
        )

Instead of the 3 in your formula you should calculate the space between @iq and @pipe with this last part of the formula charindex(@pipe, @s, charindex(@iq, @s)) - (charindex(@iq, @s) + len(@iq)), which gets the first @pipe index after @iq, and then substructs the index of the IQ value.


text:
Q: C++/Cli : Could not load file or assembly X or one of its dependencies. is not a valid Win32 application. (Exception from HRESULT: 0x800700C1) I have a C++ project, a C++\Cli project and a c# win forms project.
When i access the cli project from win forms project, i can access and use cli project functions. But when i include my cpp project headers into cli project, i get this run time error from my c# project when i access the cli project.
  CliWrapper.Func meta = new CliWrapper.Func();

This is the error i have taken :
BadImageFormatException : Could not load file or assembly X or one of its dependencies. is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)
I realized that #include <boost/thread.hpp> causes the problem

A: I have found the solution :
http://marc.info/?l=boost-users&m=123425857320026

In Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor
  Definitions add BOOST_ALL_DYN_LINK in order to force the usage of the
  DLLs. In addition copy the necessary DLLs to the directory where the
  executable resides. E.g. copy boost_thread-vc90-mt-gd-1_XX.dll to
  MyApp/bin/Debug.

A: It is very likely that your C++ project is compiled as Win32 and your C# project is either AnyCPU being ran on a 64-bit machine or, simply, an x64 assembly.
Configure your C# and C++/CLI project to target x86 architecture.


text:
Q: sed changes files date I'm using sed in this way.
find . -type f -exec sed -i "s/$3/$4/g" {} +

but it changes the dates of all files even if it does not find the string in a file.
Can I avoid it?

A: You can first grep your file, to see if there is something to replace:
find . -type f -exec grep -q "$3" '{}' ';' -exec sed -i "s/$3/$4/g" '{}' ';'

Otherwise it is not possible to avoid the timestamp update, as sed basically re-creates the file, when -i is used:

--in-place[=SUFFIX]
This option specifies that files are to be edited in-place. GNU sed does this by creating a temporary file and sending output to this file rather than to the standard output.
When the end of the file is reached, the temporary file is renamed to the output file's original name.

GNU sed Manual