text:
Q: Finding text files in a given path and applying a function to those files I made a function called "SolveLinearSystem[]" that solves,as its name suggests, a linear system of any amount of variables. It takes the path of a text file as its only argument. The function then proceeds to import and calculate the solution.
I currently have a bunch of files stored as text files individually, P1.txt, P2.txt,...,P15.txt which contain a linear system in them.
Now I need to find a way to query a directory so it shows me all text files in there, and then apply my "SolveLinearSystem[]" to each file.
My ultimate goal would be to create an unknown function that accepts a directory (Unknown[dir_]) as argument and then outputs the solution to each system similar to this:
P1.txt
{-0.385248, 0.236472, 1.03691, 1.10608, 1.14523, -1.51569, 1.14748, \
-0.961359, -1.53681, -0.8193, -0.949131}
P2.txt
{22.3934, -6.33219, -9.6342, 16.3643, -9.68272, -18.3644, -5.3851, \
3.75394, -25.4234, -7.91972, -0.370032}
P3.txt
{0.629152, -1.03705, -1.15584, 1.5237, -0.760991, 1.25683, 2.26095, \
-1.6362, 0.728382, -0.160247, -0.467798, -0.100069, -0.743948, \
0.720801, 0.904125}
...etc.

Which represent the set of solutions to each system. Thanks in advance for your help, guys!

A: You can change current working directory with SetDirectory, read docs for more info.
From the docs:
You can see a list of all files in the current working directory by evaluating FileNames[].
You could Map (docs) SolveLinearSystem[] to the output of FileNames[], once you have set the working directory to the files' location.
<3 <3 Documentation!


text:
Q: Undefined Reference To module_open I'm going through some C websocket programming code involving a  module_open function. I am getting a linker error stating this:
/tmp/ccJ3uaHB.o: In function `main':
main.c:(.text+0x8a): undefined reference to `module_open'
collect2: ld returned 1 exit status

This function is defined in a file server.h as:
extern struct server_module* module_open (const char* module_path);

Now including only relevant code, the function module_open is used in main() as follows:
#include <stdio.h>
#include <netdb.h>
#include "server.h"
#include <string.h>

int main()
{
    struct server_module* module = NULL;
    const char* page;

    if(*page == '/' && strchr(page + 1, '/') == NULL)
    {
        char module_file_name[64];
        snprintf(module_file_name, sizeof(module_file_name), "%s.so", page + 1);

         /* Try to open the module.  */
         module = module_open (module_file_name);

    }

}

And in case it helps here is the struct module from server.h as well
/* An instance of a loaded server module.  */
struct server_module {
  /* The shared library handle corresponding to the loaded module.  */
  void* handle;
  /* A name describing the module.  */
  const char* name;
  /* The function which generates the HTML results for this module.  */
  void (* generate_function) (int);
};

A: Try linking with -ldl switch.  I think you're trying to use the Dynamic Loader library right?

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript charAt() doesn't like user input that isn't zero this may be a stupid question or a typo but I'm going to ask anyway... I have the following form and when the form is submitted I want to check all the values of the input type="number" and make sure that if the user has for some reason put a zero at the start of the input, for example 01, 025, 0100, to remove the first zero as long as the value isn't zero. A simple piece of JavaScript made even easier with a jQuery selector. Note that all the text boxes here are type="number" not type="text" and please note my input

Here's my code:
$('input[type=number]').each(function(){
    // only if the string is not zero
    if(this.value.charAt(0) == "0" && this.value != "0"){
        this.value = this.value.substring(1);
    }
});

However when I came back to test my form fully I noticed my code didn't work! So I added the following to write to the console to check what was going on:
console.log("typeof:" + typeof(this.value) + " " + this.id + " char:" + this.value.charAt(0) + " val:" + this.value )
And this gave me the following output, notice the last 4 items that don't have the value of zero:

Why am I not getting the this.value.charAt(0) when the user has changed the default value of zero?

A: It seems that there are spaces in your value. Trim it before comparing (e.g. with jquery, or see here if you don't want to include jquery just for that):
$('input[type=number]').each(function(){
    // only if the string is not zero
    var myval = $.trim(this.value);
    this.value = myval.replace(/^[0]+/g,"");

});

The above solution removes arbitrary leading zeroes, that part was taken from this answer to a similar question.

A: This can be cut down somewhat:
$('input[type=number]').each(function() {
    this.value = this.value.replace(/^\s*0+(?=\d)/, '');
});

That will remove any leading zeros, even if there's leading white space (which is probably your problem).

A: It looks like for some reason there is preceding whitespace - use jQuery's trim function before your zero-check to ensure you've eliminated the whitespace.


text:
Q: Omitting preposition after "see" Should I use "that (pronouns) were" instead of "(pronoun)" in the following example?

John, who was in a blind fit of rage when he found out that the organization had killed his parents, saw them dead (in his imagination).

This sounds unnatural, but these participles seem absolutely normal.

Even though I told him to stop, I still see him eating.
When I was sneaking through the streets, I saw him sleeping.

Are these correct? When is it necessary to put "that ____ were"?

A: Let's discuss the differences between several possible alternatives, starting with:

John, who was in a blind fit of rage when he found out that the organization had killed his parents...

*

*saw them dead in his mind

That's a bit awkward for what you're trying to say. Consider an example with the opposite - "John's mother was overjoyed to see him alive after coming back from war." What you probably want to say here is "imagined the sight of them dead", or "had a vision of them being dead". Consider also this example: "Steve's mother would always worry whenever he jumped on his motorcycle. No matter how hard she tried to repel bad thoughts, she always saw him dead in a ditch somewhere." Given that John's parents have already been killed and he knows it, the situation is no longer hypothetical like in that example, which is why the sentence sounds odd to me.

*

*saw that they were dead

That's talking about a witnessed event in the past, and would imply that John actually saw his dead parents in real life, and didn't just imagine the sight of it.

A: To see (see/saw/seen) has a couple of different meanings

*

*The most common meaning is "to be in one's sight" - I saw the park.

*A less common meaning is "to assist in doing" or "to make sure an activity was completed" - I saw our guest out the door.
Since the sentence talks about rage, a someone could think that "saw them dead" refers to an action John took in revenge, per the second meaning - especially if "in his imagination" is left out.

John, who was in a blind fit of rage when he found out that the organization had killed his parents, saw them dead (in his imagination).

The ambiguity is removed when you say "saw that they were dead" instead, because the object of saw is now a clause that is self-contained in meaning, and not just a dangling word which could be attached to something earlier in the sentence.


text:
Q: Optimal data streaming and processing solution for enormous datasets into tf.data.Dataset Context:
My text input pipeline currently consists of two main parts:
I. A complex text preprocessing and exporting of tf.SequenceExamples to tfrecords (custom tokenization, vocabulary creation, statistics calculation, normalization and many more over the full dataset as well as per each individual example). That is done once for each data configuration.
II. A tf.Dataset (TFRecords) pipeline that does quite a bit of processing during training, too (string_split into characters, table lookups, bucketing, conditional filtering, etc.).
Original Dataset is present across multiple locations (BigQuery, GCS, RDS, ...).
Problem:
The problem is that as the production dataset increases rapidly (several terabytes), it is not feasible to recreate a tfrecords files for each possible data configuration (part 1 has a lot of hyperparameters) as each will have an enormous size of hundreds of terabytes. Not to mention, that tf.Dataset reading speed surprisingly slows down when tf.SequenceExamples or tfrecords grow in size.
There are quite a few possible solutions:

*

*Apache Beam + Cloud DataFlow + feed_dict;

*tf.Transform;

*Apache Beam + Cloud DataFlow + tf.Dataset.from_generator;

*tensorflow/ecosystem + Hadoop or Spark

*tf.contrib.cloud.BigQueryReader

, but neither of the following seem to fully fulfill my requierments:

*

*Streaming and processing on the fly data from BigQuery, GCS, RDS, ... as in part I.

*Sending data (protos?) directly to tf.Dataset in one way or another to be used in part II.

*Fast and reliable for both training and inference.

*(optional) Being able to pre-calculate some full pass statistics over the selected part of the data.

*EDIT: Python 3 support would be just wonderful.
What is the most suitable choice for the tf.data.Dataset pipeline? What are the best practices in this case?
Thanks in advance!

A: I recommend to orchestrate the whole use case using Cloud Composer(GCP integration of Airflow).
Airflow provided operators which let you orchestrate a pipeline with a script.
In your case you can use the dataflow_operator to have the dataflow job spin up when you have enough data to process.
To get the data from BigQuery you can use the bigquery_operator.
Furthermore you can use the python operator or the bash operator to monitor and pre-calculate statistics.


text:
Q: scala - matching by datatype string and get its frequency I have the below datatype details from a hive table schema and need to get its frequency
val a = List("decimal(10,2)","string","string","decimal(6,0)",
              "timestamp","decimal(8)", "timestamp" )

val freq = a.map{
  x => x match {
    case  x.contains("decimal") => "decimal" // getting error here
    case "string" => "string"
    case "timestamp" => "date"
  }
}.groupBy(identity).mapValues(_.length)

println(freq)

I get error saying, cannot resolve symbol.. what is wrong with the code?.
I need the output as
Map(date -> 2, decimal -> 3, string -> 2)

If there are better ways to get the above output, that is also welcome

A: You can use a guard in the first pattern match to achieve what you are trying to do.
val freq = a.map{
  x => x match {
    case  x if  x.contains("decimal") => "decimal" // getting error here
    case "string" => "string"
    case "timestamp" => "date"
  }
}.groupBy(identity).mapValues(_.length)

A: You can also fold over the List.
val freq = a.foldLeft(Map[String,Int]().withDefaultValue(0)){
  case (m,s) if s.startsWith("decimal") => m + ("decimal" -> (m("decimal")+1))
  case (m,"timestamp") => m + ("date" -> (m("date")+1))
  case (m,str)         => m + (str    -> (m(str)+1))
}


text:
Q: How to avoid random strings from appearing repeatedly I like to display some strings from a string array in to a Textview, randomly. I am using the following code for that, But the problem is that most of the time some string is displayed repeatedly.What I want is the strings once displayed should not be displayed again.I have spent hours in searching for the code, but none of them work for me. Kindly help. Thanks in advance.
public void GetQuotes(View view) {
     Resources res = getResources();
            myString = res.getStringArray(R.array.Array);
            String q = myString[rgenerator.nextInt(myString.length)];
            TextView tv = (TextView)findViewById(R.id.textView1);
            tv.setText(q);

A: Java has built in array shuffling method, put all your items into a list, shuffle it randomly, and get the first element till it has elements. If empty, add all elements again, and shuffle again:
private List<String> myString;

public void GetQuotes(View view) {
    Resources res = getResources();
    if (myString==null || myString.size()==0) {
        myString = new ArrayList<String>();
        Collections.addAll(myString, res.getStringArray(R.array.Array));
        Collections.shuffle(myString); //randomize the list
    }
    String q = myString.remove(0);
    TextView tv = (TextView)findViewById(R.id.textView1);
    tv.setText(q);
}

A: I'd suggest either checking manually if it's been used before or use a set and then write the strings in that set.
http://developer.android.com/reference/java/util/Set.html

A: Arrays and Lists in general aren't designed to avoid duplicates, they're designed as a type of collection that maintains the order of a number of elements. If you want a collection more suited for the job then you want a set:
 Set<String> set = new HashSet<String>();

to avoid duplicates.

A: Here is a very simple solution.
Now while I am saying this tongue in cheek, if you want a simple solution, you can have a dedicated string variable that stores the last used question. Then it becomes very simple if you initialized it as an empty string. Say the variable is called last.
String q = myString[rgenerator.nextInt(myString.length)];
//q has a string which may or may not be the same as the last one
//the loop will go on until this q is different than the last
//and it will not execute at all if q and last are already different
while (last.equals(q))
{
    //since q and last are the same, find another string
    String q = myString[rgenerator.nextInt(myString.length)];
};
//this q becomes last for the next time around
last = q;

Now among a few other issues, a key thing to remember here is that this only makes sure that q[1] cannot follow q[1] but it does not entirely avoid a scenario of, just to be ridiculous, say q[1], q[2], q[1], q[2] and so on.
Here is one with ArrayList which is equally simple.
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
for (int i = 0; i < myString.length)
{
    list1.add(myString[i]);
}
q = (String)list1.get(rgenerator.nextInt(list1.size()));
list1.remove(q);
list2.add(q);
if (list1.isEmpty())
{
    list1.addAll(list2);
    list2.clear();
}


text:
Q: How to launch a tutorial on first app launch using SwiftUI? I would like to launch a tutorial when my SwiftUI app first launches. Where in the project should this code go and how do I launch the tutorial, which is just a SwiftUI View, when the app first launches?
I already know how to check if the app has launched before using UserDefaults. I am wanting to know how to launch the SwiftUI view and then how to launch the standard ContentView after the user completes the tutorial.
let hasLaunchedBefore = UserDefaults.standard.bool(forKey: "hasLaunchedBefore")

if hasLaunchedBefore {
     // Not first launch
     // Load ContentView here
} else {
     // Is first launch
     // Load tutorial SwiftUI view here
     UserDefaults.standard.set(true, forKey: "hasLaunchedBefore") // Set hasLaunchedBefore key to true
}

A: Try put this in your sceneDelegate
let hasLaunchedBefore = UserDefaults.standard.bool(forKey: "hasLaunchedBefore")
let content = ContentView()
let tutorial = TutorialView()
if let windowScene = scene as? UIWindowScene {
      let window = UIWindow(windowScene: windowScene)
       if hasLaunchedBefore {
           window.rootViewController = UIHostingController(rootView: content)
       } else {
           window.rootViewController = UIHostingController(rootView: tutorial)
           UserDefaults.standard.set(true, forKey: "hasLaunchedBefore")
       }
        self.window = window
        window.makeKeyAndVisible()
}

A: In your SampleApp which after SwiftUI 2.0:
import SwiftUI

@main
struct SampleApp: App {
  @AppStorage("didLaunchBefore") var didLaunchBefore: Bool = true
  let persistenceController = PersistenceController.shared

  var body: some Scene {
    WindowGroup {
      if didLaunchBefore {
        SplashView()
      } else {
        ContentView()
      }
    }
  }
}

Then add a button with action like below in SplashView:
UserDefaults.standard.set(false, forKey: "didLaunchBefore")


text:
Q: How do you prevent the tests from stopping on the first failed test case? I'm attempting to check if certain pieces of content are present, on different pages. For example:
const contentCount = Selector('.some-element').childElementCount

.expect(contentCount).gte(1, 'The related content is missing.')

... Which works fine, except that the testing stops after the first assertion fails. This isn't ideal as I'm trying to generate a report that shows ALL of the failed assertions at once.
How do I get the test to keep running after a failed assertion?

A: Answering your question from the subject first (how to prevent the test from stopping on the first failed test case).
TestCafe will run all tests even if one of them failed. You might want to split your single test case with multiple assertions into multiple test cases with a single assertion per test to obtain a proper report.
Now, answering your question from the body (how to keep running after a failed assertion).
At the moment, there is no way to skip a failed assertion during the test execution. TestCafe considers that something went wrong if an assertion failed, so the entire test fails. However, if you don't want an assertion to fail a test, you may add a condition for it; e.g.:
if (contentCount > 0)
  await t.expect(contentCount).gte(1, 'The related content is missing.')

But, this does not look like straight and predictable test logic. So, I would choose splitting a test into multiple tests with one assertion per test.
See also: TestCafe Assertions


text:
Q: User Profile multiple data sources Want some help understanding what I have to do in this situation.
We have user profiles from active directory, but there are some properties that come from an external service which we can get from a WCF service.
What is the best way to approach? I can't seem to understand how the stuff connect, I started doing a Business Data Model in Visual Studio but it's just becoming a big mess in my head.
EDIT
I want sharepoint only to import the data, and the data may be changed in WCF service data source.

A: Peter Holpar has a very good article on this topic as it relates to SharePoint 2010. Generally speaking, it's very much the same in SP 2013. If the property is just going to be populated once from the WCF service and then SharePoint will be the owner of the property (i.e. where people go to update it) then you do not need a BCS model or the sync connection. You could just write a script or console app that does a one time population of the properties in question.
If the WCF service's datasource is still going to be the canonical source for the data, then I would probably manually create the sync connection.
Process - No Code

*

*Create and deploy your BCS model. Your model must contain a property that maps to a unique identifier in AD. I used the SAM Account Name without the domain prefix, i.e. rkaucher not contoso\rkaucher.

*Create the sync settings/properties.

*

*From the Manage Profile Service page click Manage User Properties.

*On the User Properties page either find the property you wish to modify or add a new property. In this example I have chosen to edit the Department property. Most of these attributes are pretty self-explanatory.

*At the bottom of this page ensure that there is nothing listed under Property Mapping for Synchronization. If there is, click remove.

*

*Under Add new mapping select your BCS connection for Source data connection and then pick the property from the BCS entity that you wish to map to this user profile property. Don't forget to click add and then OK.

*Go back to the Manage Profile Service page and select Configure Synchronization Settings. Be sure that Include existing BCS connections for synchronization? is checked as in this image. I didn't do this initially and it took me 30 minutes to figure out what I was doing wrong.

*

*Once you have completed that final step you can return to the Manage Profile Service page and click Start Profile Synchronization. Once the sync completed you should see the new property/value on the About me section of the profile page if you have enabled that attribute when you configured the property.

Process - Server OM
Here is some example code for creating a property. This was kind of hard to get working. I created a simple console app to create the property and the connection. One issue that I had before I got it working was that I kept getting a NullReferenceException that was caused by a SecurityException because my account (the account running the code) was not configured in both the administrators and permissions sections of the User Profile Service in Central Admin.

At this point, I am so tired my eyes are spinning, so if there are any typos here, feel free to correct them, or add a comment and I will make the correction.
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Sharepoint;
using Microsoft.Sharepoint.Administration;
using System;

//Etc...
//Get a handle on the central admin site collection as site
SpServiceContext context = SPServiceContext.GetContext(site);
UserProfileConfignanager userProfileConfigManager = new UserProfileConfigllanager(context);
UserProfileManager userProfilemanager = new userProfileManager(context);
ProfilePropertytianager propManager = userProfileConfigManager.ProfilePropertylianager;
CorePropertyManager corePropManager = propManager.GetCoreProperties();

CoreProperty coreProp = corePropManager.Create(false);
//The bool above is for isSection, which this is not.
coreProp.Name = "MyBcsFullName";
coreProp.DisplayName = "MY BCS Full Name";
coreProp.Type = PropertyDataType.StringSingleValue;
coreProp.Length = 50;
coreProp.Commit();

//Obviously it's a user type
ProfileTypePropertyManager typePropManager = propManager.GetProfileTypeProperties(Profilerype.User);
ProfilesubtypePropertyManager subtypePropManager = userProfilemanager.DefaultProfileSubtypeProperties

ProfilesubtypeProperty subProp = subtypePropManager.Create(typePropManager.GetPropertyByName(coreProp.Name));
subProp.IsUserEditable = false;
subProp.DefaultPrivacy = Privacy.Public;
subtypePropManager.Add(subProp);

Connection connection = userProfileConfigManager.ConnectionManager["BCS Properties"];

if (connection != null)
{
    PropertyMapCollection propMapCollection = con.PropertyMapping;
    PropertyMap propMap = propMapCollection[subprop.Name];
    if (propertyMap == null)
    {
        propMapCollection.AddNewMapping(ProfileType.User, subProp.Name, "FullName");
        //The final param is the name of the property in the BCS model.
    }
}

To the right, you will see the property we added.


text:
Q: General TypeScript usage for modules / namespaces I have a standard web page (not an app rendered with angular, react, vue, etc) that uses jQuery, and other libraries.
I want to integrate good practices with TypeScript.
What is the best way to do this?
My current idea is to have 3 files:

*

*the index.d.ts (describes the types of my module)

*the test.ts (the implementation of the types described in the index.d.ts)

*the page.js (the file that uses the javascript defined in the test.js -- output from the test.ts)

I currently have these contents:
index.d.ts
// Type definitions for test 1.0.0
// Project: Test
// Definitions by: Author Name

/// <reference path="../../lib/@types/jquery/index.d.ts" />
declare namespace TestNS {
    export class TestClass {
        // Fields
        element: JQuery;
        value: string;

        constructor(element: JQuery, val: string);

        OnCreate();

        static AttachToJQuery(jq: JQueryStatic): void;
    }

    interface JQuery {
        TestClass(element: JQuery, val?: string): TestNS.TestClass;
    }

    interface JQueryStatic {
        TestClass(element: JQuery, val?: string): TestNS.TestClass;
    }
}

Test.ts (loaded 2nd, after jQuery)
/// <reference path="../../lib/@types/jquery/index.d.ts" />
/// <reference path="./index.d.ts" />

export namespace TestNS {
    export class TestClass {
        // Fields
        element: JQuery;
        value: string;

        constructor(element: JQuery, val: string) {
            this.element = element;
            this.value = val;
            this.OnCreate();
        }

        OnCreate() {
            this.element.data('test-value', this.value);
        }

        static AttachToJQuery(jq: JQueryStatic) {
            //no jQuery around
            if (!jq) {
                return false;
            }

            jq.fn.extend({
                TestNS: function(newVal) {
                    return this.each(function() {
                        var obj = jq(this);
                        new TestNS.TestClass(obj, newVal);

                    });
                }
            });
        }//attach to jquery method (to easily work with noconflict mode)
    }//test class
}

page.js (loaded last)
let newJquery:JQueryStatic = jQuery.noConflict();
TestNS.TestClass.AttachToJQuery(newJquery);

let testElems = newJquery(".testClass");
testElems.TestClass();

My goal is to have my code neatly organized into a namespace in typescript, as well as on the page (but doing so in typescript gives errors related to duplicate identifiers) as well as being modular and extensible. I understand that I should publish my types under the "node_modules/@types" directory, but I simply want them all encapsulated in this module for now.
I have tried using a module, and importing what is defined in the index.d.ts, but TypeScript says I cannot import this file, and that the module name cannot be found. I did learn that if I use a module, it should be accompanied with a loader, such as CommonJS, RequireJS or AMD, but I would prefer to avoid that for now (if it's not a horrible practice to do so, as I want to minimize the levels of complexity for now).
I've tried looking at other projects, but they all use a loader, which seems a bit overkill for this kind of script.
Is there a good way to go about this?

A: If you want to make things work without a module loader, you will have to make a few changes. First of all it's worth mentioning that TypeScript supports 2 primary ways of modularizing code, namespaces and modules.
NOTE: A slightly confusing nuance here is that the keywords namespace and module can be used interchangebly and don't by themselves determine whether a thing is a module or a namespace.
1) modules (formerly called external modules) - these use typical import, export, and require semantics and require a module loader and preferably a bundler of some sort. For this pattern, each file is considered a module. Any file that contains any import or export statements will be considered an external module by the TypeScript compiler.
2) namespaces (formerly called internal modules) - this pattern supports namespaces that can span multiple files. This is the module type that you would need to use if you don't want to use a module loader. Usage of this pattern is becoming less common, but it is still an option if you want to use it for whatever reason. To use this type of modularization, you can't have any import or export statements in the file.
Here's the docs on namespaces https://www.typescriptlang.org/docs/handbook/namespaces.html
Assuming you want to go with your original plan, you will need to tweak a couple of things in your code.
1) As mentioned by @sbat, your index.d.ts is re-declaring your namespace and class types. This is likely causing duplicate definition errors. You can replace the entire contents with a simple override of the JQuery interface.
/** Extend the JQuery interface with custom method. */
declare interface JQuery {
    TestNS: () => TestNS.TestClass
}

2) Make sure you don't have any top level exports or imports. Specifically you will want to remove the export from your namespace in test.ts. This will make your module an internal one instead of an external one.
namespace TestNS {
    export class TestClass {
        ...
    }
}

A: Assuming you want to just try TypeScript in a simple project, I'd suggest you simplify things a bit:

*

*Remove index.d.ts. Definition files describe existing javascript code, so that TypeScript is aware of types in it. You don't have this situation in your project, there is no need to repeat type information you have already in your test.ts, you can safely remove this file.

*Just build your test.ts into test.js. Make sure your jquery .d.ts is located where it should be.

*Remove page.js, just code everything in test.ts for a test. Once you make it work, you can reorganize it.
However, if your goal is to have your code modular and extensible, the recommended approach is to indeed use modules:

Starting with ECMAScript 2015, modules are native part of the
  language, and should be supported by all compliant engine
  implementations. Thus, for new projects modules would be the
  recommended code organization mechanism.

https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html
To use modules in production environment in the browser you will need:

*

*Bundler. A tool that will call TypeScript to build your individual TS modules, and then combine the build output into single javascript file. You will then include this single file into your HTML. WebPack is probably the easiest to start: https://webpack.js.org/concepts/

*Package manager. A tool that installs and manages versions of the third-party modules. https://www.npmjs.com/
This is a big area to study, but I don't think it is an overkill. If your code is modular (even if it is just 2 modules), you need an infrastructure to bundle and load your modules one way or the other. There are several options with different benefits and trade-offs, but there is fundamentally no way around that.


text:
Q: Could someone help me configure MinGW in SublimeText 3? (Newbie) I downloaded MinGW following the first link here https://isocpp.org/get-started and now I need to configure it in SubimeText 3. I know I should go to Tools > Build System > New Build System... But what should I specify there?
I use Win7x64. And MinGW is in C:\MinGW

A: The complete reference for build systems is here. The first thing you need to do is make sure that the C:\MinGW\bin directory is in your PATH, then restart Sublime so the change gets picked up.
Once you've done that, create a new build system with the following contents:
{
    "cmd": ["gcc", "${file}", "-o", "${file_base_name}.exe"],
    "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
    "working_dir": "${file_path}",
    "selector": "source.c, source.c++",
    "shell": true,

    "variants":
    [
        {
            "name": "Run",
            "cmd": ["start", "cmd", "/k", "${file_path}/${file_base_name}.exe"],
            "shell": true
        }
    ]
}

and save it as Packages/User/C.sublime-build where the Packages folder is the one opened by selecting Preferences -> Browse Packages....
You can now choose this build system by selecting Tools -> Build System -> C. Once you are ready to compile, save your source file, then hit CtrlB to build. To run the program, hit CtrlShiftB and a cmd window will open up to run the resulting .exe file, then stay open until you close it (so you can see any output produced by the program).
You can try to use the C++ build system that comes with Sublime, but some users have run into issues with it in the past, especially on Windows, so this custom one may suit your needs better.
Good luck!


text:
Q: Testing typescript asyc functions, Async callback was not invoked even though it's called in .then() method I've been searching around for a while for a resolution to this but can't find anything, the only thing I can think of is redux-mock-store doesn't support Promises.
I have this test method below.
import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';
import { cleanAll } from 'nock';

var middleware = [thunk];
var mockStore = configureMockStore(middleware);

describe('Organisation thunk actions', () => {
    afterAll(() => {
        cleanAll();
    });

    describe('getOrganisation', () => {
        test('should create BEGIN_GET_ORGANISATION_AJAX action when getting organsation', (done: any) => {
            jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
            var expectedAction = [{ type: types.BEGIN_GET_ORGANISATION_AJAX }];
            var store = mockStore({});
            store.dispatch<any>((OrganisationActions.getOrganisation("e"))).then(() => {
                var actions = store.getActions();
                expect(actions).toEqual(expectedAction);
                done();
            });
        });
    });
});

This is designed to test the action below.
export const getOrganisation = (organisationId: string, expands?: string[]) => {
    return (dispatch: any) => {
        dispatch(beginGetOrganisationAjax());
            return OrganisationApi.getOrganisationAsync(organisationId).then((organisation: any) =>     {
            dispatch(getOrganisationSuccess(organisation))
        }).catch(error => {
            throw (error);
        });
    }
}

Where OrganisationApi.getOrganisationAsync(organisationId) is a call to a mockApi that I know works from usage.
When I run this test it fails twice after the 30s DEFAULT_TIMEOUT_INTERVAL specified, once as expected (as I've designed the expect to) but the second failure is an error "Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.".
Unless I'm mistaken, the async callback is the done() function invoked after the expect(actions).toEqual(expectedAction) within the .then() function in the test.
As the expect fails the .then() is definitely running but doesn't seem to be running the .done() function, can anyone see why this might be happening?

A: Finally figured out the issue, posting the resolution in case someone has a similar problem.
The Async callback is never called as the test function quits out as soon as it comes across the failing expect() statement, therefore it never actually runs the done() function in this instance.
Once this test passes it calls the done() function and my tests pass.


text:
Q: Excel File with ODBC connection I have an excel file which has an ODBC connection to SQL server. It works fine on my computer because I have ODBC connection set up on mine.
But When I send the file to other people they can not connect coz they have no ODBC set up on their machine.
My question is, Is there a way to embed the connection in the excel file itself? So they don't need to setup ODBC.
Thanks in advance.
T

A: You could consider using a ODBC file DSN instead of a registry created DSN...
You can then ship the file DSN (something.dsn) along with your Excel spreadsheet.
As long as Excel is configured to look in the location the file DSN is placed - all should be OK...

A: I'd use Andy Khan's JExcel to read and manipulate the Excel file rather than JDBC and the ODBC driver.  No installation needed, but you will have a JAR dependency.


text:
Q: Unable to delete a 21 Mb attachment I created a 21 Mb attachment to test some code I was writing. Later I saw that my DE org ran out of file storage and it wont let me save any new records (even when the data storage is 40%). I deleted all the attachments there were using the dev console anonymous execute
delete [select Id from Attachment];

When I went to the Storage Usage page I can still see 1 attachment record left with the 21 Mb size. When I clicked the link Overall Top Files by Storage Utilization, it took me to a page where all the files were listed

When I click the file name it takes me to a page where it says

When I run a select query on Attachment in the dev console, it says 0 results. I do not understand why this attachment is not shown in the query and how do I delete it if I cannot even access it.
Thank you.


text:
Q: Retrieving Specific Financial Statements in Quantmod I am currently working in the quantmod package and wish to retrieve some financial statements. I am having an issue specifying what type of financial statement I want. By default it retrieves the Annual BS.
tickers <-new.env()
s <-c(list of tickers...)
lapply(s, getFinancials, env=tickers)
FS <-data.frame(lapply(tickers, viewFinancials)

When I do attempt to specify the FS, it gives me the error message of either saying 'x' must be type of financials or since I"m using lapply it won't recognize it as a function. I do like using lapply for this because it puts the financial statements in a data frame and in the exact format that I like, I just want to do it for the Annual IS.
Thank you!

A: This code works and not only includes the BS, but the IS and CF as well:
Input:
tickers <-new.env()
t <-c("AAL",  "AAME", "AAOI")
lapply(t, getFinancials, env=tickers)
BS <- data.frame(lapply(tickers, function(x) {viewFinancials(x, type= 'BS', period = 'A')}))
IS <- data.frame(lapply(tickers, function(x) {viewFinancials(x, type= 'IS', period = 'A')}))
CF <- data.frame(lapply(tickers, function(x) {viewFinancials(x, type= 'CF', period = 'A')}))

Output:
> tickers <-new.env()
> t <-c("AAL",  "AAME", "AAOI")
> lapply(t, getFinancials, env=tickers)
[[1]]
[1] "AAL.f"

[[2]]
[1] "AAME.f"

[[3]]
[1] "AAOI.f"

> BS <- data.frame(lapply(tickers, function(x) {viewFinancials(x, type= 'BS', period = 'A')}))
Annual Balance Sheet for AAME
Annual Balance Sheet for AAL
Annual Balance Sheet for AAOI
> IS <- data.frame(lapply(tickers, function(x) {viewFinancials(x, type= 'IS', period = 'A')}))
Annual Income Statement for AAME
Annual Income Statement for AAL
Annual Income Statement for AAOI
> CF <- data.frame(lapply(tickers, function(x) {viewFinancials(x, type= 'CF', period = 'A')}))
Annual Cash Flow Statement for AAME
Annual Cash Flow Statement for AAL
Annual Cash Flow Statement for AAOI

?viewFin or ?viewFinancials would have shown you the possible options/arguments for viewFinancials.


text:
Q: Selection with xPath (PHP) I have this XML code :

Pays de production : Hongrie

I am trying to retrieve "Hongrie", I tried this :
//img[contains(@title, 'Pays de production')]

That just select the img, and when I try :
//img[contains(@title, 'Pays de production')]//strong//a

This just returns false


text:
Q: Python 3 email body encoding I am working on setting up a script that forwards incoming mail to a list of recipients.
Here's what I have now:
I read the email from stdin (that's how postfix passes it):
email_in = sys.stdin.read()

incoming = Parser().parse(email_in)

sender = incoming['from']
this_address = incoming['to']

I test for multipart:
if incoming.is_multipart():
    for payload in incoming.get_payload():
        # if payload.is_multipart(): ...
        body = payload.get_payload()
else:
    body = incoming.get_payload(decode=True)`

I set up the outgoing message:
msg = MIMEMultipart()
msg['Subject'] = incoming['subject']
msg['From'] = this_address
msg['reply-to'] = sender
msg['To'] = "foo@bar.com"
msg.attach(MIMEText(body.encode('utf-8'), 'html', _charset='UTF-8'))

s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

This works pretty well with ASCII characters (English text), forwards it and all.
When I send non-ascii characters though, it gives back gibberish (depending on email client bytes or ascii representations of the utf-8 chars)
What can be the problem? Is it on the incoming or the outgoing side?

A: The problem is that many email clients (including Gmail) send non-ascii emails in base64. stdin on the other hand passes everything into a string. If you parse that with Parser.parse(), it returns a string type with base64 inside.
Instead the optional decode argument should be used on the get_payload() method. When that is set, the method returns a bytes type. After that you can use the builtin decode() method to get utf-8 string like so:
body = payload.get_payload(decode=True)
body = body.decode('utf-8')

There is great insight into utf-8 and python in Ned Batchelder's talk.
My final code works a bit differently, you can check that, too here.


text:
Q: How to create a table with 2 panels, each one separate page? I wish to create a table with 2 independent panels. Both panels are big enough, so I have to put them on two different pages.What should I do?
\documentclass[12pt]{article}
\usepackage{subcaption}
\usepackage{booktabs}
\begin{document}
\begin{table}[bp]
\caption{\label{tab:summary}\textbf{Summary Statistics}
{\small
Some sentences. }}
\subcaption*{Panel A: Summary Statistics of 21 Commodity Futures}
{\small
\begin{tabular}{p{1.1in}rp{1in}lp{0.5in}p{0.5in}p{0.5in}p{0.5in}p{0.5in}}
\hline\hline\\[-5pt]
Commodities & Start Date & Price Unit & Exchange & Spot Price \newline Mean     & Spot Price \newline STD & Con. Yield \newline Mean & Con. Yield \newline STD & Number\newline of Obs. \\
\hline\\[-5pt]
Chicago Wheat & 02/01/1990 & cents/bushel & CME & 446.8  & 179.2  & -18.8  & 60.6  & 1,238  \\
Kansas Wheat & 02/01/1990 & cents/bushel & KCBT  & 471.7  & 188.9  & -2.3  & 65.2  & 1,308  \\
Corn  & 02/01/1990 & cents/bushel & CME & 331.6  & 152.7  & -5.6  & 45.8  & 1,318  \\
Oats  & 27/11/1990 & cents/bushel & CME & 205.1  & 93.2  & -2.8  & 38.5  & 1,277  \\
Soybeans & 02/01/1990 & cents/bushel & CME& 806.7  & 323.2  & 39.6  & 75.2  & 1,294  \\
Soybean Oil & 02/01/1990 & cents/pound & CME & 29.4  & 11.9  & 0.0   & 1.9   & 1,316  \\
Soybean Meal & 02/01/1990 & dollars/metric ton & CME & 248.4  & 97.9  & 20.8  & 32.2  & 1,209  \\
Crude Oil & 02/01/1990 & dollars/barrel & NYMEX & 45.0  & 31.2  & 1.6   & 4.5   & 1,221  \\
Heating Oil & 02/01/1990 & cents /gallon & NYMEX & 134.3  & 94.3  & 1.7   & 13.2  & 1,277  \\
Natural Gas & 27/01/1992 & dollar/MMBtu & NYMEX & 4.2   & 2.5   & -0.1  & 0.9   & 1,109  \\
Cotton & 02/01/1990 & cents/pound & ICE   & 68.7  & 23.9  & 1.8   & 13.0  & 1,308  \\
Orange Juice & 02/01/1990 & cents/pound & ICE   & 114.6  & 35.2  & -2.3  & 12.1  & 1,255  \\
Cocoa & 02/01/1990 & dollars/ton & ICE   & 1764.1  & 750.6  & -31.1  & 84.0  & 1,317  \\
Sugar & 02/01/1990 & cents/pound & ICE   & 12.4  & 5.8   & 0.5   & 1.9   & 1,305  \\
Coffee & 02/01/1990 & cents/pound & ICE   & 118.2  & 50.8  & -4.1  & 17.9  & 1,327  \\
Platinum & 02/01/1990 & dollars/troy ounce & NYMEX & 846.0  & 495.8  & 19.5  & 46.9  & 1,308  \\
Palladium & 02/01/1990 & dollars/troy ounce & NYMEX & 359.4  & 241.8  & 6.6   & 21.8  & 1,322  \\
Copper & 02/01/1990 & cents/pound & NYMEX & 177.6  & 112.8  & 7.7   & 13.6  & 1,265  \\
Lean Hogs & 02/01/1990 & cents/pound & CME & 64.0  & 18.1  & 1.9   & 15.1  & 1,242  \\
LiveCattle & 02/01/1990 & cents/pound & CME & 87.9  & 25.4  & 2.0   & 8.7   & 1,255  \\
Feeder Cattle & 30/01/1990 & cents/pound & CME& 104.1  & 37.8  & 4.0   & 11.6  & 1,291  \\

\hline\hline
\end{tabular}}
\newpage
\subcaption*{Panel B: Summary Statistics of 12 Agricultural Commodity Futures (Sample Mean)}
   \begin{tabular}{p{1.1in}p{0.35in}p{0.35in}p{0.6in}p{0.6in}p{0.8in}p{0.8in}p{0.8in}p{0.6in}}
\hline\hline\\[-5pt]
Commodities & Long  & Short  & Long/OI \newline (\%) & Short/OI \newline (\%) & Spot Price\newline RW-STD & Con. Yield\newline RW-STD & Net Long\newline RW-STD & Number\newline of Obs \\
\midrule
\multicolumn{1}{c}{Chicago Wheat} & 199.0  & 25.8  & 38.9  & 5.0   & 36.9  & 15.6  & 4.8   & \multicolumn{1}{c}{495} \\
\multicolumn{1}{c}{Kansas Wheat} & 40.4  & 2.5   & 26.4  & 1.5   & 37.3  & 16.0  & 1.7   & \multicolumn{1}{c}{495} \\
\multicolumn{1}{c}{Corn} & 428.0  & 50.8  & 24.7  & 2.9   & 25.8  & 11.4  & 11.0  & \multicolumn{1}{c}{495} \\
\multicolumn{1}{c}{Soybeans} & 165.8  & 21.6  & 23.3  & 2.7   & 50.0  & 23.0  & 4.9   & \multicolumn{1}{c}{491} \\
\multicolumn{1}{c}{Soybean Oil} & 89.3  & 8.4   & 25.4  & 2.3   & 1.7   & 0.3   & 3.0   & \multicolumn{1}{c}{493} \\
\multicolumn{1}{c}{Cotton} & 76.4  & 5.5   & 29.4  & 2.0   & 4.4   & 2.9   & 2.6   & \multicolumn{1}{c}{493} \\
\multicolumn{1}{c}{Cocoa} & 27.8  & 2.7   & 15.2  & 1.4   & 113.6  & 35.1  & 1.5   & \multicolumn{1}{c}{496} \\
\multicolumn{1}{c}{Sugar} & 278.5  & 46.8  & 29.5  & 4.8   & 1.1   & 0.6   & 8.0   & \multicolumn{1}{c}{485} \\
\multicolumn{1}{c}{Coffee} & 47.1  & 3.6   & 25.1  & 1.8   & 8.0   & 1.8   & 1.5   & \multicolumn{1}{c}{496} \\
\multicolumn{1}{c}{Lean Hogs} & 85.7  & 3.7   & 35.4  & 1.4   & 4.5   & 5.7   & 2.7   & \multicolumn{1}{c}{494} \\
\multicolumn{1}{c}{LiveCattle} & 112.2  & 3.2   & 32.4  & 0.8   & 3.0   & 3.3   & 2.6   & \multicolumn{1}{c}{498} \\
\multicolumn{1}{c}{Feeder Cattle} & 7.7   & 0.6   & 20.3  & 1.6   & 3.8   &      3.1   & 0.4   & \multicolumn{1}{c}{495} \\
\bottomrule

\end{tabular}%

\end{table}

\end{document}

A: See, if this provide what you looking for:
\documentclass[12pt]{article}
\usepackage[font=small,
            labelfont={sf,bf},
            textfont={sf},
            justification=centering,
            ]{caption}
\usepackage{subcaption}
\usepackage[group-four-digits = true]{siunitx}
\usepackage{booktabs,makecell,tabularx}
\usepackage[a4paper, margin=20mm, showframe]{geometry}

\begin{document}
\begin{table}[bp]
    \setlength{\tabcolsep}{4pt}
    \small
\caption{\textbf{Summary Statistics} Some sentences. }
    \label{tab:summary}
\subcaption*{Panel A: Summary Statistics of 21 Commodity Futures}
\begin{tabularx}{\textwidth}{@{}lXll
         S[table-format=4.1]
         S[table-format=3.1]
    *{2}{S[table-format=2.1]}
         S[table-format=4.0]}
    \toprule
\makecell[b]{Commodities} & \makecell[b]{Start Date}
    & \makecell[b]{Price Unit} & \makecell[b]{Exchange}
        & {\makecell[b]{Spot\\ Price\\ Mean}}
            & {\makecell[b]{Spot\\ Price\\ STD}}
                & {\makecell[b]{Con.\\ Yield\\ Mean}}
                    & {\makecell[b]{Con.\\ Yield\\ STD}}
                        & {\makecell[b]{Num.\\ of Obs.}}  \\
    \midrule
Chicago Wheat & 02/01/1990 & cents/bushel & CME & 446.8  & 179.2  & -18.8  & 60.6  & 1238  \\
Kansas Wheat & 02/01/1990 & cents/bushel & KCBT  & 471.7  & 188.9  & -2.3  & 65.2  & 1308  \\
Corn  & 02/01/1990 & cents/bushel & CME & 331.6  & 152.7  & -5.6  & 45.8  & 1318  \\
Oats  & 27/11/1990 & cents/bushel & CME & 205.1  & 93.2  & -2.8  & 38.5  & 1277  \\
Soybeans & 02/01/1990 & cents/bushel & CME& 806.7  & 323.2  & 39.6  & 75.2  & 1294  \\
Soybean Oil & 02/01/1990 & cents/pound & CME & 29.4  & 11.9  & 0.0   & 1.9   & 1316  \\
Soybean Meal & 02/01/1990 & dollars/metric ton & CME & 248.4  & 97.9  & 20.8  & 32.2  & 1209  \\
Crude Oil & 02/01/1990 & dollars/barrel & NYMEX & 45.0  & 31.2  & 1.6   & 4.5   & 1221  \\
Heating Oil & 02/01/1990 & cents /gallon & NYMEX & 134.3  & 94.3  & 1.7   & 13.2  & 1277  \\
Natural Gas & 27/01/1992 & dollar/MMBtu & NYMEX & 4.2   & 2.5   & -0.1  & 0.9   & 1109  \\
Cotton & 02/01/1990 & cents/pound & ICE   & 68.7  & 23.9  & 1.8   & 13.0  & 1308  \\
Orange Juice & 02/01/1990 & cents/pound & ICE   & 114.6  & 35.2  & -2.3  & 12.1  & 1255  \\
Cocoa & 02/01/1990 & dollars/ton & ICE   & 1764.1  & 750.6  & -31.1  & 84.0  & 1317  \\
Sugar & 02/01/1990 & cents/pound & ICE   & 12.4  & 5.8   & 0.5   & 1.9   & 1305  \\
Coffee & 02/01/1990 & cents/pound & ICE   & 118.2  & 50.8  & -4.1  & 17.9  & 1327  \\
Platinum & 02/01/1990 & dollars/troy ounce & NYMEX & 846.0  & 495.8  & 19.5  & 46.9  & 1308  \\
Palladium & 02/01/1990 & dollars/troy ounce & NYMEX & 359.4  & 241.8  & 6.6   & 21.8  & 1322  \\
Copper & 02/01/1990 & cents/pound & NYMEX & 177.6  & 112.8  & 7.7   & 13.6  & 1265  \\
Lean Hogs & 02/01/1990 & cents/pound & CME & 64.0  & 18.1  & 1.9   & 15.1  & 1242  \\
LiveCattle & 02/01/1990 & cents/pound & CME & 87.9  & 25.4  & 2.0   & 8.7   & 1255  \\
Feeder Cattle & 30/01/1990 & cents/pound & CME& 104.1  & 37.8  & 4.0   & 11.6  & 1291  \\
    \bottomrule
\end{tabularx}
    \end{table}

\begin{table}[bp]
\ContinuedFloat
    \setlength{\tabcolsep}{4pt}
    \small
\caption{\textbf{Summary Statistics}}
\subcaption*{Panel B: Summary Statistics of 12 Agricultural Commodity Futures (Sample Mean)}
\begin{tabularx}{\textwidth}{@{}X
%         S[table-format=3.1]
    *{8}{S[table-format=3.2]}
%         S[table-format=1.1]
%         S[table-format=3.1]
%    *{2}{S[table-format=2.1]}
%         S[table-format=3.0]
                @{}}
    \toprule
\makecell[b]{Commodities}   & {\makecell[b]{Long}}  & {\makecell[b]{Short}}
    & {\makecell[b]{Long/\\OI (\%)}} & {\makecell[b]{Short/\\OI (\%)}}
        & {\makecell[b]{Spot Price\\ RW-STD}}
            & {\makecell[b]{Con. Yield\\ RW-STD}}
                & {\makecell[b]{Net Long\\ RW-STD}}
                    & {\makecell[b]{Number\\ of Obs}}      \\
    \midrule
Chicago Wheat & 199.0  & 25.8  & 38.9  & 5.0   & 36.9  & 15.6  & 4.8   & 495 \\
Kansas Wheat & 40.4  & 2.5   & 26.4  & 1.5   & 37.3  & 16.0  & 1.7   & 495 \\
Corn & 428.0  & 50.8  & 24.7  & 2.9   & 25.8  & 11.4  & 11.0  & 495 \\
Soybeans & 165.8  & 21.6  & 23.3  & 2.7   & 50.0  & 23.0  & 4.9   & 491 \\
Soybean Oil & 89.3  & 8.4   & 25.4  & 2.3   & 1.7   & 0.3   & 3.0   & 493 \\
Cotton & 76.4  & 5.5   & 29.4  & 2.0   & 4.4   & 2.9   & 2.6   & 493 \\
Cocoa & 27.8  & 2.7   & 15.2  & 1.4   & 113.6  & 35.1  & 1.5   & 496 \\
Sugar & 278.5  & 46.8  & 29.5  & 4.8   & 1.1   & 0.6   & 8.0   & 485 \\
Coffee & 47.1  & 3.6   & 25.1  & 1.8   & 8.0   & 1.8   & 1.5   & 496 \\
Lean Hogs & 85.7  & 3.7   & 35.4  & 1.4   & 4.5   & 5.7   & 2.7   & 494 \\
LiveCattle & 112.2  & 3.2   & 32.4  & 0.8   & 3.0   & 3.3   & 2.6   & 498 \\
Feeder Cattle & 7.7   & 0.6   & 20.3  & 1.6   & 3.8   &      3.1   & 0.4   & 495 \\
    \bottomrule
\end{tabularx}%
    \end{table}
\end{document}

As you can see, I heavily reformat your table. First I split it into two table, where for second one I use \ContinuedFloat option from caption package which suppress incrementing table number (both are "Table 1".
I use tabularx for fitting it in text with, for columns with numbers I use S column type from siunitx package, in column headers I use thead from makecell package. I also reduce inter column space (from default 6 pt to 4 pt) and omit all your use of \multicolumn{1}{c}{...}.
Temporary are both tables in one page since there is no other text. When  it will be present, LateX will push second table to new page. With selection float option `[b] you can obtain that both tables are at bottom of pages.


text:
Q: Trying to concatenate Sass variable and a string I'm trying to concatenate a Sass variable with a string. How do I do it?
Below there is a code example.
@mixin setIcons($pathImages:$pathImages, $extensionIcon:$extensionIcon {
   @each $class-icon in $class-icons-30 {
     .snw-tui-icon-#{$class-icon} {
       @include icon($class-icon, $pathImages, $extensionIcon, 30px);
   }
     .snw-tui-icon-**#{$class-icon} + "selected"** {
       @include icon(**$class-icon + "selected"**, $pathImages, $extensionIcon, 30px);
  }
}

A: You want to interpolate.
$sidebar-width: 20px;

.target {
     width: calc(100% - #{$sidebar-width});
}

Hope this helps
More info into it here: https://webdesign.tutsplus.com/tutorials/all-you-ever-need-to-know-about-sass-interpolation--cms-21375

A: For a font variable, this is what worked for me:
$font-family-sans-serif:      -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol" !default;
$font-family-custom: 'My Custom Font', #{$font-family-sans-serif}

Good Luck


text:
Q: Задача с использованием событий У меня есть боковая меню с установленным стилем margin-left: -240px;.Как при клике сделать чтобы она выдвигалась и при втором клике задвигалась???

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Chat</title>
  <link rel="stylesheet" href="style/style.css">

A:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Chat</title>
  <link rel="stylesheet" href="style/style.css">

A: <!DOCTYPE html>

     <meta charset="UTF-8">
     <title>Chat</title>
     <link rel="stylesheet" href="style/style.css">

A: Вот ответ на ваш вопрос.

function scrolMenu() {
  var main = document.getElementById('menu');
  main.classList.toggle("menu0");
};
#menu{
  margin-left:50px;
}
#menu.menu0{
  margin-left: 0;
}

    <meta charset="UTF-8">
    <title>Chat</title>
    <link rel="stylesheet" href="style/style.css">

MARGIN MENU

Лучше не менять сам стиль с помощью javascript.
А дать стиль отдельному классу, и когда элемент имеет этот класс то на него подействует определенный стиль, а если нет то будет изначальный стиль.
А с помощью javascript просто добавить и удалить класс.
И что бы каждый раз не морочить голову есть ли класс у элемента или нет. (что бы понять добавить при клике или удалить) есть такой хороший метод toggle.
Берем элемент.(Это вы делали), потом возьмем его классы с помощью classList, А после этого применяем метод ՝toggle՝.
Этот метод добавляет класс если его нет, а если есть удаляет.

A: сделайте чтобы по клику добавлялся/удалялся какой-нибудь класс, а дальше если есть класс margin-left: 0px; иначе margin-left: -240px; также под этот класс можно подвязать и другие изменения стилей:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Chat</title>
  <link rel="stylesheet" href="style/style.css">


text:
Q: Update variable in the background so I'm currently writing a Flask application and I am new to flask.
There is some processing going on, which I outsourced to a separate function.
As this processing takes some time, I wanted to give the user a progress update on how many iterations have passed. No problem so far.
However, as soon I call the render template, the function ends and I cannot update that variable anymore.
I was imagining an if loop. if that variable changes, render template with the new variable as input.
But after the first iteration, the if loop will brake.
Currently, the render template renders an html function, which just displays the variable it receives. I want to update that variable as soon as it changes.
Do you guys have any suggestion, on how I could achieve this "background update"?
Cheers and thanks!

A: You need some kind of ongoing request/response cycle.
As soon as your app sends the response with the rendered template back to the browser, this connection is closed and there's no way to send any more data.
There's a few things that need to happen in order to accomplish what you want:

*

*The long running function needs to run in the background so it doesn't block execution of the rest of the application

*There has to be a way to get a status update from the long running function

*The client (ie browser) needs a way to receive the status updates

1 and 2 can be solved using celery. It allows you to run tasks in the background and the task to send information via a side channel to be consumed elsewhere.
The easiest way to achieve 3 would be to set up a route in your flask application that returns information about the task, and request it periodically from the browser using some JavaScript. The more favorable method in my opinion would be to use websockets to actively send out the information to the client, but this is a bit more complicated.
This is just a rough outline, but there's a tutorial by Miguel Grinberg about how to set this up using celery and polling from JS.


text:
Q: Kendo Datasource - Backbone - Changes made to backbone model not syncing in datasource I have a number of instances where my Kendo Datasource <-> Backbone connection is working as expected, but I have run into a situation that I hope someone knows more about.
When a model or collection is synced from the server, the datasource is also updated and respective Kendo controls are also updated.
However, if you already have a collection loaded, and you loop through that collection, making a change to the models in that collection, it appears that the linked DataSource is not getting the changes.
Example:
I have a collection of "tags" that are displayed as checkbox options. I want to display some of those checkboxes as "checked" based on other data coming from the server (in this case, I am loading a product - and want to display what colors are selected):
this.colors.each(function (me) {
  me.set('selected', '');
  if ( _.findWhere(self.model.get('colors'), {id: me.id} ) ) {
    me.set('selected', 'checked');
  };
})

$('#colors').kendoListView({
  dataSource: this.colors_datasource,
  template: '
<input type="checkbox" value="#: id #" #:selected#> #: name #
'
});

The 'this.colors_datasource' is defined in the initialize method of this backbone view. It is not seeing these changes being made to the backbone models in the collection "this.colors". I presume that this is because the models are not syncing to the server.
If I add the definition between these two blocks of code, it works:
this.colors.each(function (me) {
  me.set('selected', '');
  if ( _.findWhere(self.model.get('colors'), {id: me.id} ) ) {
    me.set('selected', 'checked');
  };
})

this.colors_datasource = new kendo.Backbone.DataSource({
  collection: this.colors
});

$('#colors').kendoListView({
  dataSource: this.colors_datasource,
  template: '
<input type="checkbox" value="#: id #" #:selected#> #: name #
'
});

So, my question: Is this the only solution, or is there a way to tell an already defined DataSource to rebuilt itself?
Thanks - StackOverflow Rocks!

A: I'm guessing there is a timing issue. Perhaps, in the case where it's not working, the datasource is being initialized incorrectly?
The code you provided at the bottom is how you should do it. From the docs you can read the kendo.Backbone.DataSource is providing the magic to get the 2-way binding. Without this the kendo ui does not know about the change events coming from the backbone collection. They provide sample code there that's very similar to what you've suggested here.
I also wanted to comment on this line:

I presume that this is because the models are not syncing to the server.

One of the beautiful things about the Backbone.Events system: it does not require a round-trip to the server in order for the UI to keep in sync with changes. As long as you handle the basic collection events add, remove, change, etc. you can keep your interface up to date without talking to your server.


text:
Q: Collecting polygon features from many people with simple online form? I work at a transportation consulting firm that works over a large geographic area with dispersed offices. We'd like to develop a database of the locations of our projects, so that we can easily find relevant past projects when starting new work. I'm trying to figure out if this is something we can do using arcgis online.
What I'd like would be a feature service that includes polygons for each project, with attributes for an identifying number and some other information. It would need to be collaborative, so that anyone in the company can contribute features. Ideally, I'd like to create a simple form that others in the company could access through a webpage to submit project info.  This page would use a "draw on the map" input to create shapes, and have some fields for the attributes.
Separately, I'd like to have a map with all features on it that could be queried by users.
I'm familiar enough with collecting features into a feature service using ArcGIS Collector on mobile, and displaying the results on a map or using the service layer in ArcMap. However, there are a few items I'm unsure about:

*

*Is there a web-based method for collecting features? (something simpler and more error-resilient than editing a map through the arcgis online interface)

*Could it be used without logging into arcgis online?

*Could it be embedded in another webpage, possibly on an intranet?

I'm not sure if this functionality is something that's currently available in arcgis online, or if it would require arcgis server, or if I should be looking outside the esri universe.

A:
1) Is there a web-based method for collecting features? (something simpler and more error-resilient than editing a map through the arcgis online interface)

Honestly, the ArcGIS Online interface for editing is pretty straight forward in my opinion, but you could use one of their application templates (i.e. the Editor application) if you feel it offers a more intuitive interface.  To do this, add your Feature Service into an ArcGIS Online map.  Save it, and share it by making a web application.  You will see a listing of templates to choose from, and Editor should be on the first page.  You can also download the template if you'd like to customize the application style.

2) Could it be used without logging into arcgis online?

Sure, all you have to do is share the feature service, map and application with Everyone.  That may or may not work for purposes but that is one way to get around the login.

3) Could it be embedded in another webpage, possibly on an intranet?

Absolutely.  When you choose to share your map, you can choose the Embed in Application option to get an iframe object of the map document.  Now if you want editing capabilities you will need to either create your own application, or if you create one using the Edit application, simply add the iframe to an existing webpage, just change the SRC URL to the Edit application.
src="http://my.arcgis.com.domain/apps/Edit/index.html?appid=r232lk24l234j2l34kj23l4k"
Here is a very quick JSFIDDLE showing how this can be done.
Earlier in your post you say:

Ideally, I'd like to create a simple form that others in the company could access through a webpage to submit project info. This page would use a "draw on the map" input to create shapes, and have some fields for the attributes.

If you need people to write/modify attributes of the feature service outside of a map, you'll need to query and post to the service.  You can access the service URL in ArcGIS Online by going to the Feature Service description page and clicking on the drop down arrow next to the layer.

I know there is a lot of information in this post, but it should point you in the right direction for making your web map application.


text:
Q: How to populate a html 5 date input I have a modal that opens with form data to be edited. Everything populates correctly except the date input. When I put a date in there it saves and updates fine so is it a format issue? The input field is showing mm/dd/yy when the modal opens.
plunkr
<label style="margin-left:296px">Date:</label>
                                            <input style="width:150px" ng-model="currentItem.ChangeOrderDate" type="date" />

A: You should convert the string to date object before populating.
$scope.currentItem = {ChangeOrderDate  : new Date('2014-08-27T07:41:43.803')};

Plnkr


text:
Q: "The JSON request was too large to be deserialized" MVC KnockoutJs I've been scrapping the threads for an answer in similar threads with no luck.
I am using knockoutJS to pass the information back from my partial view and I am getting the "The JSON request was too large to be deserialized".
I have done the   " " fix but this isn't helping.
My page has quiet a bit of information to pass back in the forms of lists,  and I believe this is why I am getting the errors on this page and not others where I am using  knockout.
I have read that I can build my own serializer but that in itself can lead to more problems.
Would anyone be able to suggest alternatives?
One thing I was trying to find out is if I can stop passing back the whole lists and only pass back the selected values, but I can't seem to find any more information on this .
TIA

A: I added the key below and it worked for me.
<appSettings>
    <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>

A: This may be by design.... to protect the site from DoS attacks or time-out conditions
There is an app setting for MaxJsonDeserializerMembers which you may be able to increase, but would need to be done with care: ...JSON payload members fails with an exception
What I have done in the past is to either break up the forms into (collapsible) sections and doing AJAX posts by group, or spreading the form out over multiple pages. Front end users generally will be happier if anything as they don't see the gazillion fields at once.

A: I've had the same error message when I returned partial view via ajax call. It turned out that the problem was in the partial - "Object Reference not set to an instance of an object".
@User.Address.Address1

The "Address" was null. Fixed that by doing some checks
@if(User.Address != null){
   @User.Address.Address1
}


text:
Q: How to Restrict AWS AMI access to certain user? I just have created an AWS EC2 AMI for my EC2 instance.
I wanted to give restriction to that AMI(user level,not account level).
For example User1 have created AMI named ami-123.
User1,User2,User3 are present in that account.
I want only User1 should have permission to create EC2 instance using ami-123.
Please help me to sort it out?

A: By default, users in an AWS Account have no permissions to do anything.
You then grant them permissions for actions they are allowed to call, such as RunInstances.
As part of these permissions, you can restrict the permissions they are receiving, such as the AMI they can specify:
arn:aws:ec2:region::image/*

See: Resource-Level Permissions for RunInstances
Alternatively, you could ALLOW RunInstances but then create a policy to DENY use of a particular AMI.


text:
Q: django form submissionr return non "post" page I have a select box and an input box that submits to a view in django.
When I submit it adds the value in django then the page reloads and the select box values are updated.
However if I press 'refresh' on that page, it tries to resubmit values again. How can I prevent this behavior, I would like the refresh after the POST to be a normal refresh of the page as if no POST had been submitted previously.
localhost/project/myview/3/3

I am trying to do a "return HttpResponseRedirect(reverse("myview"), firstid=3, secondid=3)"
But it does not seem to be working, is this the right way of doing it and how do I fix this?

A: HttpResponseRedirect only takes one parameter. You need to pass the id parameters to reverse:
return HttpResponseRedirect(reverse("myview", kwargs={"firstid": 3,
    "secondid": 3}))


text:
Q: Wordpress Multisite Internal Links I am trying to make a Wordpress Multisite network with domain mapping, and I am using nginx as the webserver.
The master blog URL is www.xenon-corporation.com, that works fine.
I can create subdomains just fine, such as teste.xenon-corporation.com.
I can even map the domains such as www.vinerz.net.
But the internal links on the page still point to the old subdomain vinerz.xenon-corporation.com and not the new domain www.vinerz.net.
What am I doing wrong?

A: WP Multisite stores domain names all over the database...
table wp_options*: option_name 'siteurl' and 'home'
table wp_site: each row has domain and path columns
table wp_sitemeta: meta_key 'siteurl'
table wp_blogs: each row has domain and path columns
* and there is a wp_#_options table for each site you have in your network...


text:
Q: CSS backface-visibility not showing on cardflip in a parent div I am trying to make an opening book animation with CSS transitions similar to a card flip animation except with another card behind it.
When I create a single card flip it works fine in chrome. But if I put it inside a parent div in order to place another card behind it the back of the card no longer shows.
HTML

              Front!!!
I don't work

              Back!!!
Can you see me?

CSS
.scene {
  margin-left: 200px;
  perspective: 6000px;
}
.turncard {
  width: 200px;
  height: 200px;
  margin-top: 50px;
  transform-style: preserve-3d;
}
.turncard-front {
  height: inherit;
  width: inherit;
  transition: transform 0.6s;
  transform-origin: top left;
}
.turncard-side {
  height: inherit;
  width: inherit;
  position: absolute;
  backface-visibility: hidden;
  background-color: green;
  text-align: center;
}
.turncard-outside{
  z-index: 1;
}
.turncard-inside {
  transform: rotateY(180deg);
  z-index: -1;
}
.turncard-front:hover {
  transform: rotateY(180deg);
}

Both the working version (without a parent div) and non-working example (with the div) are shown in this fiddle: http://jsfiddle.net/bxLa4kwu/1/

A: Stick this property on .turncard2-front:
transform-style: preserve-3d;

http://jsfiddle.net/bxLa4kwu/3/
This property tells it to preserve the 3D position of children of the turncard2-front element (e.g. inside and outside of the page) when turncard2-front is css transformed.
Be aware this doesn't work in IE11 as the property isn't supported (but you probably knew that as the first example doesn't work either in IE).


text:
Q: Can I use the WiFi drivers on Ubuntu on a VM? I have an Windows 8.1 computer that I am getting the "Limited connection" error on WiFi networks, even when I have two, three, or even four bars. After talking to support for a bit, they told me that it wasn't compatible with 8.1, yet that the drivers would be available in a few short weeks.
Since I already have it and it isn't returnable anymore I want to try to install Linux in a VM so I can temporarily use it without having a bunch of software to remove when it's ready. However, if I do so, wouldn't it still use Window 8.1's drivers since it is a VM? Is there any way I can transfer "ownership" of the network card to Ubuntu? I can't really install Wubi since I cannot get onto WiFi at all.

A: No, unfortunately you cannot. The VirtualBox manual on PCIE Passthrough states, in its first line:

When running on Linux hosts, with a recent enough kernel (at least version 2.6.31) experimental host PCI devices passthrough is available.

A number of further restrictions, even for Linux systems, are then described. Nowhere is mention made of Windows.
Sorry to have to break the bad news.


text:
Q: Difference between preprocessor macros and std::source_location There are some predefined preprocessor macros (specified in C and C++ standard) like __line__ and __file__ which are replaced by line number and file name during preprocessing respectively. In C++20, a new class std::source_location is introduced which does more or less the same thing.
So, my questions are...

*

*What are the differences between them?

*What are their advantages and disadvantages?

*Which one I should use for which reason?

A: Preprocessor macros live outside the type system. Preprocessor macro substitution happens outside the rest of the language. See this answer and this answer for a comprehensive discussion of the disadvantages of using the preprocessor.
std::source_location on the other hand behaves like any other C++ struct. It has plain value fields that are typed and behave like any other values in the language.
Besides that, functionality-wise the two mechanisms are equivalent. There is nothing that the one can achieve that cannot be done by the other (apart from the column field in source_location, which has no equivalent in the preprocessor). It's just that the new approach achieves its goals more nicely.


text:
Q: Finding the highest value in a column for a given range in another column I'm quite new to pandas and dataframes. I want to find the product ('product') from a dataframe that gave the highest income ('income') in the years ('year') 1990 to 1999.
My best attempt only gives me the row number from the dataframe and the income, although I want it to show all other columns as well.
This was my best attempt:
HighestIncome90s = df.head(1)
HighestIncome90s = df.loc[(df['year'] >= 1990) & (df['year'] <= 1999), 'income'].nlargest()

A: Let us try fixed your code with sort_values
df = df.sort_values('income',ascending=False)

HighestIncome90s = df
HighestIncome90s = df.loc[(df['year'] >= 1990) & (df['year'] <= 1999), 'income'].head(1)

If you would like get all column
Allcol = df.loc[(df['year'] >= 1990) & (df['year'] <= 1999),].head(1)

A:
I want it to show all other columns as well.

If you use
idxmax,
as in
max_income_idx = df.income[(df['year'] >= 1990) & (df['year'] <= 1999)].idxmax()

then it will be the index of the largest relevant income. You can then use it with df.loc[max_income_idx, :] to get all columns for that.

A: As I understood, your source DataFrame contains income data for
each product and year, something like:
    year product  income
0   1980      P1  120.15
1   1990      P1  120.15
2   1992      P1  140.20
3   1994      P1  160.51
4   1996      P1  171.04
5   1988      P2  140.17
6   1991      P2  145.17
7   1993      P2  160.42
8   1995      P2  181.73
9   1989      P3  140.17
10  1992      P3  175.17
11  1994      P3  240.42
12  1996      P3  315.73

But you are interested only in rows for year between 1990 and 1999.
Then, you want to sum the income for each product (for the whole 10 year period).
The code to do it is:
wrk = df.query('year.between(1990,1999)').groupby('product').income.sum()

For the time being, for the above source data, we have the following
Series:
product
P1    591.90
P2    487.32
P3    731.32
Name: income, dtype: float64

(the left column is the index and the right - total income for each
product).
And to get the final result (the "best-seller" product and the total income
that it brought) run:
result = wrk.sort_values(ascending=False).head(1)

It is also a Series, but containing only one element:
product
P3    731.32
Name: income, dtype: float64

(P3 is the index and 731.32 is the total income).
All other solutions (presented so far) give the biggest income for
a single year (within the period of interest), not the total
income in this period.

A: First Step : this code use to limit the year from 1990 to 1999
df = df.query('year >= 1990 & age <= 1999')

Second Step : after that use this code to sort income from the highest value
df = df.sort_values('income', ascending=False)


text:
Q: Git local branch out of date, but nothing to pull? I have a problem with git branch called nightly in my repo. When I was trying to git push to branch I got an error:
 ! [rejected]        nightly -> nightly (non-fast-forward)
 error: failed to push some refs to 'https://github.com/Martin819/quoll.git'
 hint: Updates were rejected because a pushed branch tip is behind its remote
 hint: counterpart. Check out this branch and integrate the remote changes
 hint: (e.g. 'git pull ...') before pushing again.
 hint: See the 'Note about fast-forwards' in 'git push --help' for details.

I have already run into this problem several times, so I thought the solution is straight forward. I had to git pull.
But, when I tries to git pull it says:
 * branch            nightly    -> FETCH_HEAD
 Already up to date.

So I tried to check the status with git remote show origin and got:
  HEAD branch: master
  Remote branches:
    master    tracked
    nightly   tracked
  Local branches configured for 'git pull':
    master  merges with remote master
    nightly merges with remote nightly
  Local refs configured for 'git push':
    master    pushes to master    (up to date)
    nightly   pushes to nightly   (local out of date)

I'm now confused, because there it says that local branch is out of date, but when trying to pull it says Already up to date. Anyway how to solce this?

A: OK, problem solved. I have accidently checkouted to 'nigthly' branch instead of 'nightly' creating a new local branch, which caused this problem. After chechout to the branch the problem disappeared.


text:
Q: Pure Javascript - Add the value of text input to
* when button clicked/enter-key I'm a very new user of Javascript and I'm having trouble with getting the value of a user's input when you click the button or hit enter.  Here is what I have so far, it does indeed add things to the li but it doesn't accept the value.
I'd like this to all be in pure JS (not jQuery).
Here is my HTML

I'd like to bind here

  <input type="text" class="theplayer" name="Player" id="bind" value="Player-name" />
  <input type="button" id="thego" value="Go" />

And my JS
const el = document.getElementById('bind');
const gobutton = document.getElementById('thego')
let nameOfPlayer = el.value;
gobutton[window.addEventListener ? 'addEventListener' : 'attachEvent']( window.addEventListener ? 'click' : 'onclick', myClickFunc, false);
function myClickFunc()
  {
    var x = document.createElement("LI");
    var t = document.createTextNode(nameOfPlayer);
    x.appendChild(t);
    document.getElementById("teammateys").appendChild(x);
  }

Here is a demo https://jsfiddle.net/sthig/hhuw0rtr/
Thanks for you help and listening to me get my head around the js verbiage correctly!

A: This isn't really an issue with "binding"--there's no such concept in vanilla JS.
Instead you need to make sure that you're grabbing the value of the text field when the onclick handler is called:
function myClickFunc()
  {
    var currentValue = document.getElementById("bind").value;
    var x = document.createElement("LI");
    var t = document.createTextNode(currentValue);
    x.appendChild(t);
    document.getElementById("teammateys").appendChild(x);
  }

You can also reduce this to:
function myClickFunc()
  {
    var x = document.createElement("li");
    x.textContent = document.getElementById("bind").value;
    document.getElementById("teammateys").appendChild(x);
  }


text:
Q: shape draw in imageview I am trying to follow
http://developer.android.com/guide/topics/graphics/2d-graphics.html
and draw a shape on top of the imageview
my class is
package com.bayer.glucofacts;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.widget.ImageView;

public class CustomDrawableImageView extends ImageView {
 private ShapeDrawable mDrawable;

 public CustomDrawableImageView(Context context) {
  super(context);
  int x = 10;
  int y = 100;
  int width = 300;
  int height = 50;
  mDrawable = new ShapeDrawable(new OvalShape());
  mDrawable.getPaint().setColor(0xff74AC23);
  mDrawable.setBounds(x, y, x + width, y + height);
 }

 protected void onDraw(Canvas canvas) {
  mDrawable.draw(canvas);
 }
}

and did xl like
<com.cmp.app.CustomDrawableImageView
  android:id="@+id/bg_image" android:src="@drawable/book"
  android:layout_width="wrap_content" android:layout_height="wrap_content" />

but this crashes my app when i doo setContnetLayout in onCreate of the activity
when i was doing only ImageView without extending it for canvas drawing, it was working fine.
whats the problem ?
basically i plan to draw an image and a few lines on top of the image. how to do this ?

A: to solve this problem you must change your constructor to
public CustomDrawableImageView (Context context, AttributeSet attrs) {
    super(context, attrs);
}

it will work


text:
Q: Auto scroll sections web site I am trying to autoscroll through the sections, but it only works in s1 and s3. According to how I think the code should work, s3 should jump to s2, but it jumps to s1 instead. wheel events do get picked up, I checked with alert(); All other lines of code do get executed. It is the scrollTop does not work, probably because of the layout, but I can not spot the problem. I would appreciate any clues. Thank you!

        ☰

CompanyX Goes All in With React Native

Starting in 2018, CompanyX Engine will support React Native.

A: I don't know your css setting, but normally we use the following code to force window scroll to the element. Make sure use html and body to animate scroll function. You can replace the following code to your event.
$("html, body").animate({
    scrollTop: $("#s2").offset().top - $(".header").height() //Base on your stcky header, you need to minus the header height
},1000 /*scroll in ms*/);

Edit: Minus Header Height for you
You must not animate the scrolling on a div, it should not work.


text:
Q: submenu inside li affecting due to style of li on active of a I have li menu and inside that , there is a submenu again for li.
Now on change of a of main li, when I change style of li , its affecting to all submenus as well.
Is there any solution?
Thanks

A: I would use one of these selectors:

*

*CSS .class Selector - http://www.w3schools.com/cssref/sel_class.asp

*CSS #id Selector - http://www.w3schools.com/cssref/sel_id.asp

*CSS3 :nth-child() Selector - http://www.w3schools.com/cssref/sel_nth-child.asp
Please, read more about CSS selectors here:
http://www.w3schools.com/cssref/css_selectors.asp


text:
Q: What is the quickest and easiest way to run a small php script on my html page? What is the quickest and easiest way to run a small php script on my html page and what do I need to do to get it running? I'm asking because I use html and css all the time, but have never done anything in php. I'll be using it to create an email form that doesn't open an email client to send it.

A: First, your host needs to support PHP.  Most do.
Make a basic script like this:
<?php
    mail('your@email.com', 'Some Subject', print_r($_POST, true));
?>

Then, build yourself an HTML form that points to this script...
<form action="yourscript.php" method="post">
    <input type="text" name="SomeField" />
    <input type="submit" name="submit" value="Submit" />
</form>

That's all there is to it.  HOWEVER, this is problematic.  You will get spam.  You need to implement CAPTCHA and such.  Otherwise you will get e-mails all the time, even if someone just hits this script with their web browser and no POST data.
Read a tutorial and learn some PHP.  It will help you in the long run.
There is also a great form example on tizag.com that will help you understand the components at work here.  Basically, you have an HTML form with a few fields (SomeField, submit) and when someone submits this form it will send the data to yourscript.php via the POST method.  The PHP script can then read the data in the $_POST array.  PHP has a convenient mail() function that is great for sending basic e-mail messages.  The print_r() function is used to show everything in an array, such as $_POST.

A: well, the form itself is html, your form will post ( or GET) to your php script and this will send the email and show output.
To execute the php script you need a webserver that supports php (IIS with the php module, apache with php module etc). Your webserver will host the script and then will execute it and return the output to the browser.
Also you need access to an SMTP server in order to send the email.
Look at php mail for basic usage, and mostly pear mail for a more complete solution ( including smtp auth).

A: You need to have php installed and configured properly with your server. Then it's as easy as this:
<?php
echo 'Hello World';
?>
Edit: Also, you may need to use the file extension .php on the page you are trying to run the script on. For example index.php - It may or may not work if the extension is .html
Does that work? If so you are ready to make your script. If not please provide more information about your hosting environment.

A: The .php file is translated just like a normal HTML page if you don't use the opening tag for PHP (), so you can just have normal HTML, and put the PHP somewhere on the page in tags.


text:
Q: How can one determine the index of a character clicked within a TextArea in JavaFX? I want to write an event handler for a TextArea which upon the user clicking on the TextArea can determine the index of the character clicked and act based on this.
The suggested solutions in Get cursor position (in characters) within a text Input field are Javascript instead of Java and do not answer how to convert mouse click coordinates to a text index.
Currently I have:
private EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent mouseEvent) {

            int x=(int)mouseEvent.getX();
            int y=(int)mouseEvent.getY();

            String type=mouseEvent.getEventType().toString();

            if(type=="MOUSE_CLICKED")
            {
                System.out.println("Mouse clicked over textarea at x="+x+" y="+y);

                // TODO

                // determine text index under click
            }
        }
    };

TextArea my_textarea=new TextArea();
my_textarea.setOnMouseClicked(mouseHandler);

A: My solution:
 private EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent mouseEvent) {

            int x=(int)mouseEvent.getX();
            int y=(int)mouseEvent.getY();

            String type=mouseEvent.getEventType().toString();

            if(type.equals("MOUSE_CLICKED"))
            {
                System.out.println("Mouse clicked over textarea at x="+x+" y="+y);

                System.out.println("Caret position: "+my_textarea.getCaretPosition());
            }

        }

    };

...
TextArea my_textarea=new TextArea();
my_textarea.setOnMouseClicked(mouseHandler);


text:
Q: jsPDF - HTML to PDF is not showing SVG (chart) While converting whole HTML body to PDF, SVG showing blank area. Actually I am exporting Plotly charts to PDF.
I think SVG is not supported in jsPDF. But looking for the suggestions.
Here is the code that i used:-
var doc = new jsPDF('p', 'pt', 'a4');

doc.addHTML(document.body, function () {
    doc.save('sample-file.pdf');
});


text:
Q: Unit testing modules in app/utils for an ember-cli app Calling moduleFor on "util:transforms" appears to work,
however .subject is undefined.
The test file that I have got so far is:
import { test, moduleFor } from 'ember-qunit';
import TransformUtil from 'myapp/utils/transforms';

moduleFor('util:transforms', "Unit - TransformUtil");

test("Exists", function(){
  expect(1);
  ok(this.subject() instanceof TransformUtil);
});

Doing the same thing for other type of modules,
e.g. "routes:index", appears to work without issue;
the app/utils folder appears to be treated differently.

A: Utilities (app/utils) are not identified by the resolver, so you need to do a manual import. As the Ember CLI documentation states:

All modules in the app directory can be loaded by the resolver but typically classes such as mixins and utils should be loaded manually with an import statement.

So you should remove the first parameter to moduleFor and then just use the imported TransformUtil object in your tests.


text:
Q: Which kinds of objects are worth destroying for fragments? When just raging for a while and destroying objects, it's pretty clear that different kinds of destructible objects provide different number of blue fragments. Pieces of walls and masonry, for instance, seem to provide none, while potted plants always net a few fragments.
I don't think I want to invest the time in destroying every single object in the hope in will get me shards, but I don't want to miss out on "valuable" objects, either. Is there some sort of guideline or chart which would indicate which objects I would want to destroy and which ones I can skip?
I realize the types of objects change between levels, but even a rough guideline will do.

A: After almost two playthroughs, here are my observations:
Objects that give notable fragments are objects that are man-made and could be considered to 'hold' something. This includes:

*

*crates

*barrels

*wagons

*shop booths

Objects that don't give fragments are usually natural or man-made but used as fencing.
Occasionally, I see something break this rule, but rarely does it give a significant amount of fragments. For example, I think there are some bones that give fragments. However, they don't give many. I've started ignoring anything that doesn't match my first rule in my "time vs. reward" calculation.
As a side note, the most abundant sources of fragments are not objects at all. Instead, they are:

*

*Vigils

*Who Knows Where

*The Shield challenge

*Monsters (especially with Idols active)

I've also noticed that I've been getting 2.5k shards after every level in New Game Plus where I place a shard in the monument. That was also when I activated 8/10 idols. I haven't tried disabling the idols to see if there is a correlation. At the time, I was level 7 or 8 and didn't have my weapons fully upgraded.


text:
Q: Unbind texture bound using ID3DXEffect->SetTexture I've got a bit of a problem when using the FX framework to bind textures to samplers using the FX framework:
ID3DXEffect->SetTexture(FXShadowtex,Lights->sunlight->ShadowTex)

Once that texture is bound to a sampler I'm not allowed to render to it again (let's say, when the sun changes position). When I do, this errors comes up:

Direct3D9: (WARN) :Can not render to a render target that is also used as a texture. A      render target was detected as bound, but couldn't detect if texture was actually used in rendering.

However, I can't find out how to 'unset' a texture using the FX framework or anything else reliably. I've tried a few things:

*

*ID3DXEffect->SetTexture(FXShadowtex,NULL). This causes a crash.

*ID3DXEffect->SetTexture(FXShadowtex,SomeDummy). This is really ugly.

*Find out which sampler index corresponds with the sampler defined in the fx files after compilation, and set that to NULL: IDirect3DDevice9->SetTexture(i,NULL). This is obviously not very practical.

*Forget about the warning. This makes the D3D debug output useless thanks to the endless amounts of spam, and too is quite ugly.

*Before doing any rendering, loop from zero to the number of samplers defined in the fx files, and set them all to NULL. This is ugly too.

Is there any other approach that I'm forgetting about? Explaining why any of the above 'solutions' are a necessary evil would be fine too. :)

A: Find out which texture unit is bound to that sampler uniform (see ID3DXEffect class on msdn), then simply unset the texture with IDirect3DDevice9::SetTexture().
I think this solution is the least ugly in this case. However, you can always write your own effect class (which is pretty straightforward btw).
Use for example D3DXCompileShaderFromFile then you can go through the returned constant table and set uniform values with IDirect3DDevice9::SetPixelShaderConstantF. Note that  matrices are set column-major in this case (which means you have to multiply the vector from the left in the shader). An effective solution is to allocate a continous space for the constants and set them in one call.


text:
Q: How to have a single regular expression that contains two regexs separated by an "or" condition so that my text validates to these two only? I want to use two regular expressions for my textbox and out of the two I want only one to be used at a time based on some condition?
Is there any way I can form a single regular expression which contains an "or" in it without requiring me to explicitly set an "or" in my code?
The two expressions are:
^[0-9]+$

i.e. use only digits
^[A-Za-z]{6}[0-9LMNPQRSTUV]{2}[A-Za-z]{1}[0-9LMNPQRSTUV]{2}[A-Za-z]{1}[0-9LMNPQRSTUV]{3}[A-Za-z]{1}$

i.e. use the format ABCDEF23G45D786Z.
Thanks

A: the | character signifies an OR.
((first regex statement)|(second regex statement))


text:
Q: How can I scrape Steam Market history? I was wondering if someone could give me a few hint on how to scrape efficiently steam market's history? I know there is an API but I can't seem to find a way to extract all the SM history of an item. For exemple, for any item, i'd like to be able to extract things such as ' numbers of items ' sold on the 12th of December 2018 and their average price.
if you take a look at :
https://steamcommunity.com/market/listings/730/G3SG1%20%7C%20Green%20Apple%20(Factory%20New)
I'd like to scrape all the values from the graph.
I'd love to get some pointers, on how to start etc, especially regarding efficiency of the process. There is a lot a data to be scraped (not the whole market ofc but still). I'd really appreciate the input of someone who's used to that.
Thanks a lot
edit :
this request supposedly gives the market history of an item but I can't seem to be getting anything. Anyone else experienced that? (some simpler requests such as priceoverview work just fine though)
https://steamcommunity.com/market/pricehistory/?country=US&currency=1&appid=730&market_hash_name=Glove%20Case%20Key

A: So basically you can use this request to get the data needed :
"https://steamcommunity.com/market/pricehistory/?appid=[gameID]&market_hash_name=[HTTP_ITEM_NAME]"
with gameID being 730 for CSGO for example
and HTTP_ITEM_NAME : the item name converted to http
ex :
★%20StatTrak™%20Shadow%20Daggers%20%7C%20Stained%20%28Field-Tested%29
full request :
https://steamcommunity.com/market/pricehistory/?appid=730&market_hash_name=%E2%98%85%20StatTrak%E2%84%A2%20Shadow%20Daggers%20%7C%20Stained%20%28Field-Tested%29


text:
Q: Artifacts when recycling Android view objects I am introducing view object recycling into my Android app to help performance.  It does help with that.  But when a new screen appears, I am seeing brief artifacts which I assume are related to the prior state of the views.  The artifacts take the form of a rectangular region of some color that should not be there.  The app adjusts itself to the correct state very quickly, but it's still annoying.  I am wondering if there is a way to prevent this.  What I am currently doing is removing the old view from the hierarchy and un-setting its event handlers.  Obviously, that is not enough.  LayoutParams typically relate a view to its parent; perhaps I need to be somehow "un-laying-out" the view when removing it?  But I'm not sure how to do that.

A: If your performance issues lay in a ListView, you can use RecyclerView instead to help that: https://developer.android.com/training/material/lists-cards.html.
Besides that, how exactly are you recycling and what type of Views do you use?


text:
Q: covariance of the integral of brownian motion over disjoint intervals Let $W_i = \int_{t_{i-1}}^{t_i} B(t) \,dt$ be the integral of Brownian motion over the time $t \in [t_{i-1},t_i]$. I'm reading a paper which says that $W_i$ and $W_j$ are independent Gaussian random variables. I can see why they're both Gaussian but it is not clear to me that they are independent.
If I look at $E[W_i W_j]$ for $j>i$, clearly the intervals $[t_{i-1},t_i]$ and $[t_{j-1},t_j]$ are disjoint. So $E[W_i W_j] = \int_{t_{i-1}}^{t_i}\int_{t_{j-1}}^{t_j} E[B(s)B(t)] \,ds \,dt$.
$E[B(s)B(t)] = s$ considering that $i < j$ and so the interval  $[t_{j-1},t_j]$ has larger values than  $[t_{i-1},t_i]$. Now, I don't see the double integral being zero!
I am missing out on something here?
Edit: paper here:

A: You're not missing anything; those are not independent.  In fact, as your post suggests, they're positively correlated which makes quite a bit of intuitive sense.  Is it possible that there's a term missing that you cut out?  If we instead defined $$W_i' = \int_{t_{i-1}}^{t_i} B(t) \,dt - (t_i - t_{i-1}) B_{t_{i-1}}$$ then you'd be looking at independent Gaussians.  Perhaps this is what the paper was saying (or what they meant to say)?

A: In this paper, $W_t$ isn't a Brownian motion.  It's a "white noise excitation" or more simply just a "white noise", and it's integral $$B_t=\int_0^t W_s ds$$ is the corresponding Brownian motion.
So, the paper is making the fairly uncontroversial claim that independent increments of a Brownian motion are independent Gaussians.
Note that there are various ways of making the meaning of the integral above precise.  One common one is to take the white noise $W_s$ to be defined by its integral (or rather by the integrals $\int W_t$ and $\int W_t^2$ over intervals or something similar) and side-step the question of what the white noise function $W_t$ is exactly.


text:
Q: Best algorithm for equal division number between column with ratio I have some number like this table:
+--------+-------------+-------------+------------+------------+
| e      | d           | c           | b          | a          |
+--------+-------------+-------------+------------+------------+
| 170000 | -228253.968 | -415460.317 | 124047.618 | 349666.667 |
+--------+-------------+-------------+------------+------------+

I want best algorithm to find how much should the negative columns add to the positive columns so that all columns become zero?
for example:
c (349666.667) to a (now c = -65793.65 & a = 0 )
d (170000) to e (now d = -58253.968 & e = 0)
c (65793.65) to b ( now c = 0 & b = 58253.968)
e (58253.968) to b ( now e = 0 & b = 0)

A: I am not quite sure what you are trying to ask, however from what I can understand it seems as if you want to know the best way to get all of the columns to equal zero after adding and subtracting them from each other.
The most efficient way that I can think of to accomplish this would be as follows.
For every row add the complete value of that row to the next row.
+--------+-------------+-------------+------------+------------+
| e      | d           | c           | b          | a          |
+--------+-------------+-------------+------------+------------+
| 170000 | -228253.968 | -415460.317 | 124047.618 | 349666.667 |
+--------+-------------+-------------+------------+------------+

d = d + e
+--------+-------------+-------------+------------+------------+
| e      | d           | c           | b          | a          |
+--------+-------------+-------------+------------+------------+
| 0      | -58253.968  | -415460.317 | 124047.618 | 349666.667 |
+--------+-------------+-------------+------------+------------+

c = c + d
+--------+-------------+-------------+------------+------------+
| e      | d           | c           | b          | a          |
+--------+-------------+-------------+------------+------------+
| 0      | 0           | -473714.285 | 124047.618 | 349666.667 |
+--------+-------------+-------------+------------+------------+

b = b + c
+--------+-------------+-------------+-------------+------------+
| e      | d           | c           | b           | a          |
+--------+-------------+-------------+-------------+------------+
| 0      | 0           | 0           | -349666.667 | 349666.667 |
+--------+-------------+-------------+-------------+------------+

a = a + b
+--------+-------------+-------------+-------------+------------+
| e      | d           | c           | b           | a          |
+--------+-------------+-------------+-------------+------------+
| 0      | 0           | 0           | 0           | 0          |
+--------+-------------+-------------+-------------+------------+

This method assumes that the sum of all of the rows is equal to zero just as the table you provided. Again, the question was not very well formatted so this is just a guess as to what I think you wanted to be solved.