text:
Q: Implementing Scanner to read text file to array For this program, what i have written so far is in the code below. I am stuck.  Any hints/help would be greatly appreciated.
Given the UML Class Diagram and the TestApp class, produce a working system that meets the following requirements:
Implement a Department class with toString and equals overrides.  Two department objects are equal if both the name and building numbers match.
Create an abstract Employee class with toString and equals overrides.  Two abstract employees are considered to be the same if they are in the same department.
Implement a Consultant class that has an hourlySalary.  Two consultants are equal if they have the same rate (in pennies).
Implement a SalariedEmployee class.  Salaried employees are equal if they are in the same department and have the same salary (in pennies).
Follow the TODO instructions in the TestApp class to read the departments from the input txt file and test the system.
Ouput should be:

Executive 100
Research 112
Engineering 115
Production 120
Accounting 122
Executive 100(100) Steve Jobs $1000000.00
Research 112(200) Bill Joy $300000.00
Engineering 115(300) James Gosling $300000.00
Production 120(1100) Craig McClanahan $250.00
Accounting 122(400) Kevin Malone $51567.00
Research 112

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class TestApp {

public static void main(String[] args) {
    ArrayList<Department> depts =
        readDepartmentsFromFile("depts.txt");
    displayDepartments(depts);

    ArrayList<Employee> company = new ArrayList<>();
    populateEmployeeArray(company, depts);

    // TODO: Display everyone's pay w/o referring to the
    // subclasses (i.e., using Employee only)

    // TODO: Display all departments that are equal to this one:
    Department d1 = new Department("Research", 112);

    // TODO: Display all departments that are equal to this one:
    Department d2 = new Department("Accounting", 50);

}

private static void displayDepartments(ArrayList<Department> list) {
    // TODO: Display the list to std error (NOT standard output)
}

private static ArrayList<Department> readDepartmentsFromFile(String filename) {
    ArrayList<Department> list = new ArrayList<>();
    // TODO: Use a Scanner to read the input file depts.txt
    // and create one Department object per line in the file.
    // Add all objects to the list.
    // Be sure to close the scanner object using a finally block.
    // Handle possible execptions by producing a nice error
    // along with the execption's message to standard error
    // (NOT standard output).
    return list;
}

public static void populateEmployeeArray(ArrayList<Employee> array,
        ArrayList<Department> departments) {
    SalariedEmployee exec = new SalariedEmployee(100, "Steve",
            "Jobs", departments.get(0), 100000000);
    SalariedEmployee architect = new SalariedEmployee(200, "Bill",
            "Joy", departments.get(1), 30000000);
    SalariedEmployee engineer = new SalariedEmployee(300, "James",
            "Gosling", departments.get(2), 30000000);
    Consultant consultant = new Consultant(1100, "Craig",
            "McClanahan", departments.get(3), 25000);
    SalariedEmployee accountant = new SalariedEmployee(400,
            "Kevin", "Malone", departments.get(4), 5156700);

    array.add(exec);
    array.add(architect);
    array.add(engineer);
    array.add(consultant);
    array.add(accountant);
}

}

* Updated TestApp
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class TestApp {

public static void main(String[] args) {
    ArrayList<Department> depts =
        readDepartmentsFromFile("depts.txt");
    displayDepartments(depts);

    ArrayList<Employee> company = new ArrayList<>();
    populateEmployeeArray(company, depts);

    // TODO: Display everyone's pay w/o referring to the
    // subclasses (i.e., using Employee only)
    for (Employee employee : company){
        System.out.println(employee);
    }

    // TODO: Display all departments that are equal to this one:
    Department d1 = new Department("Research", 112);
    for (Department department : depts)
        if(department.equals(d1)){
            System.out.println(department);
        }

    // TODO: Display all departments that are equal to this one:
    Department d2 = new Department("Accounting", 50);
    for(Department department : depts){
        if(department.equals(d2)){
            System.out.println(department);
        }
    }

}

private static void displayDepartments(ArrayList<Department> list) {
    // TODO: Display the list to std error (NOT standard output)
    System.err.println(department.toString());
}

private static ArrayList<Department> readDepartmentsFromFile(String filename) {
    ArrayList<Department> list = new ArrayList<>();
    // TODO: Use a Scanner to read the input file depts.txt
    // and create one Department object per line in the file.
    // Add all objects to the list.
    // Be sure to close the scanner object using a finally block.
    // Handle possible execptions by producing a nice error
    // along with the execption's message to standard error
    // (NOT standard output).
    File aFile = new File(filename);
    System.out.println(aFile.exists());
    Scanner sc = null;
    if (aFile.exists())
        try{
            sc = new Scanner(aFile);
            while(sc.hasNext()) {
                String deptName = sc.next();
                int buildNum = sc.nextInt();
                Department mallory = new Department(deptName, buildNum);
                list.add(mallory);

                }
            }
    catch(FileNotFoundException exec) {
        System.out.println(exec.getMessage());
    }
    finally {
        sc.close();
    }
    return list;
}

public static void populateEmployeeArray(ArrayList<Employee> array,
        ArrayList<Department> departments) {
    SalariedEmployee exec = new SalariedEmployee(100, "Steve",
            "Jobs", departments.get(0), 100000000);
    SalariedEmployee architect = new SalariedEmployee(200, "Bill",
            "Joy", departments.get(1), 30000000);
    SalariedEmployee engineer = new SalariedEmployee(300, "James",
            "Gosling", departments.get(2), 30000000);
    Consultant consultant = new Consultant(1100, "Craig",
            "McClanahan", departments.get(3), 25000);
    SalariedEmployee accountant = new SalariedEmployee(400,
            "Kevin", "Malone", departments.get(4), 5156700);

    array.add(exec);
    array.add(architect);
    array.add(engineer);
    array.add(consultant);
    array.add(accountant);
}

}

TEXT FILE -
depts.txt -
Executive 100
Research 112
Engineering 115
Production 120
Accounting 122

A: You're calling get(0) and get(1) on departments before putting anything into the ArrayList. Solution: don't do this! Fill the ArrayList and don't call get(...) ever on it before knowing that something exists at that index.
populateEmployeeArray(company, depts);  // passed into method

And here's how you fill the depts ArrayList:
// you might need a bit more code in here!!!!  The // TODO: means do it :)
private static ArrayList<Department> readDepartmentsFromFile(String filename) {
  ArrayList<Department> list = new ArrayList<>();
  // TODO: Use a Scanner to read the input file depts.txt
  // and create one Department object per line in the file.
  // Add all objects to the list.
  // Be sure to close the scanner object using a finally block.
  // Handle possible execptions by producing a nice error
  // along with the execption's message to standard error
  // (NOT standard output).
  return list;
}

As you can see, this code does nothing but returns an empty ArrayList, and so it shows that you're going about things a bit backwards. You will instead want to fix this part of your program, get it to read in the text file first, and then fix the displayDepartments(...) method so you can test that the readDepartmentsFromFile works before trying to use the depts ArrayList!


text:
Q: How to do the program that able to show the top 10 keywords in text file, in python i am working on the program that able to show the top 10 keywords in the text file. The following are the step that i already did:

*

*open the file

*do the list of pairs

*and sorted the pairs

after sorted my program got error. the paragraph below is my code.
filename = 'alice.txt'

try:
    with open(filename, encoding='utf-8') as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = 'Sorry, the file ' + filename + 'does not exist. '
    print(msg)
else:
    words = contents.split()

wordfreq = []
for w in words:
    wordfreq.append(words.count(w))

pairs = str(list(zip(words, wordfreq) ))
for key , value in pairs.items():
    print("Pairs\n" + str(list(zip(words, wordfreq))))

#print("Frequencies\n" + str(wordfreq) + "\n")
#print("Pairs\n" + str(list(zip(words, wordfreq))))
#print(max(str(list(zip(words, wordfreq)))))

#print(max(int(list(wordfreq,words))))

#print("List\n" + str(words) + "\n")

#    num_words = len(words)
#    print("The file " + filename + " has about " + str(num_words) + " words. ")

A: The first problem seems to be you've chosen the wrong data type for your word to frequency 'pairing'.
So I've fixed it and modded it a little bit into a form that should get you a big closer to your answer, please provide more specific information about your problem.
filename = 'alice.txt'

try:
    with open(filename, encoding='utf-8') as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = 'Sorry, the file ' + filename + 'does not exist. '
    print(msg)
else:
    words = contents.split()

wordfreq = []
for w in words:
    wordfreq.append(words.count(w))

pairs = dict(zip(words, wordfreq))
for key, value in pairs.items():
    print(f"Pairs\n {key}, {value}")

A: If you convert your list to a set, you can identify the unique words in the text. Then by making a zip you can use sorted to sort the words based on the frequency of their appearance in the text.
filename = 'alice.txt'

try:
    with open(filename, encoding='utf-8') as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = 'Sorry, the file ' + filename + 'does not exist. '
    print(msg)
else:
    words = contents.split()

words_set = set(words)

wordfreq = []
for w in words_set:
    wordfreq.append(words.count(w))

pairs = zip(words_set, wordfreq)

sorted_pairs = sorted(pairs, key=lambda x:x[1], reverse=True)

for w, wq in sorted_pairs:
    print("'{}' appears {} times.".format(w, wq))

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show conditional image thumbnail size in Woocommerce As I'm developing a stock photo site I want to show my visitors a large preview of he image. To avoid image theft I have watermarked my images except for the full size. To serve a large preview I created a custom thumbnail size and change the code accordingly. See the thread here.
The case is that sometimes an image is uploaded with smaller dimensions as the 3072 px (width or height). What I want is that there is a fallback in this case to the thumbnail called 'large' which is one of the default Wordpress image sizes.
As it is right now it is falling back to the full size image. It appears that no thumbnail of size 3072 px is generated when the full size image is smaller then 3072px.
I have tried to get it done by the piece of code below but can't get it right.
What's wrong?
$filemeta = wp_get_attachment_metadata( $post_thumbnail_id, FALSE );

$image_width       = $filemeta['width'];
$image_height      = $filemeta['height'];

if ($image_width < 3072 || $image_height < 3072){
$thumbnail_size    = apply_filters( 'woocommerce_product_thumbnails_large_size', 'large' );
} else {
$thumbnail_size    = apply_filters( 'woocommerce_product_thumbnails_large_size', 'preview' );
}

A: Found it.
Changed this line in product_image.php
$thumbnail_size    = apply_filters( 'woocommerce_product_thumbnails_large_size', 'preview' );

in
add_image_size( 'preview', $width = 3072, $height =3072, $crop = false );

$post_thumbnail_id = get_post_thumbnail_id( $post->ID );
$filemeta = wp_get_attachment_metadata( $post_thumbnail_id, FALSE );

if ($filemeta['width']>3071 || $filemeta['height']>3071){
    $thumbnail_size    = apply_filters( 'woocommerce_product_thumbnails_large_size', 'preview' );
}else{
    $thumbnail_size    = apply_filters( 'woocommerce_product_thumbnails_large_size', 'large' );
}

Maybe there is a smarter way but this works for me.
EDIT 2018-06-26
I picked this project up after a while and noticed that it is not working anymore due to the WooCommerce update to 3.3. WooCommerce has changes the way it handles product images. For me it means that I'm back at square one. WooCommerce displays the full-size image in the light box and that is not what I want. Does someone have a clue?


text:
Q: Functional equation, inverse w.r.t composition, which function gives identity? Given a function $$f:\mathbb{C}\to\mathbb{C},\qquad z\mapsto \frac{1-2z-\sqrt{1-4z}}{2z}\text{,}$$ I want to know a function $g:\mathbb{C}\to\mathbb{C}$, for which holds $$\left(f\circ g\right)\left(z\right) = f\left(g\left(z\right)\right) = z\text{.}$$
So to speak, I want to know the inverse w.r.t. composition, which gives the idendity map $\operatorname{Id}_{\mathbb{C}}=z$.
I do not not how to proceed, any help is highly welcome.

A: Set $w=g(z)$. Then
$$ f(g(z))=z \implies f(w)=z, $$
or
$$ z = \frac{1-2w-\sqrt{1-4w}}{2w}. $$
Now rearrange this equation to solve for $w$.


text:
Q: Angularjs filter unordered list I'm trying to filter strings in a static unordered list. I'm able to filter items in an array but not sure how to do it for static html content.
The way I've learned to achieve it using an array is by using this method:
<input type="search" ng-model="name" />

    {{ person }}

I'm trying to achieve the same effect using an existing

<input type="search" ng-model="filter.name" placeholder="filter..." />

Bob/li>

Lisa

Lewis

Xuemin

Tom

Cassidy

I want to be able to filter the list items based on the text strings inside them, so for example typing 'L' in the textbox would only show:

*

*Lisa

*Lewis

A: Here is a hacked out way of doing it JSFiddle.
The key to it is in ng-change="filter()". Every time you enter a letter you decide which elements to show or hide.
$scope.filter = function() {
    var elem = document.getElementById('list');
    for (var i = 0; i < elem.children.length; i++) {
        var name = elem.children[i].children[0].innerHTML;
        if (name.indexOf($scope.name) != -1 || $scope.name == "") {
              elem.children[i].style.display = "block";
        } else {
            elem.children[i].style.display = "none";
        }
    }
}

Like I said, it's an ugly hack, but it works. You would be better off making an object out of your names, and using ng-repeat.


text:
Q: При подключении к сайту java.io.FileNotFoundException в android Подключаюсь к сайту https://time.is/Unix_time_now для того чтобы узнать время при выполнении hrCon.getInputStream() стабильный вылет с исключением java.io.FileNotFoundException
fun test() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                var nowTime: Long = getTime()
            } catch (e: Exception) {
                L.i("exception:" + e.toString())
            }
        }
    }
@Throws(Exception::class)
    private fun getTime(): Long {

        val url = "https://time.is/Unix_time_now"
        var hrCon: HttpsURLConnection = URL(url).openConnection() as HttpsURLConnection
        if (hrCon.getResponseCode() != HttpURLConnection.HTTP_OK) {
            var istream = hrCon.getInputStream()
            val doc: Document = Jsoup.parse(istream, "UTF-8", url)
            val tags = arrayOf(
                "div[id=time_section]",
                "div[id=clock0_bg]"
            )
            var elements: Elements = doc.select(tags[0])
            for (i in tags.indices) {
                elements = elements.select(tags[i])
            }
            return elements.text().toLong()
        } else {
            return -1
        }
    }


text:
Q: Некоторые аудио файлы .ogg из массива бесконечно проигрываются Привет. Пишу аудио проигрыватель под Android. Проблема в следующем: есть коллекция (LinkedList) путей аудио файлов. Цель: MediaPlayer должен после воспроизведения одного переходить к воспроизведению следующего.
OnCompletionListener() реализован так, что в методе onCompletion() по окончании воспроизведения проверяется наличие следующего элемента-файла в коллекции и при наличии такого вызывается start() MediaPlayer`a.
Не могу разобраться почему, но 1 файл, проигрывается - включается 2 файл,
он тоже проигрывается - включается 3 файл,
он тоже проигрывается - включается 4 файл, и вот он уже проигрывается бесконечно, дальше опять несколько файлов проигрываются и следующий опять бесконечно.
Параметр Looping()=false, все файлы имеют расширение .ogg, эти файлы 3 и 4 секунды, другие более длительные, другие менее длительные.
Т.е. onCompletion() вообще не вызывается в этих двух случаях.
@Override
public void onCompletion(MediaPlayer mp){
    Toast.makeText(this, "Воспроизведение закончено!", Toast.LENGTH_SHORT).show();
    if(lllZZZ.listIterator(indd+1).hasNext()){
        if(!new File(lllZZZ.get(indd+1)).isDirectory()){
            indd=indd+1;
            startmp(indd);
        }
    }
    else{
        indd=indffZZZ;
        startmp(indffZZZ);

    }
}

Таким образом не происходит переход к следующему файлу.
Кто что думает почему?


text:
Q: Input radio button change algorithm Shop. Cart
name  |  price  |  count  |  price*count
apple      2         2           4
banana     3         4           12

Delivery
(radio button) none                       | checked
(radio button) to home (+3)
(radio button) to another town (+6)

Total Count               |      16

*

*When you change count - my script dynamically recounts total count and changes with Jquery Total Count text()

Now I just need to change dynamically Total Count text when delivery changes.
I just dont get HOW.
If I change it to to home, Total Count += 3, then if I change count for item, Total Count += ((price*newcount)-price*count)
But when I change delivery to another town, Total Count+= (new input - prev.input radio), but when I change back to 0, Total Count-= (input value)
My JQuery script simply on change takes the value of price*count, multiplies price and count siblings values and checks - and if it differs, changes the Total Count text.
var updating = false;
if(!updating){
   updatePrice();
}

function updatePrice(){
   var pricewas = pricecountitem.text();
   var pricenow = pricecount;
   var difference = pricenow - pricewas;
   var numadd = 1;

   if(difference < 0){
      pricecountitem.text(+pricewas - numadd);
   }else if(difference > 0) {
      pricecountitem.text(+pricewas + numadd);
   }

   if(difference !== 0){
      updating = true;
      setTimeout(updatePrice, 1000);
   }else{
      updating = false;
   }
}

I just cant write the algoritm how dynamically to change the value including all cases of delivery and count changes.
My head is going to blow up, can you guys please help me,  ?

A: added delivery on next page, where info is inputed. question closed.


text:
Q: Unable to connect to Apache website hosted on VPS I have set up a basic LAMP stack on a self managed VPS and now I would like to to preview the site by the IP assigned by our provider - before switching DNS over. Chrome reports the following error when trying to access the site.
I see the following in the logs:
[Mon May 28 14:06:07 2012] [notice] caught SIGTERM, shutting down

when I try to access by the IP. The only other customisation was installing Nagios which seems to be fine - although I cannot access that by http"//MY IP/nagios either

A: Add an entry to the hosts file on the client which you're testing from which maps the domain to the IP you want to test against. The hosts file is (usually) consulted before DNS, so this will override the IP configured in DNS. On *nix this file is /etc/hosts (I'm not sure offhand about other OSes.) I'm assuming that you've already configured Apache to respond for this domain.
1.2.3.4     example.com

(Remember to remove this when you actually switch DNS over so that you don't mask DNS issues.)

A: Just in case anyone else finds this useful - our dedicated server came with the firewall pre-configured - port 80 was blocked. I had to make alterations IPtables.

A: You only need to change your host file. /etc/hosts


text:
Q: Issues with Android Keyboard Look at this...

This is the main screen of the android app I'm developing. When user touches first EditText, the system keyboard shows like this:

But when user touches second EditText, the keyboard shows like this:

Without that black bar on top of it... Does anyone knows why is this? I'm working with a Samsung Galaxy Nexus... Besides... I noted that the keyboard is displayed on top of GUI... but in another screen of my app the keboard makes the GUI to roll up, like this:

In this last image, on top of the three buttons is a ScrollView, is this the reason for the keyboard make this effect?
Can anybody help me here? I'm stuck!
Thanks!


text:
Q: AndEngine Error with PhysicsWorld i am new with java and andengine and try to make the released jumper game to learn how it works. all fine now but if i try to load the PhysicsWorld i will get as follow errors:
E/AndroidRuntime: FATAL EXCEPTION: UpdateThread
          Process: com.alex.neuertest, PID: 15463
          java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.alex.neuertest-1/base.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.alex.neuertest-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.alex.neuertest-1/lib/x86, /data/app/com.alex.neuertest-1/base.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_dependencies_apk.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_slice_0_apk.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_slice_1_apk.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_slice_2_apk.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_slice_3_apk.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_slice_4_apk.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_slice_5_apk.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_slice_6_apk.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_slice_7_apk.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_slice_8_apk.apk!/lib/x86, /data/app/com.alex.neuertest-1/split_lib_slice_9_apk.apk!/lib/x86, /system/lib, /vendor/lib]]] couldn't find "libandenginephysicsbox2dextension.so"
          at java.lang.Runtime.loadLibrary0(Runtime.java:972)
          at java.lang.System.loadLibrary(System.java:1530)
          at org.andengine.extension.physics.box2d.PhysicsWorld.<clinit>(PhysicsWorld.java:35)
          at com.alex.neuertest.GameScene.createPhysics(GameScene.java:345)
          at com.alex.neuertest.GameScene.createScene(GameScene.java:96)
          at com.alex.neuertest.BaseScene.<init>(BaseScene.java:41)
          at com.alex.neuertest.GameScene.<init>(GameScene.java:0)
          at com.alex.neuertest.Core.SceneManager$1.onTimePassed(SceneManager.java:148)
          at org.andengine.engine.handler.timer.TimerHandler.onUpdate(TimerHandler.java:94)
          at org.andengine.engine.handler.UpdateHandlerList.onUpdate(UpdateHandlerList.java:47)
          at org.andengine.engine.Engine.onUpdateUpdateHandlers(Engine.java:618)
          at org.andengine.engine.Engine.onUpdate(Engine.java:605)
          at org.andengine.engine.LimitedFPSEngine.onUpdate(LimitedFPSEngine.java:57)
          at org.andengine.engine.Engine.onTickUpdate(Engine.java:568)
          at org.andengine.engine.Engine$UpdateThread.run(Engine.java:858)

maybe anyone can help me whats there wrong? how i said, iam new on this system xD

A: This error means that the library for physics box was not found. You have to add physicsbox2dextenstion.so file in app folder as shown in picture. You may be clear after watching picture. Hope this help you.

A: Project not able to find libandenginephysicsbox2dextension.so. Check do you have .so files inside your project. For different cpu architecture there are three .so file inside AndEnginePhysicsBox2DExtension.


text:
Q: Sophisticated use of Nest: Using the current iteration number and referring to outer lists I want to write an iterative algorithm on the base of Nest (avoiding usage of cycles) to create an expression of the type
$$
x^{a_1x^{a_2x^{\ldots}}}
$$
where the numbers $a_1, a_2, \ldots $ are given in a list apriori.
The problem is that I don't know how to refer to Nest's current iteration number. For example, $x^{x^{x}}$ is computed by
Nest[x^(#) &, x, 3]

How do I refer to a[[i]] in the expression x^(#) & ?

A: Another way using Fold is to use the product of x and alist as the third argument
alist = {a1, a2, a3};

Fold[#1^#2 &, x, x*alist]

$$\left(\left(x^{a_1 x}\right){}^{a_2 x}\right){}^{a_3 x}$$

A:  a = {a3, a2, a1};
 i = 1; Nest[x^(a[[i++]] #)&, x, 3]

Or
 b = {a1, a2, a3};
 i = 3; Nest[x^(b[[i--]] #)&, x, 3]


text:
Q: Render a basic div element Backbone View I am building a Backbone view that is simply a <div> and an id attribute.
I've commented where I'm lost with it:
window.ContainerView = Backbone.View.extend( {

  el: $( '<div>', { id: 'content' } ),

  initialize: function() {
    this.render();
  },

  render: function() {
    // How do I render this view?
  }
} );

In my main.js, I simply do:
var containerView = new ContainerView();

And for good measure, here is my index.html body section, where I include all my Backbone files.
<body>

  <!-- Libraries -->
  <script src="./lib/jquery-min.js"></script>
  <script src="./lib/underscore-min.js"></script>
  <script src="./lib/backbone-min.js"></script>

  <!-- Models -->

  <!-- Views -->
  <script src="./js/views/ContainerView.js"></script>

  <!-- App -->
  <script src="./js/main.js"></script>

</body>

A: the default tag of el in Backbone is div and you can set the id is id attribute. go through the documentation
window.ContainerView = Backbone.View.extend( {

  'id' : 'content',

  initialize: function() {
    this.render();
  },

  render: function() {
    $('body').append(this.el);
  }
} );


text:
Q: Access app_context from custom Converter in Quart Is there a solution to get the app context in a class that inherit werkzeug BaseConverter class?
This is my example running in Flask:
from werkzeug.routing import BaseConverter
class CodeConverter(BaseConverter):
    app = None

    def to_python(self, value):
        # Create an app context to get value from db
        # and instantiate a class X as obj
        return obj

    def to_url(self, obj):
        value = obj.code
        title = obj.title
        return "%s/%s"%(value, title)

def crate_app():
    ...
    app.url_map.converters['code'] = CodeConverter
    CodeConverter.app = app
    ...

A: Well, this works for me.
from werkzeug.routing import BaseConverter
class CodeConverter(BaseConverter):
    app = None

    async def get_object(self, app, value):
        async with app.app_context():
            # and instantiate a class X as obj
            return obj

    def to_python(self, value):
        pool = concurrent.futures.ThreadPoolExecutor()
        result = pool.submit(asyncio.run, self.get_object(self.__class__.app, value)).result()
        return result

    def to_url(self, obj):
        value = obj.code
        title = obj.title
        return "%s/%s"%(value, title)

def crate_app():
    ...
    app.url_map.converters['code'] = CodeConverter
    CodeConverter.app = app
    ...


text:
Q: missing graphs in subplot in matlab I have such a code;
figure;
    for a = 1:length(weekM')
        tday_cell = day_cell(week_cell == weekM(a));
        for b = 1:length(days)
            subplot(length(weekM'), 7, b);
            if strcmp(first_entranceM{a, b}, '0')
                plot(peaks);
                l = [l; 0];
            else
                tms_cell = ms_cell(week_cell == weekM(a));
                ttms_cell = tms_cell(strcmp(tday_cell,days{b}));
                l = [l; ttms_cell];
                plot(ttms_cell);
            end
        end
    end

I want to plot graphs with subplot function as subplot(3,7,[1:2:3...]). That is, I want to plot graph which has 3 lines, and 7 graphs on each line.
But in my case, it only shows the last line on the first line, and I can't see the remaining graphs.
I'm sure that the data to plot previous graphs are not being lost, but I don't understand why there are missing graphs.
Could you help me to fix this problem?

A: Your line with the subplot-statement needs to be changed. The first argument is correct. The second argument represents the number of columns and needs to be set to 7 here, since you have 7 days. The last argument is the index of the addressed subplot and needs to be changed in every iteration.
This index can be generated using the sub2ind-function, which calculates the index from the subscripts. The following line can be used instead of yours:
subplot(length(weekM'),7,sub2ind([7,length(weekM')],b,a));


text:
Q: Regex substitute file extension prefix placement doesn't work - replace matches I'm quite familiar with regex, but I'm not familiar with C++11's std::regex_replace. I spent like more than an hour trying to figure out how to replace a simple file extension, but nothing is working!
What I want to achieve is quite simple. I want to replace myfile.pdf with myfile.txt. So I wrote my regex to match files that end with .pdf:
std::regex regex("^.*\\.(pdf)$")

And following a reference and following a cheat-sheet, I want to see the prefix (whatever comes before a match), so I use:
std::string myStr = std::regex_replace(std::string("HiThere.pdf"), regex, std::string("$`"))
std::cout<< myStr <<std::endl;

And I get an empty string! This happens, although I get a match! To show that I'm getting a match, simply replace "$`" with "$1", and you'll see the first match replacing the whole string.
One side note, according to all references, $0 should show the whole string, but it doesn't!
All I want to achieve is to replace that match with ".txt". What am I doing wrong here?

A: This is correct behaviour.  $` is the string before the match - but you matched the whole string!  (So $` is empty).
I also think you need to capture the .*, rather than the .pdf (you know what that is, after all!).  I think what you want is:
std::regex regex("^(.*)\\.pdf$")
std::string source("HiThere.pdf");
std::string myStr = std::regex_replace(source, regex, "$1.txt");

or even:
std::regex regex("\\.pdf$")
std::string source("HiThere.pdf");
std::string myStr = std::regex_replace(source, regex, ".txt");

A: "$`" is going to be empty since you matched the entire input string.
It's a prefix to the match, not to the first backreference.
You can achieve your goal quite simply:
std::regex regex("^(.*)\\.pdf$");
const std::string myStr = std::regex_replace(
   "HiThere.pdf",
   regex,
   "$1.txt"
);
std::cout << myStr << '\n';


text:
Q: union all and sum I have 2 tables:
table 1
mmsi   type   l   w   flag   value
123    456    A   B   C      37
236    567    X   Y   Z      28

table 2
mmsi   type   l   w   flag   value
123    456    A   B   C      30
234    567    X   Y   Z      20

and I want to run a query to get unique values and for each row the sum of values stored in  the last field:
table final
mmsi   type   l   w   flag   value
123    456    A   B   C      67
234    567    X   Y   Z      20
236    567    X   Y   Z      28

How can I do it? I am trying with UNION ALL and SUM
SELECT "mmsi", "type", "l", "w", "flag", "value", SUM ("value")
FROM (SELECT "mmsi", "type", "l", "w", "flag", "value" FROM "table 1" UNION ALL
SELECT "mmsi", "type", "l", "w", "flag", "value" FROM "table 2") as def
GROUP BY "mmsi", "type", "l", "w", "flag", "value"

but this give me the following wrong result:
mmsi   type   l   w   flag   value  sum
123    456    A   B   C      37     37
123    456    A   B   C      30     30
234    567    X   Y   Z      20     20
236    567    X   Y   Z      28     28

Thanks!

A: You need to remove value from the select and group by:
SELECT "mmsi", "type", "l", "w", "flag", SUM("value")
FROM (SELECT "mmsi", "type", "l", "w", "flag", "value" FROM "table 1"
      UNION ALL
      SELECT "mmsi", "type", "l", "w", "flag", "value" FROM "table 2"
     ) as def
GROUP BY "mmsi", "type", "l", "w", "flag";


text:
Q: C# The client and server cannot communicate, because they do not possess a common algorithm I'm trying to migrate my C# web application to a production instance that runs on windows server 2012 R2. When I try to browse the application via IIS I receive this strange error "The client and server cannot communicate, because they do not possess a common algorithm" and I'm not entirely sure what it means.
I read some other questions online similar to mine and they stated the problem stems from incompatibility issues with SSL/TLS. I believe my new server uses TLS 1.2 after checking in regedit and locating what I assume is my TLS certificates. My application encounters this error whenever it tries to connect to a DB that runs on a SQL Server 2008 DB system located on a different instance. Where my website is currently hosted, it's not having any issues (it's running on a Windows Server 2008 R2 instance).
My question is, do you know where I can locate what security certificates my App on the production server and my SQL Server DB instance, and do they have to be similar to solve this "The client and server cannot communicate, because they do not possess a common algorithm" error. Any help will be greatly appreciated.

A: Upgrade your project to use ASP.NET 4.6 or higher or use the following code on ASP.NET 4.5
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // .NET 4.0

ASP.NET 4.6 automatically uses TLS 1.2 if its available.


text:
Q: Can't Keep Pretty Url with htaccess I'd like to have url like
mydomain/a/b from mydomain/page.php?a=$1&b=$2
The htaccess file understand that I want to go to mydomain/page.php?a=$1&b=$2 when i use mydomain/a/b but he change the urlname to mydomain/page.php?a=$1&b=$2 and I don't want that, i want to keep mydomain/a/b.
Here is the htaccess file I use:
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)/([0-9]+)$ page.php?a=$1&b=$2


text:
Q: How do I get the output from a Perl pipe as it becomes available? The following code is working sort of fine:
open( PIPE, '-|', 'ant' );
for( <PIPE> ) {
    print;
}

However, it doesn't do what I want. Since the Ant build can take 5 minutes, I would like to see the output line by line.
Instead, I'm getting the entire input at the end of the process.
Looking at it with the Perl debugger, Perl waits at the 'for' statement, until Ant terminates. Why is that?

A: Just for completeness (problem was solved as pointed out in the comment to Uri's answer) the problem arose because the for expression evaluates the <> operator in list context (see), equivalently to the following:
foreach $line (@lines = <PIPE>) {
    print $line;
}

In list context, the <> operator tries to read all lines from its input to asign to the list - and the input comes from a process, it will block until the process ends. Only afterwards it it will enter the loop body.
The alternative  syntax
while( <PIPE> ) {
    print;
}

is equivalent instead to
while(  $line = <PIPE> ) {
    print $line;
}

i.e., it consumes each line from the input in each loop iteration, and this is what one wants to do in this scenario.

A: I believe the problem is buffering. You could make the filehandle hot(unbuffered) like so:
select PIPE;
$| = 1; # the pipe is just a coincidence. that's the variable's name
select STDOUT; # select it back

This should disable buffering for PIPE. I read about something like this in Learning Perl, 5TH. See this, also. You should probably also make sure buffering doesn't happen someplace else.
EDIT: the OP posted that replacing the for with while solved the problem
I think I understand now. while gets each line and runs the loop, whereas for acts like foreach and first gets all the lines (it needs list context) and then loops over the lines.

A: Found it.
The problem is with the 'for' statement.
The following code works as expected
open( PIPE, '-|', 'ant' );
while( <PIPE> ) {           # replacing 'for' with 'while'
    print;
}

I don't know the reason, but now it is working.


text:
Q: Is Opentaps open source dead? We have been trying to find information about opentaps recent development but most of the timestaps are years old.
-What is the commit level on this project?
-How many active developers are on this project?
-What is the roadmap of this project?
-Is there any real recent development going on?

A: I can confirm that Opentaps is not dead at all. We are working on the version 2 of the project and that's the reason you do not see commits there.
If you need any help of information please let me know.


text:
Q: Is it possible to limit build queue for certain build configuration? I am trying to work out an efficient setup to ensure that compiling and deploying builds takes priority over running tests. I have a single agent containing two build configurations:

*

*Build, deploy, high level test (5 minutes)

*Unit tests, integrations tests, smoke tests (15 minutes)

I have configured the triggers such that the build projects runs every time a commit occurs in VCS. What I would like to do is to queue up the test project to run as lower priority. However, if multiple commits are made in a short space of time (a few minutes), I do now want to queue up lots of test projects.
For example, this is what I would like to achieve:

*

*12:00 commit

*12:02 commit

*12:08 commit

Build/deploy configuration kicked off at:

*

*12:00 (eta 5 mins)

*12:05 (eta 5 mins)

*12:10 (eta 5 mins)

Test project kicked off at:

*

*12:15 (eta 15 mins)

Where the test project runs just once with the latest deployed code. I do not want to queue up the test project 3 times.
Effectively, I only want to run the test project when the agent is idle and untested changes have been committed. Is this possible? if so, what is the best way to achieve it?

A: For batching frequent commits you can use 'Quiet period mode' in VCS trigger settings, read about this here. To avoid build triggering if the configuration in queue now - disable checkbox 'Trigger a build on each check-in' in VCS trigger settings.
And to manage build queue priorities click on 'Build Queue' link and then on 'Configure Build Priorities'. At this place you can manage priority classes. Read more about this here.
Note: You should be with System Administator role.


text:
Q: Как переделать программу, чтобы она могла работать с несколькими запросами? Есть программа, которой подается на вход 2 натуральных числа: размеры таблицы (а*b)
и строка вида
ADD (число) (число).
Оба числа являются координатами ячейки в таблице.  Программа должна прибавить 1 в ячейку с такими координатами. У меня программа может обрабатывать только 1 строку, а как сделать так, чтоб можно было ввести сразу несколько запросов?
public class Test3 {
static Scanner scanner = new Scanner (System.in);
static String str = scanner.nextLine();
static int a = scanner.nextInt();
static int b = scanner.nextInt();

static int[][] table = new int[a][b];
public static void main (String args[]) {

    res(getOp(str));

    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            System.out.print(" " + table[i][j] + " ");
        }
        System.out.println();
    }

}
public static String getOp(String str) {
    String [] ops = str.split(" ");
    return ops[0];
}
public static int getX(String str) {
    String [] ops = str.split(" ");
    return Integer.parseInt(ops[1]);
}
public static int getY(String str) {
    String [] ops = str.split(" ");
    return Integer.parseInt(ops[2]);
}
public static void res(String op) {
    switch(op) {
    case "ADD":
        table [getX(str)-1][getY(str)-1]+=1;
        break;

    }
}

A: Старайтесь хоть немного избавляться от статики. Помните о инкапсуляции. Разбивайте методы осмыслено, а не лишь бы раздробить на части. К примеру, вы создали 3 метода, которые делят строку сплитом(каждый), два из них парсит стринг в инт? Это дублирование кода. Старайтесь быстрее выйти за пределы класса и метода мейн. А еще свитч с одним кейсом выглядит очень странно...
import java.util.Scanner;

class Test3 {

    public static void main(String args[]) {

        while (true) {
            Scanner scanner = new Scanner(System.in);
            String str = scanner.nextLine();
            int a = scanner.nextInt();
            int b = scanner.nextInt();

            new Test4(a, b).start(str);

        }
    }

}

class Test4 {

    private final int[][] table;

    public Test4(int a, int b) {
        this.table = new int[a][b];
    }

    public void start(String str) {
        res(str, table);
        printTable(table);
    }

    private void res(String str, int[][] table) {
        final String[] split = str.split(" ");
        switch (split[0]) {
            case "ADD":
                table[stringToInteger(split[1]) - 1][stringToInteger(split[2]) - 1] += 1;
                break;

        }
    }

    private Integer stringToInteger(String s) {
        return Integer.valueOf(s);
    }

    private void printTable(int[][] table) {
        for (int i = 0; i < table.length; i++) {
            for (int j = 0; j < table[i].length; j++) {
                System.out.print(" " + table[i][j] + " ");
            }
            System.out.println();
        }
    }

}


text:
Q: Session Disappearing After Leaving Domain - Zend Framework With the Zend Framework, I have a problem with my sessions disappearing when I simply navigate away my domain, and then come back to it, but don't have any problems when going between pages on my own site.
Does anyone have any idea what's causing this?

A: OK I solved the problem (seemingly), by just clearing the cache in my browser. But I'd like to know why it works when I do that?
Thanks


text:
Q: Characterization of being a submersion Let $\mathcal{M}$ be a smooth $m$-dimensional manifold and let $F\colon \mathcal{M} \longrightarrow \mathbb{R}^{n}$ be any smooth map, with m $\geq$ n . I want to prove that, if $p \in \mathcal{M}$:
$$ \text{$F$ is a submersion at $p$} \iff \lbrace d_{p}F^{1},\dots,d_{p}F^{n}\rbrace  \text{ are l.i. in $(T_{p}\mathcal{M})^{*}$} $$
Were $d_{p}f := \lambda^{-1}_{f(p)} \circ T_{p}f \colon T_{p}\mathcal{M} \longrightarrow \mathbb{R} \in (T_{p}\mathcal{M})^{*}$, $T_{p}f\colon T_{p}\mathcal{M}\longrightarrow T_{f(p)}\mathcal{M}$ is the tangent map at $p$ and $\lambda_{p}\colon V \longrightarrow T_{p}V$ is the canonical isomorphism between a finite dimensional vector space over $\mathbb{R}$ and its tangent space. We can extend the definition of differential of a smooth map $F\colon \mathcal{M} \longrightarrow V$ by putting $D_{p}F := \lambda^{-1}_{F(p)} \circ T_{p}F \colon T_{p}\mathcal{M} \longrightarrow V$, where $V$ is a finite dimensional vector space over $\mathbb{R}$.
This is trivial if you take $\mathcal{M} = \mathbb{R}^{m}$ since you can identify the tangent map with the differential from ordinary calculus, but I want to formalize the proof as much as possible in the general case using the definitions I gave.

A: Linear algebra Fact: Let $A:V\rightarrow \mathbb{R}^n$ be a linear transformation of vector spaces, then $A$ is surjective iff $\pi_1A,\pi_2A,...,\pi_nA$ are linearly independent members of $V^*$. (Where $\pi_i:\mathbb{R}^n\rightarrow \mathbb{R}$ is ith projection).
Proof: Equip $V$with any inner product, then there exists $v_1,...,v_n\in V$ such that $\pi_iA(x)=x \circ  v_i$ for all $x\in V , i\in [n]$. $\dim(Im(A))=\dim(V)-dim(Ker(A))=dim(V)-dim(\{v_1,...,v_n\}^{\perp})=dim(span(\{v_1,...,v_n \}))$.
Thus $A$ is surjective iff $dim(Im A)=n$ iff $dim(span(\{v_1,...,v_n\}))=n$ iff $v_1,...,v_n$ are L.I. iff $\pi_1A,...,\pi_nA$ are L.I. $\square$
Identify the tangent space of any point of $\mathbb{R}^n$ with $\mathbb{R}^n$
Now let's go back to your setting, then for any $v\in T_pM$: $dF^i_p(v)=<v,F^i>=<v,\pi_i \circ f>=<Df|_pv,\pi_i>=\pi_i(Df|_pv)$.
So $dF^i_p=\pi_i\circ Df|_p$. Now apply the previous fact on the linear transformation $Df|_p:T_pM\rightarrow \mathbb{R}^n$ and you will be done.


text:
Q: Как взаимодействовать с ботом Telegram Создал бота, отправлял ему команды апишные из адресной строки браузера, он откликается. Как я понял, логика работы бота пишется в одном php файле, расположенном. Не могу понять как бот с этим файлом контактирует?  Там есть токен и адрес бота, но как инициализировать подключение к нему? На Java за меня все сделал Idea и спец. библиотека. Сейчас же мне надо все сделать на PHP. Я нашел много библиотек на PHP, но хочу понять на более простом примере как работает бот.

A: *

*Написать обработчик, к примеру:
//определим константы
define('BOT_TOKEN','ТВОЙТОКЕНДЛЯБОТА');
define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
//получаем информацию от бота
$content = file_get_contents("php://input");
//расшифровываем её
$update = json_decode($content, true);
//ID чата с пользователем. Понадобится при отправке ответа
$chatID = $update["message"]["chat"]["id"];
//Текст сообщения от пользователя
$messageText = $update["message"]["text"];
//Имя пользователя (Пример: Игорь)
$username = $update["message"]["from"]["first_name"];
//Наш ответ
$reply = $username.", спасибо, что написали мне ".$messageText;
//Формируем запрос
$sendto = API_URL . "sendmessage?chat_id=" . $chatID . "&text=" . $reply;
//Отправляем запрос
file_get_contents($sendto);

*Залить этот файл на какой-нибудь https сервер с поддержкой PHP (к примеру, heroku.com).

*Привязать бота к твоему файлу (он должен быть на сервере с валидным сертификатом)
набираешь в браузере:
api.telegram.org/botТВОЙТОКЕНДЛЯБОТА/setWebhook?url=https://ТВОЙСЕРВЕР.РУ/ТВОЙФАЙЛ.php


text:
Q: Criar uma directive que force o bind de um formulá Seguindo uma publicação de Fernando Mantoan, a coisa parace se bem simple, cria-se a directive:
myApp.directive('forceBind',  function() {
  return {
    require: '^form',
    priority: -1,
    link: function (scope, element, attrs, form) {
      element.bind('submit', function() {
        if (form.$valid) {
          angular.forEach(form, function(value, key) {
            if (value.hasOwnProperty('$modelValue')) {
              if (!value.$viewValue) {
                value.$setViewValue("");
              }
            }
          });
        }
      });
    }
  };
});

E o problema seria solucionado, ele até mostra o código funcionando.
Só que quando fui fazer na minha aplicação, olha só o que apareceu:

Depois de uns dois dias pesquisando, descobri que esse erro seria por conta da versão do angular,  ele usa a versão 1.2.1. Daí começa meus problemas, pois eu uso a versão 1.6.3 no angular, e já tentei de tudo para mudar sintax, mas acredito que eu não tenho o conhecimento necessário. :(
Aqui vai a parte do código onde eu faço a utilização da directive no form:
<form  force-bind ng-model="formUsuario" name="formUsuario"  ng-submit="salvarUsuario()" autocomplete='off'>

Dados Pessoais

            <input  class="form-control"  type="text" placeholder="Matrícula" floating-label ng-model="usuario.matricula" ng-disabled="{desabilita}"/>

            <input  class="form-control"  type="text" placeholder="Nome" floating-label ng-model="usuario.nome" required />

            <input  class="form-control"  type="text" placeholder="E-mail" floating-label ng-model="usuario.email"/>

                Perfil
                <select id="perfil_id" class="form-control" ng-model="usuario.perfil_id" ng-options="v.id as v.descricao for (k, v) in perfis" ng-disabled="{desabilita}">
                </select>

                Ativo
                <select id="ativo" class="form-control" ng-model="usuario.ativo" ng-disabled="{desabilita}">
                    <option value="1">Ativo</option>
                    <option value="2">Desativado</option>
                </select>

            <input  class="form-control" type="password" placeholder="Senha Atual" floating-label ng-model="usuario.senhaAtual" ng-trim="false" >

            <input  class="form-control" type="password" placeholder="Nova Senha" floating-label ng-model="usuario.novaSenha" />

            <input  class="form-control" type="password" placeholder="Senha Confirmada" floating-label ng-model="usuario.senhaConfirmada" />

        <button type="submit" class="btn btn-primary" ng-model="btnSalvar" ng-disabled="formLogin.$invalid || formUsuario.$pristine || btnCarregando.ativo">

            {{btnCarregando.ativo ? btnCarregando.mensagem : 'Salvar lterações'}}
        </button>

Acredito que de código seja suficiente, a directive e o html que faz a chamada do force-bind, caso seja necessário algo a mais só comentar que eu adiciono.
A grande questão é como fazer um force-bind para angular js na versão 1.6.3 evitando o erro:
ncaught TypeError: Cannot read property 'hasOwnProperty' of undefined
at force-bind.js:13
at Object.forEach (angular.js:424)
at HTMLFormElement.<anonymous> (force-bind.js:12)
at HTMLFormElement.dispatch (jquery-3.2.1.js:5206)
at HTMLFormElement.elemData.handle (jquery-3.2.1.js:5014)
   (anonymous) @ force-bind.js:13
   forEach @ angular.js:424
   (anonymous) @ force-bind.js:12
   dispatch @ jquery-3.2.1.js:5206
   elemData.handle @ jquery-3.2.1.js:5014

E conseguir fazer um input seja identificado ao se enviado para o backend.

A: Me pergunto, como buscar uma propriedade que não está declarada no código?
usei essa adaptação do código:
tcc.directive('forceBind',  function() {
return {
    require: '^form',
    priority: -1,
    link: function (scope, element, attrs, form) {
        element.bind('submit', function() {
            if (form.$valid) {
                angular.forEach(form, function(value, key) {
                    if(typeof value == 'object'){
                        if (value.hasOwnProperty('$modelValue')) {
                            if (!value.$viewValue) {
                                value.$setViewValue("");
                            }
                        }
                    }
                });
            }
        });
    }
};
});

Com a directive acima o erro não era mais apresentado, mas também não era forçado o bing dos campus no momento de enviar o código, só depois de muito tempo percebi que, eu não estava usando o atribulo name nos inputs, fazendo com que o erro fosse apresentado.
Só fiz colocar o atributo  name e tudo começou a funcionar:

     <input  class="form-control" name="teste3"type="password" placeholder="Senha Confirmada" floating-label ng-model="usuario.senhaConfirmada" />

Referencias:
Exemplo 1, nesse exemplo todos os campos tem o atributo name
Exemplo 2, nesse exemplo NEM todos os campos tem o atributo name, mas o que tem funciona


text:
Q: MSVC 2010 and MSVC 2012 are not works together I have come accross following situation:

*

*I had MSVC 2012 express and pro  edition in my windows 8 machine. My application build and run was working fine. Now I have installed MSVC 2010 express edition. My application build works. However it crashes duing run.

*I had MSVC 2010 express and pro  edition in my windows 7 machine. My application build and run was working fine. Now I have installed MSVC 2012 express edition. My application build works. However it crashes duing run.
I am using qt 5.0.2 64 and 32 bit creator to build and run my application.
My question is whether MSVC 2010 and MSVC 2012 are not works together in a single machine?
Will they replace older version exe/dlls or will they conflict each other?
Is there any solution/fix without removing MSVC 2010 and MSVC 2012?

A: The order of installation is important - you can use VS2010 and VS2012 together (I do) but you must install VS2010 first.
Simply reinstall VS2012 and you should be ok, although you may need to use the Windows SDK registration utility after installing VS2012 to make sure that VS2010 is directed to the Windows 7 SDK.


text:
Q: How to toggle between 2 Desktops with one hotkey in windows 10? I want to have one hotkey to do that.
at the moment I have to press Win+Ctrl+ Left/Right
Is it possible to press one combination to get from desktop 1 to desktop 2 and the other way around?

A: You can setup a Macro if you are using a Macro-Compatible Keyboard :)
But if you dont you can use AutoHotkey
You can find several Tutorials for AutoHotkey on Google. I dont know myself a way to just have one combination.


text:
Q: View json parse object structure in eclipse javascript I would like to view the json parse objects structure in eclipse. Due to the cross domain issue I am unable to use the console.log() to view the structure in chrome. How else can I view this [object Object] returned structure from Json.Parse ?

A: Use JSON.stringify(object), it will convert your object to a string(then you can alert, write or whatever you want).
EDIT
If this is the returned value from the request:
'{"Date":"05\/25\/2013","Description":"New2","Details":"New2","ItemRequestedID":"1343","Picture":,255,217],"Status":1,"User":"2120","UserName":"Ind1"}'

It is not yet parsed, so you need to use JSON.parse(string) to parse it to a valid JS Object. Once it is parsed, this will be the structure of your object:
{
    "Date": "05\/25\/2013",
    "Description": "New2",
    "Details": "New2",
    "ItemRequestedID": "1343",
    "Picture": ,
    255,
    217], "Status": 1,
"User": "2120",
"UserName": "Ind1"
}
var obj = JSON.parse(result)//where result is the string above and obj is the parsed object with this structure

Then you will be able to access what you need doing obj.Date, obj.Description etc


text:
Q: Get Facebook autocomplete list when posting When you create a new post on Facebook, and use the @ (at sign), when typing you get an autocomplete list of friends and pages liked.
Do you have any idea how to get this list using Facebook's Graph API? Or maybe some other solution? I am using Facebook CSharp SDK, so maybe there is a way using this library.
Thanks.

A: You can not tag users in normal posts or comments made via API.
The only situation where that is possible, is in Open Graph stories.
https://developers.facebook.com/docs/sharing/opengraph/using-actions#tags

If you need the user's liked pages also, then you need to request user_likes permission from them beforehand. (But I rather doubt that Facebook will approve the use of the permission for this purpose in review.)


text:
Q: Ctrl+alt+end not working inside remote desktop I am using dell laptop
I wanna change password but ctrl+alt+end is not working
Is there is any other way to change the password?

A: You could setup a script using AutoHotKey. Like an alternative key shortcut that would kick off the keys you need.
To change password, I think you could use control center.
Disclaimer: Its been over a year since I used windows, so things could have changed.
Source: https://superuser.com/questions/92801/how-to-send-ctrlaltend-to-remote-desktop

A: Use terminal to change password, if your GUI doesn't works.
Search on Google how to do that change in your OS.


text:
Q: How to get image height width in jquery I have a form where I uploads the image, in the jQuery function;
$('body').on('change', '#file', function () {

By using this.files[0] I am getting image name and size. for this I am using.
this.files[0].size and this.files[0].name. But now I want to get height and width of image. How can I do that?

A: I've got the solution by myself, it is as follows,
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
 function imageIsLoaded(e) {
         var image = new Image();
         image.src = e.target.result;
         image.onload = function() {
              // access image size here
              alert(this.width);
              alert(this.height);
         };
 };

as jquery dont know exact file type, so after Image type validation we can convert any image file to jQuery readable image, so jQuery can handle it as image. Hence for converting file to image we need reader.


text:
Q: Public IP address pointing to Internal IP address I have done port forwarding for an internal IP address used by some application to a public IP address so that the application can be accessed over the internet. The problem I have is when i access using the public IP from an external network over the internet the next link that browser redirects to is showing the local IP address and it fails because the local IP is not reachable externally. I suspect it could be a DNS problem or something missing on NAT but i don't know what exactly. Is there anything else I can do to ensure each of the links shows the public IP not the internal IP when the browser links are being navigated? The web application has been deployed on IIS in windows server 2012 r2

A: At first, The `NAT in the firewall should be configured in order to map the public IP/port to the intranet IP/port of the website. thus the internal web server could be accessed publicly.
Secondly, if the situation is that the website could be accessed properly but the hyperlink failed to be used, this should be rectified over the application level instead of the network issue, such as the hyperlink should be coded to the relative path instead of the absolute URL path.
What is the difference between ResolveUrl and ResolveClientUrl?


text:
Q: Select value from comma separated values in cell based on previous and next values I have a large database, a subset of which looks like this
ID    year        value1      value2
 1    2000   203,305,701     1, 2, 1
 1    2001       203,504        1, 1
 1    2002           203           1
 2    2010           245           3
 2    2011       245,332        2, 1
 2    2012           332           3
 2    2013           332           2
 2    2014       245,332        2, 1

Reproducible code:
structure(list(
ID = c("1", "1", "1", "2", "2", "2", "2", "2"),
year = c("2000", "2001", "2002", "2010", "2011", "2012",
"2013", "2014"), value1 = c("203, 305, 701",
"203, 504", "203", "245", "245, 332",
"332", "332", "245, 332"), value2 = c("1, 2, 1",
"1, 1", "1", "3", "2, 1", "3", "2", "2, 1")), class = "data.frame", row.names = c(NA, -8L))

"value1" and "value2" contain comma-separated values. The objective is to simplify the "value1" column to a single value. The algorithm I've thought out goes like this:

*

*Check for previous and next values for each row while grouping by ID (taking intersections: i.e. the common value in two consecutive rows).
For example, for row 5: The intersection of {245, 332} with the previous row {245} for value1 is 245, while with the next row {332} it is 332

*Prefer next value over previous value for selection.
I want to prioritise the next value i.e. {332} in this split decision.

*If either intersection does not narrow down to a single value, select value1 based on max(value2). If value2 does not have a maximum, select randomly.
The third step does not come into play since a single value is selected based on the first two steps.
The algorithm continues to the next row as soon as a single value is reached. Previous and next refers to the preceding and the following row respectively.
Similarly, for row 1:
The intersection is 203 with only the next row, as we stopped the algorithm as soon as we arrived at a single value.
The final data should  look like this
ID    year        value1      value2
 1    2000           203     1, 2, 1
 1    2001           203        1, 1
 1    2002           203           1
 2    2010           245           3
 2    2011           332        2, 1
 2    2012           332           3
 2    2013           332           2
 2    2014           332        2, 1

I tried writing a basic code in R to loop over each row grouping by "ID" and going through each year since I have no idea which package to use for this and going case by case, but it seems to me that this might not be the most efficient method. (I am also very new to R)


text:
Q: react HOC component not working after passed with dispatch and getstate from reduxjs I have a piece of code down below work well before transformed to HOC component:
class Filters extends React.Component {
  componentDidMount() {
    const { store } = this.context;
    this.unsubscribe = store.subscribe(() => this.forceUpdate());
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    const { store } = this.context;
    const currentFilter = store.getState().visibilityFilter;
    const tags = ["All", "Active", "Completed"];
    return (
      <>
        Show:{" "}
        {tags.map((t, index) => {
          if (t === currentFilter) {
            return (

                {t + " "}
                {index === 2 ? " " : ","}

            );
          }
          return (
             {
                store.dispatch({
                  type: "SET_VISIBILITY_FILTER",
                  filter: t
                });
              }}
            >
              {t + " "}
              {index === 2 ? " " : ","}

          );
        })}
      </>
    );
  }
}
Filters.contextTypes = {
  store: React.PropTypes
};

I changed it into HOC component like below and its not working and not error notification.This code is from canonical tutorial todolist from reduxjs offical document.I check react offical document https://reactjs.org/docs/higher-order-components.html and did not find any exception which did not obey its rules.Does anyone know what is error?
const Originfilters = ({ currentFilter, handleClick = (f = f) }) => {
  const tags = ["All", "Active", "Completed"];

  return (
    <>
      Show:{" "}
      {tags.map((t, index) => {
        if (t === currentFilter) {
          return (

              {t + " "}
              {index === 2 ? " " : ","}

          );
        }
        return (
           {
              handleClick(t);
            }}
          >
            {t + " "}
            {index === 2 ? " " : ","}

        );
      })}
    </>
  );
};
class Filters extends React.Component {
  componentDidMount() {
    const { store } = this.context;
    this.unsubscribe = store.subscribe(() => this.forceUpdate());
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    const { store } = this.context;
    return (
      <Originfilters
        currentFilter={store.getState().visibilityFilter}
        handleClick={(filter) => {
          store.dispatch({
            type: "SET_VISIBILITY_FILTER",
            filter
          });
        }}
      />
    );
  }
}
Filters.contextTypes = {
  store: React.PropTypes
};

A: This logic is stale nowadays and cancel the question


text:
Q: Node.js and Couchbase Compatibility I am attempting to install the Node.js SDK for Couchbase on a Windows 7 machine.     I am running the installation by typing npm install --save couchbase into a command prompt window.  I have received mixed results from my attempts.  My results are below.
Versions for Which the Installation Works Well

*

*0.10.40

*0.10.45

*0.12.14

Versions for Which the Installation Generates Multiple Compilation Errors

*

*4.0.0

*4.3.0

*4.4.5

*5.6.0

*6.2.0

Do you know with which versions of Node.js the Node SDK for Couchbase is compatible?

A: After trying several potential solutions, I have been able to get the Node.js SDK for Couchbase to install on my machine over Node.js 6.0.0.  I am sharing the information below, in case anyone else is experiencing the same issue.  These steps seem to have resolved the problem for me.

*

*Uninstalled Visual Studio 2012 (and Visual Studio 2015...I attempted to use both versions to no avail)

*Restarted my computer

*Installed all of the components (not just the defaults) for Visual Studio 2013 Community Edition (https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx)

*Restarted my computer

*Opened a command prompt and made sure NVM was using Node.js 6.0.0 (e.g. nvm use 6.0.0 or nvm install 6.0.0)

*From the command prompt, globally installed node-gyp (npm install –g node-gyp) (Reference:  https://github.com/nodejs/node-gyp)

*From the command prompt, ran npm config set msvs_version=2013

*From the command prompt, ran npm config get msvs_version to confirm that I got 2013 by setting the value in the previous step

*From the command prompt, ran npm config set python <path_to_the_python_executable> e.g. npm config set c:\Python27\python.exe

*Ran npm config get python to confirm that I got the value I typed in the previous step

*From the command prompt, ran npm install couchbase
Some additional information is available in this thread on the Couchbase forum.


text:
Q: How to access all child
* elements in a list in jquery? For example, I have a html code that looks like the following:

a

b

c

d

e

f

g

I want to traverse through each of the
 element and check whether it has a specific class "class1". I am looking for something that look like (python-equivalent):
for i in $("#li1").children():
    print i.hasClass("class1")

I couldn't find a way to evaluate each of the child
 element in javascript or jquery. Can someone help?

A: You cannot nest
 directly under
. That would be an invalid mark-up. Although, you may have something like this:

a

b

c

d

e

f

g

So, for the above code, to get the same output, use this way:
$("#li1 li").each(function () {
  console.log($(this).hasClass("class1"));
});

This would print:
false
false
false
false
false
true
false

A: It building upon what Praveen has put you could also use the following just to loop through only those li tags that have the class

$("#li1 li.class1").each(function () {
  console.log($(this).hasClass("class1"));
});

Cheers

A: This looks like you're asking how to loop in JavaScript
Here is a way using while which stops at the index with a falsy value (i.e. undefined)
var i,                           // set up variables,
    i_idx = 0,                   // initial index
    list = $("#li1").children(); // and interesting object

while (i = list[i++]) {
    console.log($(i).hasClass("class1"));
}

Here is a way using for which goes through all indicies by doing two things in the comparison expression space of the for
var list = $("#li1").children(); // interesting object

for (var i_idx = 0, i; i = list[i_idx], i_idx < list.length; ++i_idx) {
    console.log($(i).hasClass("class1"));
}

Here i is set using the index i = list[i_idx] and then the index is tested against the length i_idx < list.length in a single expression by making use of the comma operator

Please note

*

*a jQuery Object's indexed properties point to native DOM objects, which is why they need to be wrapped in $(...) to use in jQuery again.

*while and for etc do not provide var scope, the variables i, i_idx, list are scoped by their parent function (or the global scope)

*Generating list in the condition of a while or for will result in its regeneration every iteration. This is usually not desired which is why it is vard in advance.

*There are native methods for iterating Array (.forEach, .map, etc) and jQuery provides iterating methods too, but you may be unexpectedly caught out if you don't know where these are coming from (e.g. Array-likes such as NodeList do not always provide such a method)

ES6
If you are working in an EMCAScript 6 supported environment, you can use for..of which behaves much more as you had in the python example,
for (let i of $("#li1").children()) {
    console.log($(i).hasClass("class1"));
}


text:
Q: How to setup setupProxy.js file in react typescript project I'm using React CRA-typescript template and want to configure proxy manually using http-proxy-middleware
This is my setupProxy.js

And this is my fetch request

But proxy is not redirecting to correct url and still using localhost.
This how request send in browser

Anyone know why this is happening or am I doing it wrong here?


text:
Q: Big-O, Omega, Theta and Orders of common functions
Based on this table, is it generally going to be true that for two functions whose most "significant" terms are of the same order that they will be big-Theta each other? And a function of order lower on this table will be big-O ones above it?
Here is the context of my question if it helps:

A: I'm not sure I fully understand your question, but have a look at (b):
$$
\lim_{n \to \infty} \frac{\sqrt{n}}{n^{\frac{2}{3}}} = 0
$$
This means $f(n) = o(g(n))$, i.e. we can pick $c >0$ arbitrarily small, and $\forall c>0 \ \exists \ N(c)\ s.t. \ \forall n>N(c) \ \sqrt{n} < c n^{\frac{2}{3}}$. At the same time $\nexists N(s) \ s.t. \forall n>N(s) \ \sqrt{n} >s n^{\frac{2}{3}}$.Hence $f(n) \neq \Omega (g(n))$.
Here $f(n)$ is the numerator and $g(n)$ is the denominator.

A:
is it generally going to be true that for two functions whose most "significant" terms are of the same order that they will be big-Theta each other?

Yes, in the following sense.
Assume that $f(n)=h(n)+r(n)$ and $g(n)=k(n)+s(n)$ with $h(n)=\Theta(k(n))$, $r(n)=o(h(n))$ and $s(n)=o(h(n))$. Then indeed $f(n)=\Theta(g(n))$.

A: It is not true that all functions corresponding to the same entry in the table will be $\Theta$ of each other.  In particular, $a^x = O(b^x)$ if and only if $|a| \leq |b|$.  I'm not sure about the L-notation bit.
It is true, however, that $f = O(g)$ if $g$ is lower down on the table.


text:
Q: Yii framework: Trying to get property of non-object What I have:
public function beforeValidate() {
    $offender = Accounts::model()->find(array('select'=>'id','condition'=>'username=:username','params'=>array(':username'=>$this->offender)));
    $informer = Accounts::model()->find(array('select'=>'id','condition'=>'username=:username','params'=>array(':username'=>$this->informer)));
    $this->offender = $offender->id;
    $this->informer = $informer->id;
    return parent::beforeValidate();
}

What I get:
PHP Notice, that says, that i'm trying to get property "id" of non-object $offender and $informer.
But those are 100% objects:
var_dump($offender):

object(Accounts)[46]

var_dump($informer):

object(Accounts)[46]

And it actually sets the right id, but shows that notice anyway. What is wrong?
SOLVED
Can't post it as official answer for six more hours, so i just leave it here:
Actually, the problem was in double beforeValidate() call.
AbuseController.php:
    if(isset($_POST['AbuseReport']))
    {
        $model->attributes=$_POST['AbuseReport'];
        if($model->validate())
        {
            $model->save();
        }
    }

First time it validates on $model->validate(), and replaces $this->offender and $this->informer with correct ID's. Second time it validates on $model->save();, but model returns null this time, because $this->offender is already ID, but it expects username.
The whole solution to this is to disable second validation: $model->save(false);.

A: use isset or is_object
if(isset($offender->id) || is_object($offender->id)){
$this->offender = $offender->id;
$this->informer = $informer->id;
}


text:
Q: Avoiding Repetitive View Code in ASP.NET MVC This is for an ASP.NET MVC 4 application in a Razor view. I am passing a model to a partial view and am trying to iterate through a given list of properties contained in the model to be displayed as a table.
Given something like List<string> propertyNames, in this table, I would like to output the DisplayNameFor and the value of the property in a structure like so:

    @Html.DisplayNameFor(Model.property)
    @Model.property

I'll have to do this a few times in the partial because different properties correspond to different div elements in the partial where different tables will be inserted so I've created a helper and this is where I get hung up. First, the only way I know how to do this is reflection, and I have read that reflection is expensive especially for just doing one property at a time. Also, using this method, I can't get @Html.DisplayNameFor to work correctly because, using reflection, I don't quite know the syntax:
@helper IterateDetailPropertyNames(List<string> propertyNames) {
    foreach (var property in propertyNames)
    {

                @Html.DisplayNameFor(m => m.GetType().GetProperty(property).GetValue(Model, null));
                @*Error: Templates can be used only with field access, property access...*@

                @Model.GetType().GetProperty(property).GetValue(Model, null)

    }
}

How can I make this work and improve this?

A: A models ModelMetadata gives you the data you need to generate your table. It contains the model value in additional to properties such as the DisplayName, DisplayFormatString, NullDisplayText etc that are determined from annotations applied to your properties.
For more information of ModelMetadata, refer the documentation and ASP.NET MVC 2 Templates, Part 2: ModelMetadata.
To generate your table, you could write the following HtmlHelper extension method
public static class TableHelper
{

    public static MvcHtmlString DisplayTableFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        // Get the ModelMetadata for the model
        ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        StringBuilder html = new StringBuilder();
        // Loop through the ModelMetadata of each property in the model
        foreach (ModelMetadata property in metaData.Properties)
        {
            var x = metaData.DisplayFormatString;
            string label = property.DisplayName;
            string value = null;
            if (property.Model == null)
            {
                value = metaData.NullDisplayText;
            }
            else if (metaData.DisplayFormatString != null)
            {
                value = string.Format(metaData.DisplayFormatString, property.Model);
            }
            else
            {
                value = property.Model.ToString();
            }
            TagBuilder labelCell = new TagBuilder("td");
            labelCell.InnerHtml = label;
            TagBuilder valueCell = new TagBuilder("td");
            valueCell.InnerHtml = value;
            StringBuilder innerHtml = new StringBuilder();
            innerHtml.Append(labelCell.ToString());
            innerHtml.Append(valueCell.ToString());
            TagBuilder row = new TagBuilder("tr");
            row.InnerHtml = innerHtml.ToString();
            html.Append(row.ToString());
        }
        TagBuilder table = new TagBuilder("table");
        table.InnerHtml = html.ToString();
        return new MvcHtmlString(table.ToString());
    }
}

and in the view
@using YourAssembly.TableHelper
....
@Html.DisplayTableFor(m => m)

You can also include the assembly in your web.config file so that the @using statement is not required in the view
As s side note,
 elements are for tabular data and should not be used for layout. Instead consider using styled
 elements


text:
Q: Spring PROPAGATION_REQUIRED.. joined Im using Spring and have two methods which are using declarative transaction...
in some cases methodA calls methodB.. what i need to know is in declarative trasaction does the commit occur twice...
example
public void methodA() throws Exception {

            this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED)
                final Order order = this.transactionTemplate.execute(new TransactionCallback<Order>() {
                    @Override
                    public Order doInTransaction(TransactionStatus status) {
                            Order order = new Order();
                            String name = "Customer 2 " + (new Date()).toLocaleString();
                            order.setCustomer(name);
                            entityManager.persist(order);
                         ..........................
                           .......................
                         // call methodB
                        methodB();

 }

public void methodB() throws Exception {

this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                    final Address add = this.transactionTemplate.execute(new TransactionCallback<Address >() {
                        @Override
                        public Order doInTransaction(TransactionStatus status) {
                                Address add= new Address ();
                                add.setAddress("address");
                                entityManager.persist(add);

                        ......................
                        .....................
    }

By using PROPOGATION_REQUIRED, the transaction in methodB will join the transaction started in methodA.
But would this mean that the transaction is committed twice?
I added sychronizer to the transaction in methodB :
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){

                    public void afterCommit() {
                        System.out.println("====> AFTER SUCCESSFUL COMMIT 2 TO DB...");

                    }

I added sychronizer to the transaction in methodA :
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){
                public void afterCommit() {
                    System.out.println("====> AFTER SUCCESSFUL COMMIT 1 TO DB...");

                }

The output i got was after methodA completed::
====> AFTER SUCCESSFUL COMMIT 2 TO DB...
====> AFTER SUCCESSFUL COMMIT 1 TO DB...

I guess this means that two sycnronisers have been assigned tot he trans..manager, and when the commit occurs once... both synchronisers are called?.. correct?

A: since you are using PROPAGATION_REQUIRED there will not be two different transaction, both methods will be running within the same transaction. If you look at the definition of PROPAGATION_REQUIRED it says

Support a current transaction; create a new one if none exists.

.
So if methodB completes successfully then it will not commit the transaction, but if it fails it will mark the transaction as rollback-only. The responsibility to actually commit or rollback will be on the the guy who created the transaction. In your case it will be on methodA


text:
Q: D3.js linechart - controlling x-axis with dates I have created a linechart with D3.js, but can't seem to figure out how to control the X-axis completely.
You can see my example her: http://codepen.io/DesignMonkey/pen/KdOZNQ
I have sat the ticks count for the x-axis to 3 days, and I have an Array with a range of 31 days, that should show a day in each end of the x-axis and skip to every third day. But for some reason when the a-axis pass the 1st in the month, it shows both 2015-08-31 and 2015-09-01 and doesn't skip to 2015-09-03 as it is supposed to.
My code for the linechart is here:
// Set the dimensions of the canvas / graph
let margin = {top: 30, right: 20, bottom: 30, left: 40},
    width = 330 - margin.left - margin.right,
    height = 180 - margin.top - margin.bottom;

// Set the ranges
var x = d3.time.scale().range([0, width]).nice(10);
var y = d3.scale.linear().rangeRound([height, 0]);

// Define the axes
var xAxis = d3.svg.axis().scale(x)
    .orient("bottom")
    .ticks(d3.time.days, 3)
    .tickFormat(d3.time.format('%e'))
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10)

var yAxis = d3.svg.axis().scale(y)
    .orient("left")
    .ticks(5)
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(10)

// Define the line
var valueline = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.value); });

// Adds the svg canvas
let svg = d3.select(template.find(".chart"))
  .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// For each line
data.forEach((item) => {

  // Scale the range of the data
  x.domain(d3.extent(item.data, function(d) {
    if(d.value != undefined)
      return d.date;
  }));

  // Create a perfect looking domainrange to the nearest 10th
  y.domain([
    Math.floor(d3.min(item.data, function(d) {
      if(d.value != undefined)
        return d.value;
    })/10)*10
    ,
    Math.ceil(d3.max(item.data, function(d) {
      if(d.value != undefined)
        return d.value;
    })/10)*10

  ]);

  // Add the X Axis
  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  // Add the Y Axis
  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

  // Add only points that have value
  svg.append("path")
    .attr("class", "line color-"+ item.colorClass)
    .attr("d", valueline(item.data.filter((pnt) => pnt.value != undefined)));

});

Can somebody tell me what I'm doing wrong here? :)
/Peter
UPDATE:
I found out it's like, that it want to show the new month. See this pen: http://codepen.io/DesignMonkey/pen/jbgYZx
It doesn't say "Septemper 1" but only "Septemper" like it wants to label the change of month. How do I disable this? :)

A: Solution:
var count = 0;
var tickRange = data[0].data.map((item) => {
  count = (count == 3) ? 0 : count+1;
  if(count == 1) {
   return item.date;
  }
})
.filter((d) => d != undefined);

and then:
  var xAxis = d3.svg.axis().scale(x)
      .orient("bottom")
      .ticks(d3.time.days, 3)
      .tickValues(tickRange)
      .tickFormat(d3.time.format('%e'))
      .innerTickSize(-height)
      .outerTickSize(0)
      .tickPadding(10)

Thanks :)


text:
Q: set to contain all numbers that can't be written with a finite number of digits I'm sorry if this was already asked/answered trough some different name, but I just couldn't find anything related to it nor here nor after a Google search.
It might also be because my native language isn't English and my thus my notions of maths in foreign languages is very limited.
Anyways, I'd like to know if there is a way to describe a set (I hope that is the proper word for it) that has all the numbers that can't be written with a finite number of digits (like $\sqrt{2}$, but also $\pi$ or $\dfrac13$).
Thank you!

A: Try
$$S=\Bbb {(R-Q)}\cup\lbrace{x\in \Bbb Q|x={p\over q},\ \ p,q\in \Bbb Z, \ \ q\ne
 0,\  \ (p,q)=1, \ \ \forall k\in\Bbb N, \ \ 10^k \ \  doesn't \ \ divide \  \   q}\rbrace \ \ $$

A: Your set includes all irrational numbers and all rational numbers whose simplified form is $m/n$ where $n$ has a  prime factor different from $2$ and $5$. For example $1/15$ is not in your set but $7/5$ is in your set.


text:
Q: ¿Por qué no se retorna el modelo a la vista cuando retorno hacia la misma vista? Tengo un AccessController que tiene dos ActionResult, Login() y Entrar(). El Login() es el HttpGet y al retornar le paso un modelo a la vista. El Entrar() es el HttpPost y si el modelo que recibe de la vista no es valido, entonces retorno return View("Login");. El problema es que el modelo que paso a la vista es nulo cuando retorno return View("Login");. Cuando la vista se carga la primera vez, el modelo se carga perfectamente, pero al mandar a mostrar la vista de nuevo cuando el modelo del HttpPost no es valido entonces me dice que el modelo es nulo. Este es el form de la vista:
<form action="Entrar" method="post">

Entrar al Sistema

        <input type="text" name="usuario" id="usuario" class="form-control w-75" placeholder="Digite su Usuario" minlength="8" required>
        <input type="password" name="password" id="contrasena" class="form-control w-75 mt-3" placeholder="Digite su Contraseña" minlength="8" required>

        <select name="empresa" id="selectEmpresa" class="btn-secondary colorSelectEmpresa w-75 py-2 mt-3">
            @{
                WebAppInventariosTNRD.Models.ListViewModels.AllListViewModels oLista = new WebAppInventariosTNRD.Models.ListViewModels.AllListViewModels();
                oLista = Model;
                int contador = 1;
                foreach (var oElemento in oLista.ListaDeEmpresasList)
                {
                    if (contador == 1)
                    {
                        <option value="@contador" selected class="bg-light text-dark">@oElemento.NombreEmpresa</option>
                    }
                    else
                    {
                        <option value="@contador" class="bg-light text-dark">@oElemento.NombreEmpresa</option>
                    }
                    contador++;
                }
            }
        </select>
        <button type="submit" class="btn btn-success py-2 px-3 mt-3">Iniciar Sesión</button>

</form>

Y este el ActionResult que dirige hacia esa vista:
        public ActionResult Login()
    {
        AllListViewModels allListViewModels = new AllListViewModels();
        allListViewModels.ListaDeEmpresasList = null;

        using (InventarioTNRDEntities db = new InventarioTNRDEntities())
        {
            allListViewModels.ListaDeEmpresasList = (from _emp in db.Empresa
                                                    select new ListaDeEmpresasListViewModel
                                                    {
                                                        NumeroEmpresa = _emp.IdEmpresa,
                                                        NombreEmpresa = _emp.NombreEmpresa
                                                    }).OrderBy(n => n.NumeroEmpresa).ToList();
        }
        return View(allListViewModels);
    }

Este es el Action Entrar()
    [HttpPost]
    public ActionResult Entrar(string usuario, string password, string empresa)
{
    try
    {
        using (InventarioTNRDEntities db = new InventarioTNRDEntities())
        {
            var lst = from _empresa in db.Empresa
                      join _ctlgUsuarios in db.CatalogoUsuarios
                      on _empresa.IDcatalogoUsuarios equals _ctlgUsuarios.IDcatalogoUsuarios
                      join _users in db.Usuarios
                      on _ctlgUsuarios.IDcatalogoUsuarios equals _users.IDcatalogoUsuarios
                      where _users.NombreUsuario == usuario && _users.Password == password && _empresa.Numero.ToString() == empresa
                      select _users;

            var IdEmpresa = from _empresa in db.Empresa
                            where _empresa.Numero.ToString() == empresa
                            select _empresa.IdEmpresa;

            if (lst.Count() > 0)
            {
                Usuarios oUser = lst.First();
                Session["User"] = oUser;
                Session["Empresa"] = IdEmpresa.First();
                Session["NotificarAccion"] = "0";
                return RedirectToAction("Index", "Main");
            }
            else
            {
                ViewData["NotificacionIndex"] = "2";
                ViewData["Mensaje"] = "Los datos ingresados no son correctos.";
                return View("Login");
            }
        }
    }
    catch (Exception ex)
    {
        ViewData["NotificacionIndex"] = "3";
        ViewData["Mensaje"] = "Error inesperado en tiempo de ejecución! " + ex.Message;
        return View("Login");
    }
}

El error es: oLista was null. Justo al intentar iterarlo en el foreach en la vista, cabe mencionar que en modo debug me di cuenta que cuando mando a mostrar la vista de nuevo, no esta entrando al codigo de la vista Login(), pero si la muestra hasta dar el error.

A: *

*El código no esta completo, no puedo ver el método Entrar.

*La manera de llenar el select no es correcto, requiere más código y puede estar generando el problema.

Sugerencia de como hacerlo:

*

*[https://asp.mvc-tutorial.com/tag-helpers/the-select-tag-helper/][1]

*[https://stackoverflow.com/questions/34624034/select-tag-helper-in-asp-net-core-mvc]

A: En el metodo de Login mandas la vista y el modelo, pero en el metodo entrar solo mandas la vista sin el modelo y la vista necesita ese modelo para rellenar la info que estas utilizando. Porque mejor no haces un redirect al metodo login cuando el usuario falle acceder?


text:
Q: How to create 4 buttons in 2rows and 2 columns at center of the screen <TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/TableLayout01"
    android:layout_height="wrap_content" android:layout_width="fill_parent">
    <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content"
                    android:layout_height="wrap_content">

        <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="Settings"
            android:id="@+id/btnSettings"></Button>
        <Button android:text="@+id/Button01" android:id="@+id/Button01"
            android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    </TableRow>
    <TableRow android:id="@+id/TableRow02" android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button android:text="@+id/Button03" android:id="@+id/Button03"
            android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
        <Button android:text="@+id/Button04" android:id="@+id/Button04"
            android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

    </TableRow>
</TableLayout>

please give suggestions,whether the code is right or wrong???

A: So close!
First you need to put the whole table layout in the following view. This can be your root view if you want
<RelativeLayout android:layout_width="fill_parent" android:id="@+id/relativeLayout1" android:layout_height="fill_parent">

Then just ad to your table layout the following atribute:
android:layout_centerInParent="true"

And finally change in the table layout android:layout_width="fill_parent" to android:layout_width="wrap_content"
Easy!


text:
Q: GUI tool to integrate xsd/xml into database I have a lot of xsd files with different complex types on it. I want to import data into my oracle database, but amount of data so huge and i can't use xsd2db or altova xmlspy because it's blowing my mind. I'm looking for simple and useful etl tool which can help me with it. Does anyone know gui tool to generate ddl by xsd?

A: This is a follow up to my comment; I am not positioning this as an answer, but it should help you understand more what is it that you are after, and maybe what you can do about it. For sure, it should be a good example for @a_horse_with_no_name...
I am not familiar with xmlspy, but given what I saw in xsd2db, it made me think of the .NET ability to infer a DataSet from an XML Schema. While the authoring style of the XSD itself may affect the way a DataSet is derived, it would be mostly insignificant for larger bodies of XSD. Even more, there is a big chance that the derivation might not even work (so many limitations there actually).
From my own experience, the derivation process in .NET gives you a very normalized structure. To illustrate, I am going to introduce a sample XML:
<ShippingManifest>
    <Date>2012-11-21</Date>
    <InvoiceNumber>123ABC</InvoiceNumber>
    <Customer>
        <FirstName>Sample</FirstName>
        <LastName>Customer</LastName>
    </Customer>
    <Address>
        <UnitNumber>2A</UnitNumber>
        <StreetNumber>123</StreetNumber>
        <StreetName>A Street</StreetName>
        <Municipality>Toronto</Municipality>
        <ProvinceCode>ON</ProvinceCode>
        <PostalCode>X9X 9X9</PostalCode>
    </Address>
    <PackingList>
        <LineItem>
            <ID>Box1</ID>
            <Load>1-233</Load>
            <Description>Package box</Description>
            <Items>22</Items>
            <Cartons>22</Cartons>
            <Weight>220</Weight>
            <Length>10</Length>
            <Width>10</Width>
            <Height>10</Height>
            <Volume>1000</Volume>
        </LineItem>
        <LineItem>
            <ID>Box2</ID>
            <Load>456-233</Load>
            <Description>Package box</Description>
            <Items>22</Items>
            <Cartons>22</Cartons>
            <Weight>220</Weight>
            <Length>10</Length>
            <Width>10</Width>
            <Height>10</Height>
            <Volume>1000</Volume>
        </LineItem>
    </PackingList>
</ShippingManifest>

Conceptually, its structure is very simple: a shipping manifest entity, a customer, a shipping address and a packing list.

Converting this to an ADO.NET DataSet is a straight forward exercise, with a very clean output.

It should be easy to imagine how the number of entities (tables in your database if you wish) could mushroom for just a bit more complex XML...
As a sidebar, if one designs the XSD keeping in mind a process involving DataSets, then removing the PackingList element and moving the LineItem collection as repeating under ShippingManifest gives a somewhat simplified layout: one without the PackingList entity.

Automatic tools to convert an XSD data model to a relational model, such as .NET's, are typically designed to generate a highly normalized structure. The denormalization, I guess, is left to the user for obvious reasons.
QTAssistant's XML Builder is different. Our requirement was to create an ER model which would work where .NET's XSD to Dataset doesn't, and with an output containing smaller number of entities, where possible. This is what QTAssistant generates for the same:

What QTAssistant did here, was to merge all entities engaged in a one-to-one relationship. From a modeling perspective, it's an obvious sin. It does have its benefits, particularly for our users interested in a simple structure capable of capturing data (test data to be more specific).
The generated mapping (XSD to ER) is bi-directional. It means that it can be used to generate valid XML from a database, or "shred" XML data into a database (the shredding is done by generating DML statements). The way this technology is used: test cases are stored in Excel spreadsheets, XML is generated, sent to a web service, and the results are stored back in Excel.
We also generate an XML file describing the structure which through an XSLT could be converted to DDL. And this is where things could get messy, depending on you schema. It is rather common to see XSDs where simple types are unconstrained: strings without maxlength, or using patterns without a maximum length; unconstrained decimals, etc. These are just some of the reasons why, in our case, we don't have an out of the box-straight-forward-way to generate the DDL but rather provide hooks for customizations.
So, to close my comment, I pretty much know what you want to do (I have to assume that other things, such as Oracle's XML capabilities, or XML databases and XQuery, etc. have been ruled out). Unfortunately, the XSD really matters here, so if you can share those as per my comment, I can take a look - it'll be up to you how much you want to share back here.


text:
Q: Solving Challenge -- Accessing Object Properties in a Function Challenge:

*

*create an object named team with two properties, partner1 and partner2

*write a function sayTeamNames that accepts a single parameter teamObj

*have that sayTeamNames log both partner names separated by ' and '

*call sayTeamNames with your team object

const team = {
  partner1: 'Bob,
  partner2: 'Julie'
}

function sayTeamNames(teamObj) {
  for (var key in teamObj) {
    console.log(teamObj[key] + ' and ' + teamObj[key])
  }
}

sayTeamNames(team)

A: Two problems I see:

*

*lose the , after the Julie

*lose the ' for Bob

const team = {
  partner1: 'Bob',
  partner2: 'Julie',
}

function sayTeamNames(teamObj) {
  for (var key in teamObj) {
    console.log(teamObj[key] + ' and ' + teamObj[key])
  }
}

sayTeamNames(team)

Note that based on the code, it will ouput Bob and Bob Julie and Julie if you want display something like Bob and Julie, use

const team = {
  partner1: 'Bob',
  partner2: 'Julie',
}

function sayTeamNames(teamObj) {
  for (let i = 0; i < Object.keys(teamObj).length; i += 2) {
    console.log(Object.values(teamObj)[i] + ' and ' + Object.values(teamObj)[i + 1])
  }
}

sayTeamNames(team)

A: you could do something like this
  const team = {
          partner1: 'Bob',
          partner2: 'Julie'
        }

        function sayTeamNames(teamObj) {
          console.log(Object.values(teamObj).join(' and '))
        }

        sayTeamNames(team)