text:
Q: Как отловить событие другого скрипта? Есть фотогалерея на JS. Которая показывает обычным пользователям фоточки в модальном окне. Надо сделать, чтобы у админа в этом же окне добавлялись некоторые кнопочки (например "отметить человека").

Думал при загрузке страницы проверять права юзеров, и, если зашел админ, подключать еще один JS-файл, который добавляет функционал. Т.е. при нажатии на миниатюру фотки, должна вызываться дополнительная функция из другого файла, которая добавит необходимые элементы.

Терзают смутные сомненья. Точно ли это сработает, да и вообще - хорошая это мысль, или есть более адекватные варианты.
A: Сработать вроде должно, если не накосячить :)
Вообще идея не часто встречаемая. Думаю по таким критериям можно определиться:

*

*дополнительного функционала для админа много? Ради одной кнопочки огород не стоит городить.

*Если есть разные права - т.е. админ, модер и т.д., то удобно будет подключать - одному одну библиотечку, другому - другую.

Вообще помните: лишние подключение к серверу - лишняя нагрузка. В основном на сервер и чу-чуть на пользователя. С другой стороны ваш вариант удобнее. Так что выбирайте что вам важнее:

*

*если оптимизация, то альтернативы

*если удобство в коде, как для программиста, то ваше решение

A: Слегка не понял, в чём именно. Если проблема в реализации, то есть как сделать так, чтобы какой-то код выполнялся при каком-то событии модуля, то решение довольно простое. В самом модуле должна быть какая-то пустая функция, которую можно будет подменить.
//конфигурация модуля
onSomeMethod=function(){};
//код модуля
function someEvent(){
    onSomeMethod();
    //код события
}

А в другом скрипте, который грузится после загрузки первого, подмените нужную функцию:
onSomeMethod=function(){
    //нужный вам код
}

Разумеется, функции и переменные не отдельные, а как свойства/методы нужного обьекта.
Если проблема более абстрактна, danpetruk всё описал выше.


text:
Q: Storage Audio in Sqlite in newfolder I use thus code and it works fine with me
String fileName = Environment.getExternalStorageDirectory() +"/Music/Diary.flac";

Music folder is already exist is SD card , I want to  make folder New Folder created automatically in SD card , I tried something like that
String fileName = Environment.getExternalStorageDirectory() +"/NewFolder/Diary.flac";

but it's not working

A: You need to create a directory first. Try this:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/NewFolder", "/Diary.flac");
    file.getParentFile().mkdir();
    if(!file.exists()){
        try {
                  file.createNewFile();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Default JsonNetSerializer does not camel case property names I'm injecting a custom serializer using NEST.JsonNetSerializer like this
var settings = new ConnectionSettings(connPool, sourceSerializer: JsonNetSerializer.Default);

When I was using the built in serializer it camel cased the property names for me (from snake case) automatically. How can I make the custom serializer work the same way? I see that I can use ConnectionSettings.DefaultFieldNameInferrer() to specify how property names are inferred. But it seems unneccessary to copy the NEST code to make it work as before.
The only reason I'm not using the built-in serializer is because I have to work with dynamic models, and the internal JSON.NET objects in NEST are inaccessible.


text:
Q: Tutorial on DOM parser Hi I had been looking for good tutorial on DOM parser more than an hour, but couldn't find not even one. so can anyone help me with good tutorial on DOM parser.

A: Working with XML on Android - it got all options of parsing including examples.


text:
Q: Video captured from x11grab is not playable in HLS format on Firefox/Safari I'm trying to produce an HLS playlist from a video file.
It's a file captured from a virtual screen with ffmpeg and x11grab module:
ffmpeg -y -t 10 -copyts -draw_mouse 0 -framerate 24 -f x11grab -thread_queue_size 1024 -i :0 -f pulse -i default -acodec copy /tmp/test_preprocessed.mkv

But when I'm trying to produce HLS from this file, the output seems not correct, as it doesn't play in Firefox/Safari, but does play in Chrome (using hls.js or https://www.hlsplayer.net/ for example)
Original file: https://transfer.sh/y1a6Fv/735171b9-42a1-461a-a118-981119bdf74e_preprocessed.mkv
HLS Playlist generated from this file: https://video-staging-bucket.ams3.digitaloceanspaces.com/c08584ca-4731-4820-b5c7-71f12955c0b2/stackoverflow/playlist.m3u8
(Works in https://www.hlsplayer.net/ with chrome, doesn't works with Firefox/Safari)
How I'm producing the HLS:
ffmpeg -y \
  -t 10 \
  -i 735171b9-42a1-461a-a118-981119bdf74e_preprocessed.mkv \
  -r 24 \
  -filter_complex '[0:v]split=3[v1][v2][v3]; [v1]scale=w=1280:h=720[v1out]; [v2]scale=w=854:h=480[v2out]; [v3]scale=w=640:h=360[v3out]' \
  -map '[v1out]' -c:v:0 libx264 -x264-params "nal-hrd=cbr:force-cfr=1" -b:v:0 3200k -maxrate:v:0 3200k -minrate:v:0 2500k -bufsize:v:0 3200k -preset slow -g 48 -sc_threshold 0 -keyint_min 48 \
  -map '[v2out]' -c:v:1 libx264 -x264-params "nal-hrd=cbr:force-cfr=1" -b:v:1 1600k -maxrate:v:1 1600k -minrate:v:1 1250k -bufsize:v:1 1600k -preset slow -g 48 -sc_threshold 0 -keyint_min 48 \
  -map '[v3out]' -c:v:2 libx264 -x264-params "nal-hrd=cbr:force-cfr=1" -b:v:2 900k -maxrate:v:2 900k -minrate:v:2 700k -bufsize:v:2 900k -preset slow -g 48 -sc_threshold 0 -keyint_min 48 \
  -map a:0 -c:a:0 aac -b:a:0 96k \
  -map a:0 -c:a:1 aac -b:a:1 128k \
  -map a:0 -c:a:2 aac -b:a:2 128k \
  -f hls \
  -hls_time 4 \
  -hls_playlist_type vod \
  -hls_flags independent_segments \
  -hls_segment_type mpegts \
  -hls_segment_filename 'hls'/stream_%v_data%02d.ts \
  -master_pl_name playlist.m3u8 \
  -var_stream_map "v:0,a:0 v:1,a:1 v:2,a:2" \
  -t 10 \
  'hls'/stream_%v.m3u8

Is there something I missed ? Maybe a standard ? Or maybe problem is related to PTS/DTS of my file ?
Thanks !


text:
Q: has_one update problem I have two models, User and Account. Each user may have one account.
Creating an account for a user works fine. My problem is that when I try to update the account, the previous accounts user_id is nullified and a new account row is created with the user_id. I do not want this happening. I want to update the existing row with the changes to account. How do I do this?
Thanks.

A: With this code
@account = @user.account.build(params[:account])
if @account.save
   #...
else
   #...
end

you're building a new account. What you need is to update
if @account.update_attributes(params[:account])
   #...
else
   #...
end

A: Since you didn't provide any code lets say this is how you create a user
user = User.create(:name => "bob")

Then you can associate the user with an account by specifying the user_id
account = Account.create(:user_id =>user.id, :status => "not activated")

Now lets say we want to to change the status of the account. We can call the updated method in rails http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002270 like this:
Account.update( account.id, :status => "activated")

I can be more helpful with more info.


text:
Q: Serializing message with protobuf for akka actor which contains serializable data I have a persistent actor which can receive one type of command Persist(event) where event is a type of trait Event (there are numerous implementations of it). And on success, this reponds with Persisted(event) to the sender.
The event itself is serializable since this is the data we store in persistence storage and the serialization is implemented with a custom serializer which internally uses classes generated from google protobuf .proto files. And this custom serializer is configured in application.conf and bound to the base trait Event. This is already working fine.
Note: The implementations of Event are not classes generated by protobuf. They are normal scala classes and they have a protobuf equivalent of them too, but that's mapped through the custom serializer that's bound to the base Event type. This was done by my predecessors for versioning (which probably isn't required because this can be handled with plain protobuf classes + custom serialization combi too, but that's a different matter) and I don't wish to change that atm.
We're now trying to implement cluster sharding for this actor which also means that my commands (viz. Persist and Persisted) also need to be serializable since they may be forwarded to other nodes.
This is the domain model :
sealed trait PersistenceCommand {
  def event: Event
}

final case class Persisted(event: Event) extends PersistenceCommand
final case class Persist(event: Event) extends PersistenceCommand

Problem is, I do not see an elegent way to make it serializable. Following are the options I have considered
Approach 1. Define a new proto file for Persist and Persisted, but what do I use as the datatype for event? I didn't find a way to define something like this :
  message Persist {
   "com.example.Event" event = 1 // this doesn't work
   }

Such that I can use existing Scala trait Event as a data type. If this works, I guess (it's far fetched though) I could bind the generated code (After compiling this proto file) to akka's inbuilt serializer for google protobuf and it may work. The note above explains why I cannot use oneof construct in my proto file.
Approach 2. This is what I've implemented and it works (but I don't like it)
Basically, I wrote a new serializer for the commands and delegated seraizalition and de-serialization of event part of the command to the existing serializer.
class PersistenceCommandSerializer extends SerializerWithStringManifest {
  val eventSerializer: ManifestAwareEventSerializer = new ManifestAwareEventSerializer()

  val PersistManifest   = Persist.getClass.getName
  val PersistedManifest = Persisted.getClass.getName
  val Separator         = "~"

  override def identifier: Int = 808653986

  override def manifest(o: AnyRef): String = o match {
    case Persist(event)   => s"$PersistManifest$Separator${eventSerializer.manifest(event)}"
    case Persisted(event) => s"$PersistedManifest$Separator${eventSerializer.manifest(event)}"
  }

  override def toBinary(o: AnyRef): Array[Byte] = o match {
    case command: PersistenceCommand => eventSerializer.toBinary(command.event)
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = {
    val (commandManifest, dataManifest) = splitIntoCommandAndDataManifests(manifest)
    val event                           = eventSerializer.fromBinary(bytes, dataManifest).asInstanceOf[Event]
    commandManifest match {
      case PersistManifest =>
        Persist(event)
      case PersistedManifest =>
        Persisted(event)
    }
  }

  private def splitIntoCommandAndDataManifests(manifest: String) = {
    val commandAndDataManifests = manifest.split(Separator)
    (commandAndDataManifests(0), commandAndDataManifests(1))
  }
}

Problem with this approach is the thing I'm doing in def manifest and in def fromBinary. I had to make sure that I have the command's manifest as well as the event's manifest while serializing and de-serializing. Hence, I had to use ~ as a separator - sort of, my custom serialization technique for the manifest information.
Is there a better or perhaps, a right way, to implement this?
For context: I'm using ScalaPB for generating scala classes from .proto files and classic akka actors.
Any kind of guidance is hugely appreciated!

A: If you delegate serialization of the nested object to whichever serializer you have configured the nested field should have bytes for the serialized data but also an int32 with the id of the used serializer and bytes for the message manifest. This ensures that you will be able to version/replace the nested serializers which is important for data that will be stored for a longer time period.
You can see how this is done internally in Akka for our own wire formats here: https://github.com/akka/akka/blob/6bf20f4117a8c27f8bd412228424caafe76a89eb/akka-remote/src/main/protobuf/WireFormats.proto#L48 and here https://github.com/akka/akka/blob/6bf20f4117a8c27f8bd412228424caafe76a89eb/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala#L45


text:
Q: Common drain JFET output resistance "problem" The output resistance of small signal model for common drain JFET amplifier equals $$ \frac{1}{g_\text{m}} || R_{\text{ds(on)}} \parallel R_\text{S} $$ and since $$ R_{\text{ds(on)}} =\frac{1}{g_\text{m}} $$ we can also write this formula as \$\frac{1}{g_m} \parallel \frac{1}{g_m} \parallel R_\text{S}\$ right?
Which could be derived to $$R_{\text{OUT}} = \frac{1}{g_\text{m}}/2 \parallel R_\text{S}$$ right?

A: Here's a good summary table of small signal FET equations from the Sedra/Smith textbook on microelectronics, where \$ V_{ov} \$ is the overdrive voltage which is equal to \$ V_{GS} - V_{tn} \$.
NOTE: The reason why your assumption is wrong is because \$ r_o \neq \frac{1}{g_m} \$. Also, your model shows a common source, not a common drain.

A: \$g_m\$ is a transistor transconductance.
In saturation region we viewing the transistor (FET) as a voltage controlled
current source.
Vin is a input voltage and the output is a current, hence \$g_m=\frac{Io}{V_{in}}\$
Hence, for the FET \$g_m\$ is equal to \$gm = \frac{dI_d}{dV_{gs}}\$ (slope of the Id = f(Vgs) function)
In saturation region the Drain terminal behaviour just like an current source controlled via \$V_{gs}\$ voltage.
And this is why you see the voltage controlled \$(V_{gs})\$ current source
\$I_d = g_mV_{gs}\$ in the small signal equivalent circuit. Look at the answer given by KingDuken.
But this "drain" current source is not ideal. For the ideal current source the output current (drain current \$I_D\$) does not depend upon the voltage across it (\$V_{ds}\$). But in the real transistor \$V_{ds}\$ voltage due to channel length modulation will have small effect on the drain current.
And to "model" this effect (to represent channel length modulation on the small-signal equivalent circuit), we add a resistor \$r_o\$ parallel to the drain current source.

As you can see \$r_o \approx \frac{1}{\lambda I_D}\$ represent variation of \$I_D\$ with \$V_{DS}\$.
And \$R_{ds(on)}\$ is a FET resistance in the triode region when FET is full-on and \$V_{ds}\$ is very low \$V_{ds}<<(V_{gs} - V_{th})\$.
We can estimate the lambda value if we solve this set of equations:
$$I_{d1}=K(V_{gs} - V_{th})^2 (1+\lambda V_{ds1})$$
$$I_{d2}=K(V_{gs} - V_{th})^2 (1+\lambda V_{ds2})$$
$$I_{d1} - I_{d2} = K \lambda (V_{ds1} - V_{ds2}) (V_{gs} - V_{th})^2$$
Use the above to calculate \$\lambda\$
$$\lambda=\frac{I_{d1} - I_{d2}}{K(V_{ds1} - V_{ds2}) (V_{gs} - V_{th})^2}$$
Or this one
$$\lambda=\frac{I_{d2} - I_{d1}}{I_{d1}V_{ds2} - I_{d2}V_{ds1}}$$
Additional we can find \$K\$ factor
$$K = \frac{I_{d1}V_{ds2} - I_{d2}V_{ds1}}{(V_{ds2} - V_{ds2})(V_{gs} - V_{th})^2}$$

But we never do this type of calculation when designing circuit using a discrete FET's.


text:
Q: Efficiently updating dataframe rows on the fly I have two separate problems where I want to set values in a dataframe column based on values in other columns of that row or other rows that are related (ie. other rows that have some column value in common with said rows column value).
Starting DF
   acct no  product type  amount  product sum  product id
0      100             1      35          0.0         NaN
1      100             2      45          0.0         NaN
2      100             2      50          0.0         NaN
3      101             4      10          0.0         NaN
4      101             4       1          0.0         NaN
5      102             5      70          0.0         NaN
6      102             6      90          0.0         NaN

In one problem (for work), I would like to group by (in this case on two columns), take the sum of values listed in a third column, then write this sum value to a here-to-for unset column on all of the rows that were grouped-by
ex (account-product group by and sum as product sum):
   acct no  product type  amount  product sum  product id
0      100             1      35          35.0         NaN
1      100             2      45          95.0         NaN
2      100             2      50          95.0         NaN
3      101             4      10          11.0         NaN
4      101             4       1          11.0         NaN
5      102             5      70          70.0         NaN
6      102             6      90          90.0         NaN

In another problem (for 'fun'), I would like to create a 'product_id' that is based on another column value 'account number' and follows the convention account_number_i  where i is the ith product for that account
ex (iterate through account groups and write to product id as account iter):
   acct no  product type  amount  product sum  product id
0      100             1      35          0.0         100-1
1      100             2      45          0.0         100-2
2      100             2      50          0.0         100-3
3      101             4      10          0.0         101-1
4      101             4       1          0.0         101-2
5      102             5      70          0.0         102-1
6      102             6      90          0.0         102-2

In trying to do both of these, I have started by iterating through a sorted dataframe and utilizing functions like group by and sum, but it is about as slow as you would imagine. I am not nearly as comfortable with the pandas syntax as with python and one reason I am asking is to get a better grip on the best way to do what seems like a pretty common/ important task, updating empty rows based on related rows. I have used pandas for running averages and know this is fast, but what I want is a little more esoteric.

A: Don't iterate through your dataframe - 99% of the times there are better options.
Your problems can be easily solved by using groupby with transform, and cumcount:
df["product sum"] = df.groupby(["acct no","product type"])["amount"].transform('sum')
df["product id"] = df["acct no"].astype(str)+"-"+(df.groupby("acct no").cumcount()+1).astype(str)

print (df)

   acct no  product type  amount  product sum product id
0      100             1      35           35      100-1
1      100             2      45           95      100-2
2      100             2      50           95      100-3
3      101             4      10           11      101-1
4      101             4       1           11      101-2
5      102             5      70           70      102-1
6      102             6      90           90      102-2


text:
Q: Meaning of the term "phase" in chemistry and thermodynamics I have some doubts about the definition of the term "phase" in chemistry and thermodynamics (is the meaning the same?).
The "textbook" definition is:
"A phase is a form of matter that is uniform throughout in both chemical composition and physical state."
Does physical state means macroscopic intensive proprieties, like temperature? So a body with a temperature gradient doesn't have a phase? Is the term "phase" only significant at equilibrium?
And does "same chemical composition" means same chemical formula or same concentration? In the first case a solution would have two phases, in the second only one.

A:
The "textbook" definition is: "A phase is a form of matter that is uniform throughout in both chemical composition and physical state."
Does physical state means macroscopic intensive proprieties, like temperature?

That's one textbook's definition, not "the" textbook definition. Other textbooks have other definitions.
Consider water held at it's triple point. At this point, some of the water will be liquid, some will be solid, and some will be gaseous. All three phases have the same uniform chemical composition, the same temperature, and the same pressure. Uniformity in temperature not what is meant by "physical state" in this context.
The intent of the term "physical state" is to capture concepts such as solidity vs liquidity vs gaseousness, thermal and electrical conductivity, crystalline structure, transitions that generate or consume heat, etc. However, poking at the concept of "phase of matter" hard enough makes the concept breaks down a bit. For example, by going around the critical point, a liquid transitions to a gas without going through a phase transition. The distinction between a gas and a plasma is fuzzier yet.

A: @David Hammen
So to summarize, correct me if I'm wrong.
From a microscopic point of view we can say that a phase is a set of particles (atoms or molecules) of same type held together in the same way (same structure, same type of bonds).
From a macroscopic point of view a phase is a portion of matter the proprieties of which don't depend on the spatial coordinates. By proprieties I mean anything that is definite from a phenomenological perspective (anything I've a meaningful procedure to observe and measure).
The two view should be consistent (I think). If we go with this interpretation a phase is not defined by continuity but by uniformity. Meaning that if a propriety change with continuity we have infinite phases. This would also be coherent with the way thermodynamics looks at this kind of systems (they have to be broken down in parts small enough to be considered homogeneous otherwise we can't talk of a "state").

A: In thermodynamics when we talk about phase we mean the phases like liquid, solid and gas.
In chemistry one can have phases which refer to the crystal structure of materials for example in perovskites, the orthorhombic and tetragonal phases are most common non-cubic variants.
Mixed throughout, as inn general language, we sometimes talk of a phase of a process. A certain phase might take place in the gradual development of something.
So, no - the meaning of the word phase in thermodynamics and chemistry is not uniform.


text:
Q: iPhone accessing one resource by two threads I want to synchronize one queue among two threads. Such as one thread performs enqueue and other performs dequeue.
Any ideas??

A: Cocoa class like NSArray or NSMutableArray is non thread safe, you have to use object NSLock class to make them thread safe.


text:
Q: How to count a value in a specific row of an array with Python So basically I have an array, that consists of 14 rows and 426 Columns, every row represents one property of a dog and every column represents one dog, now I want to know how many dogs are ill, this property is represented by the 14. row. 0 = Healthy and 1 = ill, so how do I count the specific row?
I tried to use the numpy.count_nonzero but this counts the values of the entire array, is there a way to tell it to only count a specific row?

A: You can simply sum the values of the 14.row and you get the number (count) of ill dogs:
count = A[13,:].sum() # number of ill dogs -- 13 because the index starts with 0

A: Suppose we have this vector:
>import numpy as np
>arr = np.arange(30).reshape(6,5)
>arr
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [25, 26, 27, 28, 29]])

With this, you will get the sum of all values for a specific row:
>np.sum(arr[1,:]) #On row 1
35

For your specific case, use:
>np.sum(arr[13,:])


text:
Q: RegEx not working on Angular 2 I have this form Builder group for my form and I want to add a pattern to validate the email address but the regex i'm using is not working. This is my code.
I am new to Angular 2 and I will need some help.
Thank You
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

this.form = this.formBuilder.group({
    'name': new Control('', Validators.compose([
        Validators.required,
        Validators.pattern('[\\a-z\\A-Z\\s]+')
        ])),
    'gender': new Control('Male'),
    'email': new Control('', Validators.compose([
        Validators.required,
        Validators.pattern(re)
    ]))
});


text:
Q: How to pass std::function as an argument to a mocked method in gmock? I am getting a runtime error when trying to pass an std:function as an argument to a mocked method inside EXPECT_CALL.
I wish to verify that Bar is called with callback as an argument.
Code:
#include <gtest/gtest.h>
#include <gmock/gmock.h>

class Foo {
public:
    virtual void Bar(const std::function<void (const std::string &name)> &callback) = 0;
};

class MockFoo : public Foo {
public:
    MOCK_METHOD(void, Bar, (const std::function<void (const std::string &name)> &callback));
};

TEST(FooBarTest, callback) {
    MockFoo foo;

    const std::function<void(const std::string &name)> callback;

    EXPECT_CALL(foo, Bar(callback)).Times(1);

    foo.Bar(callback);
}

int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

An error is produced at runtime:
/usr/local/include/gtest/gtest-matchers.h:211:60: error: no match for 'operator==' (operand types are 'const std::function<void(const std::__cxx11::basic_string<char>&)>' and 'const std::function<void(const std::__cxx11::basic_string<char>&)>')
   bool operator()(const A& a, const B& b) const { return a == b; }

A: There are pre-defined ACTIONS that you could use for this purpose. Your EXPECT_CALL would look something like:
using namespace testing; // for brevity

TEST(FooBarTest, callback) {
    MockFoo foo;

    const std::function<void(const std::string &name)> callback;

    EXPECT_CALL(foo, Bar(_)).WillOnce(Invoke(callback));

    foo.Bar(callback);
}

As pointed out by @IanGralinski, there's no matcher for std::function, so you can use any matcher for the call (i.e. _).
However, this is not how I would use gmock here - why mocking Foo if you use it directly? Usually mocks are used when you test interactions of your (real) class with other classes (mocked). So in your example: Foo could be mocked by MockFoo and used by some other class (real one), using dependency injection.
On a side note, remember to add virtual destructor to Foo if the object derived from Foo is to be deleted by pointer to Foo (this would be UB without virtual dtor).

A: The arguments to the method named in an EXPECT_CALL are actually matchers. When you just provide a value (something which is not already a gmock Matcher<T> type), that implies an Eq matcher. So EXPECT_CALL(foo, Bar(callback)) really means EXPECT_CALL(foo, Bar(Eq(callback))). The trouble is, std::function does not provide an operator== for comparing two functions. Its type-erasure properties mean an equality test would be impossible to implement in general, plus of course some of the class functor types it might wrap around won't have their own operator== either.
But it is possible to test whether a std::function contains a very specific object. If you don't want to just ignore the argument by expecting Bar(_), here's an idea for identifying whether a std::function is a specific dummy function.
First, create a callable class which we'll use to initialize the std::function object. I'll also have its operator() call a mock method, which is not needed when it's just passed to a mock function, but this will make it possible to use the same std::function in different contexts, or set expectations before one real function which will both call it directly and pass it to a mocked interface.
template <typename FuncT> class DummyFunction; // undefined

template <typename RetType, typename... ArgTypes>
class DummyFunction<RetType(ArgTypes...)> {
public:
    constexpr DummyFunction() : DummyFunction(0) {}
    explicit constexpr DummyFunction(int key) : m_key(key) {}
    constexpr DummyFunction(const DummyFunction& f) : m_key(f.m_key) {}
    constexpr int key() const { return m_key; }

    MOCK_METHOD(RetType, doCall, (ArgTypes...));

    RetType operator()(ArgTypes... args)
    { return doCall(std::forward<ArgTypes>(args)...); }

    friend constexpr bool operator==(const DummyFunction& f1, const DummyFunction& f2)
    { return f1.m_key == f2.m_key; }
    friend constexpr bool operator!=(const DummyFunction& f1, const DummyFunction& f2)
    { return !(f1 == f2); }
    friend std::ostream& operator<<(std::ostream& os, const DummyFunction& f)
    { return os << "DummyFunction(" << f.m_key << ")"; }

private:
    int m_key;
};

Then a gmock Matcher to test whether a std::function contains a DummyFunction object with the exact same function type as template parameter and the same key as a given DummyFunction object could look like this. Since it's possible to convert one type of std::function to another as long as the parameter types and return types convert correctly (or the return type changes to void), I made it a "polymorphic" matcher which accepts any std::function specialization for testing.
template <class DummyFuncType>
class IsDummyFunctionTester {
public:
    explicit constexpr IsDummyFunctionTester(int key) : m_key(key) {}

    // The three member functions required for gmock "PolymorphicMatcher":
    template <typename FuncType>
    bool MatchAndExplain(const std::function<FuncType>& f,
                         ::testing::MatchResultListener* listener) const {
        bool type_ok = f.target_type() == typeid(DummyFuncType);
        if (type_ok) {
            int f_key = f.template target<DummyFuncType>()->key();
            if (f_key == m_key) return true;
            *listener << "std::function contains DummyFunction(" << m_key << ")";
        } else if (!f) {
            *listener << "std::function is empty";
        } else {
            // Note name() is implementation dependent. For g++/clang it's mangled.
            *listener << "std::function target's type_info::name() is "
                      << f.target_type().name();
        }
        return false;
    }

    void DescribeTo(std::ostream* os) const
    { *os << "is a DummyFunction(" << m_key << ")"; }
    void DescribeNegationTo(std::ostream* os) const
    { *os << "is not a DummyFunction(" << m_key << ")"; }

private:
    int m_key;
};
template <typename FuncType>
decltype(auto) StdFuncIsDummyFunc(const DummyFunction<FuncType>& f) {
    return ::testing::MakePolymorphicMatcher(
        IsDummyFunctionTester<DummyFunction<FuncType>>(f.key()));
}

So finally, you can do:
TEST(FooBarTest, callback) {
    MockFoo foo;

    const DummyFunction<void(const std::string &name)> callback;

    EXPECT_CALL(foo, Bar(StdFuncIsDummyFunc(callback))).Times(1);

    foo.Bar(callback);
}

If you have just one DummyFunction, or if exactly which DummyFunction is which isn't important for the test, you can just use the default "key" of zero like above. Otherwise, you can specify unique keys for each distinct dummy callback.


text:
Q: Creating a json file from a xml file in python with xmltodict I am trying to create a json file from an input xml file using xmltodict with the following code
import io, xmltodict, json
infile = io.open(filename_xml, 'r')
outfile = io.open(filename_json, 'w')
o = xmltodict.parse( infile.read() )
json.dump( o , outfile )

the last line get me the following error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 182, in dump
    fp.write(chunk)
TypeError: must be unicode, not str

I guess I need to change the encoding. My initial xml file seems to be ascii. Any idea on how to make this work?
Thanks

A: You can open the file in binary mode
outfile = io.open(filename_json, 'wb')

This will allow str as well.

A: unicode and str are two different types of objects in Python prior to version 3. You can turn your value into a unicode object (which is basically also a string) by coercing it:
my_var = unicode(my_str)


text:
Q: undefined local variable or method `scoped' for # I get this error when i did pagination (will_paginate) + rails 4. really dont understand what went wrong
gem file
gem 'will_paginate', '~> 3.0'

here is the controller
@users = User.where.not(:name => "admin").all
@user_paginate = @users.paginate(:page => params[:page], :per_page => 3)

view
<%= will_paginate @user_paginate %>

application controller i did
require 'will_paginate/array'

model relations
User has_many :listings
Listing belongs_to :user
any help will be appreciated thanks

A: found the solution
change gem 'will_paginate', '~> 3.0'
to
gem 'will_paginate', '~> 3.0.5'

and this worked for me

A: try this @users = User.where.not(:name => "admin").all.paginate(:page => params[:page], :per_page => 3) and see if you get the same error.
or (name: 'admin')
why do you have the require 'will_paginate/array'
thats for something like this array.paginate(:page => a, :per_page => b)
Check this post


text:
Q: How to prevent carriage return being copied to clipboard in Powershell? I have a powershell script that is hashing the MAC address, then posting it into a file and a clipboard.
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($MAC)))
$hash | clip
$hash | Out-File $Env:USERPROFILE\Desktop\this.txt

The issue I am having is that a carriage return is being exported to the clipboard. I don't want that.
Is there a way of stopping that happening?
Additional info - When I paste the text that is on the clipboard into a hex editor I see 0D0A
The clipboard function would be fine if I could just loose that some how?
Thanks

A: If you can use PowerShell 5.0 or higher, Set-Clipboard is available. It does not add any newline characters. So, your example would become:
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($MAC)))
$hash | Set-Clipboard
$hash | Out-File $Env:USERPROFILE\Desktop\this.txt

A: $Hash.TrimEnd() should clear any unicode whitespace at the end of the string. http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx

A: Unfortunately, it looks like clip itself appends the newline. So, let's do it the .NET way!
Here's a function that takes stdin and puts it in the clipboard:
function Out-ClipboardText
{
    param(
        [Parameter(
            Position=0,
            Mandatory=$true,
            ValueFromPipeline=$true)
        ]
        [String]$text
    )

    process
    {
        powershell -sta -noprofile -command "add-type -an system.windows.forms; [System.Windows.Forms.Clipboard]::SetText('$text')"
    }
}

Adapted from http://brianreiter.org/2010/09/03/copy-and-paste-with-clipboard-from-powershell/ and https://stackoverflow.com/a/887406/1030702
Use it like so:
$hash | Out-ClipboardText

It uses the .NET clipboard function to set the text. Unfortunately, it's also a little slow and complicated because it needs to start a new PowerShell process in STA mode, as required for Clipboard (source).


text:
Q: Possible Cisco Router Hack? We have a Cisco EPC3928AD EuroDocsis 3.0 2-PORT Voice Gateway from our ISP. The router is connected to a firewall (an Ubuntu-box running iptables and Wireshark). Our LAN (10.0.0.1/24) is beyond the firewall. No other equipment is connected to the router. The router's WIFI has been disabled.
A few days ago we noticed problems when fetching mail or browsing. The connection started to get slower and sometimes we do not have a connection at all. This behavior seem to occur at random and during irregular time periods (1-30 minutes approx.). All equipment on the LAN is affected. Certain services like Skype are not affected.
The ISP did a checkup of the router and the connection to the rest of the WAN. They found no problems, neither with the modem itself nor the signal strength or the cable. They also set up monitoring of the WAN segment that the modem is on and that ran for several days without finding any problems.
Our LAN has no DHCP. We also had the DHCP in the modem was switched off. The NIC on the firewall facing the WAN was set to 192.168.0.201. Although our LAN has static addresses and DNS configurations on each NIC are set to the ISP's recommended DNSs, they told us that activating the DHCP in the router "sometimes helps"...
We proceeded to activate the DHCP with starting address 192.168.0.201 and with a range of 1. We also reserved 192.168.0.201 for the MAC of the NIC facing the modem. What happened next puzzled us: in the router's "Preassigned DHCP IP Addresses"-list an unknown MAC, 00:11:e6:de:ad:07 (00:11:e6 belongs to Scientific Atlanta, part of Cisco), was occupying 192.168.0.201. Moreover, in the router's "Connected Devices Summary", the same MAC was showing up, but this time with an IP (10.0.0.74) on the LAN!
We restarted the router, but to no avail. The same unknown MAC showed up again, this time with a LAN address (10.0.0.2) already in use by a workstation on the LAN. Blocking the MAC in IP-tables made the MAC disappear from the "Connected Devices Summary", but is still in the "Preassigned DHCP IP Addresses"-list. We have set the IP-range to 2, so it now occupies 192.168.0.202 instead of 192.168.0.201.
Restarting the router or disconnecting it from the firewall does not help. The unknown MAC keeps on reappearing. The intermittent problems with the connection persist. What is going on? Is this a hack of some kind? Any input will be much appreciated.

A: The same occurred to me, with the same router and exactly the same MAC address (00:11:e6:de:ad:07). After a blackout a DLNS server with IP ending in 249 (named BRCM-DMS:249) appeared on my network. I solved it enabling and disabling media server on Share and storage. After a while, IP and network server disappeared...


text:
Q: Removing a 'trend in variance' from a time series I'm looking at a time series which has a very strong daily cycle in it. However, on top of having a daily cycle in the actual values of the time series, it also has a very strong daily variance cycle.
I am wondering if I can meaningfully remove the 'variance trend' from my time series. I can calculate the 'average variance' for a given hour and then divide by it, but I'm not sure I'm doing anything useful if I do this?
The large variance does correlate with large values in the daily cycle too, but taking a log doesn't seem to help much.
EDIT: EXTRA INFORMATION
As pointed out in the comments, this problem is rather under-defined. Unfortunately, this is a symptom I am also dealing with and so I can't fix that. However, I will try to give some more information.
The goal is to have a model of the time series from which realisations can be drawn. The time series data is a measure of concentration over time, with clear daily and yearly cycles and a linear trend. There are many covariate time series which at least follow the same daily and yearly cycles.
I am currently just trying to explore and learn different time series techniques. I wasn't hoping for a 'solution' but rather for a bit of direction as I hadn't been able to find much information about trends in the variance.

A: No one will be able to help you without an example of the data or more information, however a few things can be said. I will not elaborate on the algebra of things though, you best research that for yourself.
The books of Greene and/or Hayashi concerning Econometrics are a good source about the topics of heteroscedasticity, autocorrelation and (F)GLS. An easier example is Stock/Watson.
First, the variance trend can probably be modeled by a matrix of covariances, ie.
$V[\epsilon|X] = \Omega$
In that case you can use the GLS estimator to eliminate the heteroscedasticity. Especially useful to you should be the FGLS techniques. In that case you estimate the matrix from residuals of a regular OLS and then iteratively refine your estimates.
Wikipedia FGLS
As far as your dependency on the magnitude of your data is concerned, this is also eliminated by FGLS. You can see that the GLS estimator (in terms of General Method Of Moments) comes down to the following problem:
${E}[\,x_t(y_t - x_t'\beta)/\sigma^2(x_t)\,]=0$
So you should transform your model accordingly (this is equivalent to using the GLS estimator, using the matrix $\Omega$
In addition to the wikipedia article I wrote about GLS / heteroscedasticity
here
If you are using R, another strategy can be to use Newey-West variance/covariance robust error term estimators. This can be achieved by adding vcov=vcovHAC as an argument to your R-functions. If your dataset is large enough, this will give you consistent estimates of your error terms.

A: You can find some suggestions by looking with following keywords:
-Seasonal ARIMA models
-State Space Models
-Basic Structural Model by AC Harvey
-Kalman Filter and structural time series models
-TRAMO/SEATS  and/or Demetra


text:
Q: Getting selected value from dropdown when editing aggregated object at MVC 5.0 I can't get the value from DropDownList when the DropDownList targets a field of an object inside the Model.
@Html.DropDownList("MyID", null, htmlAttributes: new { @class = "form-control" })

The ViewBag is filled with this:
ViewBag.MyID = new SelectList(db.WFMasters, "MyID", "Code", wFDefDetail.wfDef.MyID); //MyID is property of wfDef. Model is wFDefDetail.

I have no trouble to get the value of the DropDownList if the target value is a property of the model.
In this case, the DropDownList is correctly filled but I don't get the selected value at the View Controller method. The controller receives null for wFDefDetail.wfDef.MyID.
Also, if I change to @html.EditorFor method I can get the value of wFDefDetail.wfDef.MyID so must be some detail I miss to put DropDownList to work too.

A: To map data properly dropdown name property should match the model like below:
@Html.DropDownList("wfDef.MyID", (IEnumerable<SelectListItem>)ViewBag.MyID, htmlAttributes: new { @class = "form-control" })

A: You could use dropdown list change event handler to send the form to your server. In the example below the request to your profile will be sent when the select control is changed. The selected option value will be sent with request as tab parameter.

$("[name=tab]").change(function() {
  $(this).parent("form").submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://stackoverflow.com/users/2700303/byteartisan">
  <select name="tab">
    <option value="default" disabled="disabled">Select tab...</option>
    <option value="profile">Profile Tab</option>
    <option value="topactivity">Activity Tab</option>
  </select>
</form>

If the form includes single data field only, then you could get tab value in action method directly:
public ActionResult MyAction(string tab)
{
    string SelectedValue = tab;
    // do something
}

If the form sends a complex data that described by custom class, use corresponding property of argument object, for example:
public ActionResult MyAction(CustomType FormData)
{
    string SelectedValue = FormData.tab;
    // do something
}


text:
Q: Get-ChildItem Fails When Using a Variable With the Include Switch Powershell v4.0
Windows 7
This code works and retrieves the 2 files I'm trying to find:
$dir = Get-Item -Path "C:\TestSource"
Get-ChildItem -Path "$($dir.FullName)\*" -File -Include *.txt,*.inf

This code works too, but it only finds the txt file:
$Dir = Get-Item -Path "C:\TestSource"
$Filter = "*.txt"
Get-ChildItem -Path "$($dir.FullName)\*" -File -Include $Filter

However, this does not return any objects:
$Dir = Get-Item -Path "C:\TestSource"
$Filter = "*.txt,*.inf"
Get-ChildItem -Path "$($dir.FullName)\*" -File -Include $Filter

It's necessary to build the $Filter variable into an array like so:
$Dir = Get-Item -Path "C:\TestSource"
$Filter = @("*.txt","*.inf")
Get-ChildItem -Path "$($dir.FullName)\*" -File -Include $Filter

The Microsoft page on Get-ChildItem leads me to believe it's possible to use variables with the Get-ChildItem cmdlet.  However, why is the cmdlet not returning objects unless the variable is an array?  Since the explicit string works in the first example, shouldn't the 3rd example work as well?

A: The argument to Include is always an array - in your first example -Include *.txt,*.inf passes a two-element array as the filter.
In your third example it is a comma-separated string. If you pass an array it should work:
$Dir = Get-Item -Path "C:\TestSource"
$Filter = "*.txt", "*.inf"
Get-ChildItem -Path "$($dir.FullName)\*" -File -Include $Filter

A: Lee gave the answer; in your third example you are trying to pass multiple values for the -Include parameter to evaluate but you didn't format it appropriately as an array so the script is looking for a file with this entire string pattern in its name: *.txt,*.inf


text:
Q: asp.net Server Error in '/' application in vs 2015 from host which I bought I'm trying to publish a website which I built on asp.net framework 4.6 which works quite well when I start from IIS.
What I mean is that I can reach to admin panel through login page however when I try to reach from the host I can not reach to the admin page.
It gives this error "Server Error in '/' Application.  The resource cannot be found.  Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.
Please review the following URL and make sure that it is spelled correctly.   Requested URL: /admin.aspx"


text:
Q: How to toggle ExtJs grid action column icon and tooltip? I need to toggle Action column icons and tooltip. I have 2 images for Play and Pause (play-icon.png and pause-icon.png) I want to toggle it. Here I put piece of code. any idea to do this?
columns: [{
            xtype: 'actioncolumn',
            flex: 0.4,
            text: 'play',
            sortable: false,
            menuDisabled: true,
            align: 'center',
            items: [{
                icon: FLEET_SERVER_URL + 'images/play-icon.png',
                tooltip: 'Play',
                scope: this,
                handler: function(grid, rowIndex, colIndex) {
                    //here I want to toggle the icons
                }
            }]
        },

A: I Don't know this is correct way or not, to fix this issue. But this is working for me.
I am setting innerHTML to Grid cell by Row index and cell index.
In bellow code this.TravelReportList is my ExtJS grid panel object
rowIndex I am getting on cell click event.
below line of code setting the Play Icon and 'Paly' tool tip for cell
this.TravelReportList.getView().getNode(rowIndex).cells[1].innerHTML = '

';

below line of code setting the Pause Icon and 'Pause' tool tip for cell
this.TravelReportList.getView().getNode(rowIndex).cells[1].innerHTML = '

';

My Final code is below
columns: [{
                    xtype: 'actioncolumn',
                    flex: 0.4,
                    text: 'play',
                    sortable: false,
                    menuDisabled: true,
                    align: 'center',
                    items: [{
                        icon: FLEET_SERVER_URL + 'images/play-icon.png',
                        tooltip: 'Play',
                        scope: this,
                        handler: function (grid, rowIndex, colIndex) {

                            if (this.tripPlayConf.rowIndex == rowIndex) {
                                if (this.pause == false) {
                                    this.TravelReportList.getView().getNode(rowIndex).cells[1].innerHTML = '

';
                                    this.pause = true;
                                }
                                else {
                                    this.TravelReportList.getView().getNode(rowIndex).cells[1].innerHTML = '

';
                                    this.pause = false;
                                }
                            }
                        }
                    }]
                }]

A: As far as I know, actioncolumn isn't flexible for modifying its behavior on a per-row basis. A suitable workaround in this case could be using a widgetcolumn with a button as its widget. A rowViewModel allows you specifying a viewmodel that is created for each individual row, and has access to that rows record ('{record}'); you can bind to its properties from the widget. For accessing a record from inside handler, you can use getWidgetRecord() method that is created for the widget (no matter of its xtype). Here is a (classic) fiddle example
Ext.define('MyView', {
    viewModel: {
        stores: {
            gridStore: {
                fields: ['name', 'isPlaying'],
                data: [{
                    name: 'FOO',
                    isPlaying: false
                }, {
                    name: 'BAR',
                    isPlaying: true
                }]
            }
        }
    },

    extend: 'Ext.grid.Panel',
    xtype: 'MyView',
    bind: {
        store: '{gridStore}'
    },
    columns:[{
        dataIndex: 'name',
        flex: 1
    }, {
        xtype: 'widgetcolumn',
        width: 50,
        widget: {
            xtype: 'button',
            bind: {
                iconCls: '{playButtonIcon}',
                tooltip: '{playButtonTooltip}'
            },
            handler: function(button) {
                var rec = this.getWidgetRecord();
                rec.set('isPlaying', !rec.get('isPlaying'));
            }
        }
    }],
    rowViewModel: {
        formulas: {
            playButtonIcon: function(get) {
                return get('record.isPlaying')? "x-fa fa-pause" : "x-fa fa-play";
            },
            playButtonTooltip: function(get) {
                return get('record.isPlaying')? "playing" : "paused";
            }
        }
    }
});

Ext.application({
    name : 'Fiddle',

    launch : function() {
        Ext.create({
            xtype: 'MyView',
            width: 300,
            height: 300,
            renderTo: Ext.getBody()
        });
    }
});


text:
Q: How do I access an Entity Framework domain object inside of a Kendo UI Grid in MVC5 I'm a newbie to web development, C# and .net (VS2013), not sure I'm asking this correctly but after searching through books, all through the telerik docs, and google searches I'm still stuck on something simple.
What I'm trying to do is create a page in an MVC app using the Kendo Grid and Ajax to display information on client locations and include the primary phone.number and primary address.add1, coming from different DB tables, in the grid.
My Domain Objects
public partial class location
{
    public location()
    {
        this.addresses = new HashSet<address>();
        this.location_note = new HashSet<location_note>();
        this.phones = new HashSet<phone>();
    }
    public long id { get; set; }
    public long acct_id { get; set; }
    public Nullable<bool> active { get; set; }
    public string name { get; set; }
    public string contact { get; set; }
    public Nullable<long> location_account_id { get; set; }

    public virtual ICollection<address> addresses { get; set; }
    public virtual ICollection<location_note> location_note { get; set; }
    public virtual ICollection<phone> phones { get; set; }
}

public partial class address
{
    public long id { get; set; }
    public long acct_id { get; set; }
    public long location_id { get; set; }
    public bool primary { get; set; }
    public string add1 { get; set; }
    public string add2 { get; set; }
    public string city { get; set; }
    public string county { get; set; }
    public string state { get; set; }
    public string zip { get; set; }
    public string comment { get; set; }
    public long address_type_id { get; set; }

    public virtual address_type address_type { get; set; }
    public virtual location location { get; set; }
}

public partial class phone
{
    public long id { get; set; }
    public long acct_id { get; set; }
    public long location_id { get; set; }
    public bool primary { get; set; }
    public long phone_type_id { get; set; }
    public string number { get; set; }

    public virtual location location { get; set; }
    public virtual phone_type phone_type { get; set; }

My Scaffolded LocationController
public class LocationController : Controller
{
    private vessenceEntities db = new vessenceEntities();

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult locations_Read([DataSourceRequest]DataSourceRequest request)
    {
        IQueryable<location> locations = db.locations;
        DataSourceResult result = locations.ToDataSourceResult(request, location => new {
            id = location.id,
            acct_id = location.acct_id,
            active = location.active,
            name = location.name,
            contact = location.contact,
            location_account_id = location.location_account_id,
        });

        return Json(result);
    }

My View - Index.cshtml
@(Html.Kendo().Grid<VEPrototype.location>()
  .Name("grid")
  .Columns(columns =>
  {
    columns.Bound(c => c.acct_id);
    columns.Bound(c => c.active);
    columns.Bound(c => c.name);
    columns.Bound(c => c.contact);
    columns.Bound(c => c.location_account_id);
    })
  })
  .ToolBar(toolbar => {
        toolbar.Create();
        toolbar.Excel();
        toolbar.Pdf();
  })
  .Editable(editable => editable.Mode(GridEditMode.PopUp))
  .Pageable()
  .Sortable(sortable => {
      sortable.SortMode(GridSortMode.MultipleColumn);
  })
  .Filterable()
  .Scrollable()
  .DataSource(dataSource => dataSource
      .Ajax()
      .Model(model => model.Id(p => p.id))
      .Read(read => read.Action("locations_Read", "Location"))
  )

Things I have tried to do:

*

*When I do a debug stop in the LocationController I can't see any data in the IQueryable location variable, just queries - but if I do a ToList() then I can see the correct addresses in each location.  So I've tried adding values to the json result going to the view like:
primaryaddress = location.addresses.GetElementAt(0).add1

Just to see if I could get something back - doesn't work.  Seems like even if I add the extra address and phone data to the Json result the view is tied to the location model so I can't get to those extra data pieces I've added, makes sense.  So do I need to associate the view to a different model that I would build somewhere else and add the Location, Address, and Phone data I want in the grid?

*I've tried creating another location partial class with PrimaryAddress and PrimaryPhone properties and within that class doing a foreach through the addresses in the location class - but when the getters run the address hasn't been populated yet and I get null reference exceptions.
When using the standard razor syntax and the VS scaffolded controller I can see the entire location domain object in the view and for each through the addresses of each location and find the primary address and phone.  I'm tripping up when using the Kendo Grid with Ajax where its passing Json to the view and I'm lost on how to get the addresses and phone data into the view.  Sorry this is probably basic, if someone could point me to some documentation on best practices for using the Kendo controls it might help me get unstuck.  I have searched and looked through the telerik website but the Ajax/Json examples I've found are pulling data from only one table in a DB which works great with the scaffolded components already.
Thanks in advance...

A: I don't have time for a full answer here but a few things off the top... IQueryable is a deferred execution interface, meaning that the query is not actually run until you call something like .ToList() on the query, see here.  Secondly I would recommend looking into possibly using AutoMapper so that you can separate your data transfer objects(client models) from those being persisted to the database(entity models)(you can also do this mapping without Automapper if the mapping are simple). Taking both of these things into account will allow you to test the DTO and client bindings in one context and test the controller through to entity bindings in another context, thereby removing some of the magic.
EDIT #1:
Here is an example of Entity to DTO Mapping using OData:
    [EnableQuery]
    public IQueryable<FooDto> Get()
    {
        // Load set into read-only context for performance.
        var sets = Context.Foos.AsNoTracking();
        // AutoMapper will modify the database query to support exposing DTOs
        var setsDtos = sets.Project().To<FooDto>();
        return setsDtos;
    }

Or here is a case for a single result using OData:
    [EnableQuery]
    public SingleResult<FooDto> Get(string key)
    {
        return
            SingleResult.Create(
                Context.Foos.AsNoTracking().Where(set => set.FooId == key)
                    .Project()
                    .To<FooDto>()
                    .AsQueryable());
    }


text:
Q: Java: Network Statistics of running Java App from inside App itself Is there a way to monitor the network traffic (bytes transferred, packet count) from inside the java program itself?
I want to benchmark a third party application (IBM Domino DIIOP). There is no way to pass a custom network socket etc. to the library. The benchmark app is running on windows/Linux. Right now I'm doing the monitoring with Wireshark, but it's complicated and time-consuming. Wireshark negatively influences the network performance, so it's not the perfect choice for benchmarking.
Is there a pure java solution which works on Windows and/or Linux?

A:
Is there a way to monitor the network traffic from inside the java program itself?

There are several ways:

*

*You can monitor sockets. Please refer to the following article. Also there is a number of libraries on the internet.

*You can use runtime weaving with AspectJ to intercept calls with AOP and calculate statistics.

Still you should keep in mind that not all statistics can be collected from application in general. Network communication is delegated to OS and application is generally not aware of transport details.

bytes transferred

You can calculate bytes read and written by the app but not the actual amount of bytes transmitted over network.

packet count

Packet count is not available from application as it is responsibility of network protocol driver to form and deliver packets.


text:
Q: NSString is wiped when the segue finished Ive been working on updating an xcode project to storyboard style and having changed the three views in the old xcode xib to three view controllers on the new storyboard style im having a problem with the string i created to pass the data from one view controller to the other, when i switch to the third view controller to get some more info, the date of birth, the first label with the initial piece of data goes blank.
I have three view controllers.  The first is where i have the strings *concentrationString and *DOBString.  This is where the data that is selected on the other views is displayed.
FirstViewController.h
@interface FirstViewController : UIViewController {
    IBOutlet UILabel *concentrationlabel;
    IBOutlet UILabel *DOBlabel;

}

@property (strong, nonatomic) NSString *concentrationString;
@property (strong, nonatomic) NSString *DOBString;

FirstViewController.m
#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController
@synthesize concentrationString, DOBString;

...

- (void)viewDidLoad
{
    [super viewDidLoad];

     concentrationlabel.text = concentrationString;
     DOBlabel.text = DOBString;

...

The SecondViewController.m has several buttons for medications that tells the first view controller what value to put into the concentration label using the prepareForSegue stuff i found
#import "SecondViewController.h"
#import "FirstViewController.h"

...

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"Adrenaline"]) {
        NSString *concentrationString = @"Adrenaline";
        FirstViewController *vc = [segue destinationViewController];
        vc.concentrationString = concentrationString; }

    else if ([segue.identifier isEqualToString:@"Morphine"]) {
        NSString *concentrationString = @"Morphine";
        FirstViewController *vc = [segue destinationViewController];
        vc.concentrationString = concentrationString; }

and it updated the label on the first view with either "Adrenaline" or "Morphine" depending on which button was clicked.
When the user goes to the ThirdViewController.m to select the patients date of birth from a picker and i use the prepareForSegue method to send that value back, the first label goes blank, although i did not specify a change to concentrationString
#import "DOBViewController.h"
#import "FirstViewController.h"

@interface DOBViewController ()

@end

@implementation DOBViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad {
    NSDate *now = [NSDate date];
    [picker setDate:now animated:YES];
    [DOBset setTitle:@"Date of birth" forState:UIControlStateNormal];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)displayDate:(id)sender {
//  NSDate * selected = [picker date];
//  NSString * date = [selected description];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:@"dd-MMMM-yyy"]; //24hr time format
    NSString *dateString = [outputFormatter stringFromDate:picker.date];
    [DOBset setTitle:dateString forState:UIControlStateNormal];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"DOB"]) {
        NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
        [outputFormatter setDateFormat:@"dd-MMMM-yyy"]; //24hr time format
        NSString *DOBString = [outputFormatter stringFromDate:picker.date];
        FirstViewController *vc = [segue destinationViewController];
        vc.DOBString = DOBString;
    }
}

@end

How should i work this?
Thank you in advance.
Best Regards,
Kurt.

A: The reason that this is not working is because you are creating two different objects for the same view Controller(namely 1st view controller). In order to get the changes from both controllers visible in the first controller you have to get the same reference of the first view controller in both the controllers.
It can be done by creating an IBOutlet for the first view controller in the AppDelegate class as a property
@property(nonatomic,strong) IBOutlet FirstViewController *firstViewController;
and then using the code in both classes by importing AppDelegate.h:
   AppDelegate *app=[UIApplication sharedApplication].delegate;
   FirstViewController *vc=(FirstViewController *)app.firstViewController;
   vc=[[segue destinationViewController];

Now vc will refer to the same class rather than two different objects of the FirstViewController and then you can see the changes done together.

A: Try changing your FirstViewController like this...
FirstViewController.h
@interface FirstViewController : UIViewController

@property (strong, nonatomic) NSString *concentrationString;
@property (strong, nonatomic) NSString *dOBString;

@end

FirstViewController.m
#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController ()

// anything that isn't accessed from outside this class should be
// in the private category extension.
@property (nonatomic, weak) IBOutlet UILabel *concentrationLabel;
@property (nonatomic, weak) IBOutlet UILabel *dOBLabel;

@end

@implementation FirstViewController

...

- (void)viewDidLoad
{
    [super viewDidLoad];

     self.concentrationLabel.text = self.concentrationString;
     self.dOBLabel.text = self.dOBString;
}
...

I think you are confusing the program with ivars and properties that are not actually pointing to the same thing.
When you use a property *always refer to it using self.property. (Unless in the getter, setter or constructor where you should use _property).
By changing the code this way you should find it works.
Also, variable names start with a lowercase letter and use camel case.
i.e. DOBlabel is not OK... dOBLabel is OK.
concentrationlabel is not OK... concentrationLabel is OK.


text:
Q: Keras building a network for 9 dimensional feature vector I have the following simple data set. It consists of 9 features and it is a binary classification problem. An example of the feature vectors are show below. Each row has its corresponding 0,1 label.
30,82,1,2.73,172,117,2,2,655.94
30,174,1,5.8,256,189,3,2,587.28
98.99,84,2,0.84,577,367,3,2,1237.34
30,28,1,0.93,38,35,2,1,112.35
...

I know CNNs are used extensively for image classification, but I'm trying to apply it to the data set I've at hand. I'm trying to apply 5 filters each of size 2. I've been stuck with getting the network to be built in the right way given the shape of this data. Here is my function that builds the network.
def make_network(num_features,nb_classes):
   model = Sequential()
   model.add(Convolution1D(5,2,border_mode='same',input_shape=(1,num_features)))
   model.add(Activation('relu'))
   model.add(Convolution1D(5,2,border_mode='same'))
   model.add(Activation('relu'))
   model.add(Flatten())
   model.add(Dense(2))
   model.add(Activation('softmax'))

I will also finally call a testing function to test the accuracy of the model I've created. The following function tries to achieve that
def train_model(model, X_train, Y_train, X_test, Y_test):

    sgd = SGD(lr=0.01, decay=1e-6, momentum=0.3, nesterov=True)
    model.compile(loss='binary_crossentropy', optimizer=sgd)
    model.fit(X_train, Y_train, nb_epoch=100, batch_size=10,
              validation_split=0.1, verbose=1)

    print('Testing...')
    res = model.evaluate(X_test, Y_test,
                         batch_size=batch_size, verbose=1, show_accuracy=True)
    print('Test accuracy: {0}'.format(res[1]))

When I make the model and pass it the training function I get the following error
Using Theano backend.
Traceback (most recent call last):
  File "./cnn.py", line 69, in <module>
    train_model(model,x_train,y_train,x_test,y_test)
  File "./cnn.py", line 19, in train_model
    validation_split=0.1, verbose=1)
  File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 413, in fit
    sample_weight=sample_weight)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1011, in fit
    batch_size=batch_size)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 938, in _standardize_user_data
    exception_prefix='model input')
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 96, in standardize_input_data
    str(array.shape))
Exception: Error when checking model input: expected convolution1d_input_1 to have 3:(None, 1, 9) dimensions, but got array with shape (4604, 9)

I'm new to Keras. I'm trying to adapt code from here. Any help or pointers would be much appreciated. Thanks in advance.

A: Your code model.add(Convolution1D(5,2,border_mode='same',input_shape=(1,num_features))) defines that the input should be in shape (batch_size, 1, num_features). However, X_train as well as X_test might be in shape (batch_size, 9), which is inconsistent.

def train_model(model, X_train, Y_train, X_test, Y_test):
    X_train = X_train.reshape(-1, 1, 9)
    X_test = X_test.reshape(-1, 1, 9)

    ....


text:
Q: AWS lambda to create ec2 instance using Launch template and boto3 only using the required permissions I am having problems setting the correct permissions to my IAM role that is assumed by a lambda function. The purpose of the lambda is to launch ec2 instance using the provided Launch Template. However, I am constantly getting You are not authorized to perform this operation.errors due to not correct permissions of the IAM role.
The only policy I am attaching at the moment to the role is this one:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:RunInstances",
                "ec2:GetLaunchTemplateData"
            ],
            "Resource": "*"
        }
    ]
}

Lambda boto3/python code:
import boto3

ec2 = boto3.resource('ec2')

lt = {
    # 'LaunchTemplateId': 'lt-0b91c7e5c5437a1c1',
    'LaunchTemplateName': 'template_name',
    'Version': '$Latest'
}

def handler(event, context):

    instances = ec2.create_instances(
        LaunchTemplate=lt,
        MinCount=1,
        MaxCount=1
        # UserData=user_data
    )

Note: If I attach AmazonEC2FullAccess AWS Managed policy to the lambda role it works fine
What am I missing?
Also, is there an easy way of finding what are the "bare minimum" IAM policy permissions that are needed by a resource to function?

A: Based on the comments.
Often, RunInstances permission is not enough to launch an instance. What permissions are required depends on what does the instance do, e.g. uses KMS encrypted volumes, iam instance roles/profiles, set tags and more.
In the OPs case, the instance to be launched was using tags, thus ec2:CreateTags permission was needed to make it work.


text:
Q: Reuse last facebook login session after reopening application I want to re-login a Facebook user in parse without showing login dialog of Facebook using saved TOKEN in Parse.
I am using 3 methods for save and restore session but how to use them in Facebook object of ParseFacebookUtils?
/*
 * Save the access token and expiry date so you don't have to fetch it each
 * time
 */
public static boolean save(Facebook session, Context context) {
    Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
    editor.putString(TOKEN, session.getAccessToken());
    editor.putLong(EXPIRES, session.getAccessExpires());
    editor.putLong(LAST_UPDATE, session.getLastAccessUpdate());
    return editor.commit();
}

/*
 * Restore the access token and the expiry date from the shared preferences.
 */
public static boolean restore(Facebook session, Context context) {
    SharedPreferences savedSession = context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
    session.setTokenFromCache(
            savedSession.getString(TOKEN, null),
            savedSession.getLong(EXPIRES, 0),
            savedSession.getLong(LAST_UPDATE, 0));
    return session.isSessionValid();
}

public static void clear(Context context) {
    Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
    editor.clear();
    editor.commit();
}

And i am restoring session by following before login-
    ParseFacebookUtils.initialize(APP_ID);
    // restore session
    restore(ParseFacebookUtils.getFacebook(), this);
    // login using restored data
    ParseFacebookUtils.logIn(permissions, LoginActivity.this,
            new LogInCallback() {
                @SuppressWarnings("deprecation")
                @Override
                public void done(ParseUser user, ParseException e) {

                // work after login

                        ParseUser.enableAutomaticUser();
                        save(ParseFacebookUtils.getFacebook(),this);
                }});

But it's not working it always opens login dialog of facebook.

A: I solved it by calling openActiveSession method with allowLoginUI = false in onCreate() method of my Activity.
My code is-
ParseFacebookUtils.getSession().openActiveSession(this, false, new Session.StatusCallback() {

@Override
public void call(Session session, SessionState state, Exception exception)
{
     if (session.isOpened()) {

        ParseFacebookUtils.logIn( LoginActivity.this,
                        new LogInCallback() {

                            @Override
                            public void done(ParseUser user, ParseException e) {
                            // user logged in
                            }

                    });
              }
              else
              {
                // error found
              }
           }
        });


text:
Q: Call to a member function getClientOriginalName() on array I have a multiple image. When I upload multiple image. I get this error.

Call to a member function getClientOriginalName() on array

my blade
<form action="{{ route('design-studios.store') }}" method="post" enctype="multipart/form-data">
    @csrf

        Title
        <input type="text" class="form-control" id="title" name="title" value="{{ old('title') }}">

   //......

        <fieldset class="border p-3">
            <legend>Slideshow</legend>

                Image
                <input id="sliders" name="sliders[]" type="file" multiple class="form-control">

        </fieldset>

</form>

My Controller.
public function store(Request $request)
{
    $design_studio = new DesignStudio;
    $design_studio->user_id = 1;
    $design_studio->title = $request->title;
    $design_studio->lang = $request->lang;
    $design_studio->body = $request->body;
    if($request->has('image')) {
        $image = $request->file('image');
        $filename = $image->getClientOriginalName();
        $image->move(public_path('images/design-studio'), $filename);
        $design_studio->image = $request->file('image')->getClientOriginalName();
    }
    if ($sliders = $request->file('sliders')) {
        foreach ($sliders as $slider) {
            $filename = $slider->getClientOriginalName();
            $slider->move(public_path('images/design-studio'), $filename);
            $design_studio->sliders = $request->file('sliders')->getClientOriginalName();
        }
    }
    $design_studio->save();
    $design_studio->categories()->attach($request->category);
    return redirect()->route('design-studios.index');
}

My Model
protected $casts = [
    'sliders' => array()
];

I get this error.

Call to a member function getClientOriginalName() on array

A: Here you need to call that method on the file you are looping through instead of trying to call it on the array of files.
$design_studio->sliders = $slider->getClientOriginalName();


text:
Q: Question regarding SF User Name, and Email updates while keeping passwords Our company is rebranding , thus we need to update both the salesforce (SF) user name and email for both the Marketing and System Admin user accounts we need for an external client's non-production orgs. We don't need to freeze the 2 current users, just change their user names and email addresses to the ones that our network admin will be changing in Outlook. Therefore, we believe that we can maintain the passwords also. Otherwise, if we can't keep our present passwords for these 2 users, there will be more work to update the various integrations that also do api calls to SF.
Question:

*

*If our Network Admin changes both the Marketing and System Admin user emails in outlook (when rebranding time arrives), and no user updates have been done on our client's lower SF orgs, we should still be able log into these orgs using the old/current username and and passwords to make the new Username and email updates to the external clients SF orgs such that the new email addresses match the ones that our Network Admin has created for our 2 Outlook marketing and System Admin users, correct?

*After the user name and email changes have been made in Salesforce, we should still be able to keep the passwords associated with the 2 users before the username and email updates correct?
Thanks much

A: For my company's purposes we have created the newly branded email address while creating an alias to the old email so that the SF user account will still get email directed to the user's rebranded inbox whenever email notifications are sent from SFDC to the user's old email address. The process is similar to call forwarding for phones. The alias will stay up for an "unlimited amount of time".


text:
Q: Dont accept Null Values to store into an array How do I need to code so that the array token[] doesn't take the null values read? The code is as follows.
String[] token = new String[0];
String opcode;
String strLine="";
String str="";
    try{
        // Open and read the file
        FileInputStream fstream = new FileInputStream("a.txt");

        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        //Read file line by line and storing data in the form of tokens
        if((strLine = br.readLine()) != null){

                token = strLine.split(" |,");//// split w.r.t spaces and ,

  // what do I need to code, so that token[] doesnt take null values

            }
            }
        in.close();//Close the input stream
    }

A: Yes, you can set null values into elements of array. If you want the token to prevent null values then you should check it first before assignment. But in your code the token array accepts only one element at index 0. If you need to set many elements consider to use List. And what you've assigned is just overridden by the other array returned by the split.
String[] token = strLine.split(" |,");
if(token!= null && token.lingth >0){

  // use the array

A: An object oriented way to handle this is to make a new class that encapsulates the token array.  Give this class a way to set and get elements.  The set method will throw an exception if a null is passed in.
public void setElement(int index, String element) {
    if (element == null)
        throw new IllegalArgumentException();
    //...
}

In your case since you're not creating the token array, you'd populate your new class from it:
for each t in token
   myEncapsulation.setElement(loopCount, t);

This is pseudo code of course.

A: Disclaimer:
I'm not really sure what your question is about, maybe you should add some details.
Anyway, from the returns section of split method javadoc:

Returns:

the array of strings computed by splitting this string around matches of the given regular expression

Here is a link: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String, int)
So the split method always returns a String array. If the passed regexp doesn't match it will return a String array with just one element: the original String.
This line:
if(strLine.split(" |,")!=null){

Should become like this:
String[] splittedStrLine = strLine.split(" |,");
if(splittedStrLine.length > 1) {

Hope this helps


text:
Q: Azure Cognitive Search query results are not JSON but String in Unicode notation enclosed in double quotes In the official documentation, the query result is shown in JSON notation with syntax highlighting as shown below.

In my environment, the query result of Azure Cognitive Search is not JSON, but a String with Unicode notation enclosed in double quotes.
How can I get the decoded string in JSON instead of unicode?
"content\":\"\\n\\u30c6\\u30b9\\u30c8\\u7528\\u306e\\n\\nPDF\\u30d5\\u30a1\\u30a4\\u30eb\\u3067\\u3059\\u3002\\n\\n\\n\"

A: THis is a known issue with the portal search explorer, and will be fixed sometime this week. In the meantime, if you use any other HTTP client such as Postman to do your queries, you should the results in JSON format as expected.


text:
Q: iOS: How to display a small view on top of main view? I'm new here, don't be very hard on me :)
Learning iOS development and trying to display a small view to enter some data to my app, which is using storyboards.
I tried adding it as subview but I can't move it from the top-left corner or make the background to fade. Any advice on how to do this?
Forgot to mention that this is for iPhone.
Thanks

A: Based on your comment it seems that you don't have a clear understanding of the difference between UIView and UIViewController.
Think of a UIViewController as your screen. Your screen might be showing many different views at once, but they are all part of the UIViewController's view.
Rather then present a new UIViewController (i.e. screen), you want to do something like this:
//Use a XIB for this, not a storyboard
UIView *newView = [[[NSBundle mainBundle] loadNibNamed:@"addData" owner:self options:nil] lastObject];
[self.view addSubview:newView];

I suggest reading these two guides from Apple until you understand the difference between a UIView and a UIViewController:
View Programming Guide
View Controller Programming Guide


text:
Q: Navigation bar works fine in iOS 8 but doesn't show up in iOS 7 (swift) Pushing ViewController programmatically works fine in iOS 8 but in iOS 7 it neither shows navigation bar nor the bottom bar.
I tried:-  self.navigationController?.setNavigationBarHidden(false, animated: false)
but it doesn't work.
My code for pushing view controller is
let viewController = storyboard!.instantiateViewControllerWithIdentifier("info View") as infoViewController
viewController.isCompanyContact = true
self.navigationController?.pushViewController(viewController, animated: true)


text:
Q: UiBinder custom widget with parameterized constructor Let's say we have a custom widget that was declared using UiBinder and it needs to have some arguments in its constructor. How can I make it in order to be able to supply these arguments when i declare it in ui.xml?
That is i have a
CustomWidget(int param1, int param2)

and when i add it to a ui.xml i need to be able to do:
...

xmlns:my="urn:import:...">

<g:Container>
 <my:CustomWidget param1="1" param2="arg2"/>
</g:Container>

A: Use @UiConstructor on your constructor:
@UiConstructor
CustomWidget(int param1, int param2)

Look at docs: http://code.google.com/webtoolkit/doc/latest/DevGuideUiBinder.html#Using_a_widget


text:
Q: Strange number error in HLSL I have a very-very strange problem with my project. I tried to send an index number with my vertices, and use this number in the HLSL shader.
But, when I set this number to a value, like, 1, the shader get a very wide spectrum from that number - going down to negative value, between 0-1 and above 1. Even when I give in nonsense numbers, like 10000
(I use C# with SlimDX, and this is made with pixel shader 2.0 and I tried 3.0 as well.)
        int c = 0;

        int testValue = 10000;

        for (int i = 0; i < tris.Length; i++)
        {
            vertices[c].Position = tris[i].p0;
            vertices[c].Normal = tris[i].normal;
            vertices[c].Index = testValue;
            vertices[c++].Color = Color.LightBlue.ToArgb();

            vertices[c].Position = tris[i].p1;
            vertices[c].Normal = tris[i].normal;
            vertices[c].Index = testValue;
            vertices[c++].Color = Color.LightBlue.ToArgb();

            vertices[c].Position = tris[i].p2;
            vertices[c].Normal = tris[i].normal;
            vertices[c].Index = testValue;
            vertices[c++].Color = Color.LightBlue.ToArgb();
        }

This is how I create my vertices. Everything works as they should work, except the Index value. I get the colors right, I get the normals right, I get the position right.
Here is the HLSL code:
VertexToPixel IndexedRenderedVS( float4 inPos : POSITION, float4 inColor : COLOR0, float3 inNormal : NORMAL, int inIndex : TEXCOORD0)
{
VertexToPixel Output = (VertexToPixel)0;

float4x4 xWorldViewProjection = mul(xWorld, xViewProjection);

Output.Position = mul(inPos, xWorldViewProjection);

if (inIndex < 0)
    Output.Color = float4(1, 0, 0, 1);

 if (inIndex > 0 && inIndex < 1)
     Output.Color = float4(0, 1, 0, 1);

 if (inIndex > 1)
     Output.Color = float4(0, 0, 1, 1);

 //Output.Color = inColor;

return Output;
}

 PixelToFrame IndexedRenderedPS(VertexToPixel PSIN)

 {
 PixelToFrame Output = (PixelToFrame)0;

 Output.Color = PSIN.Color;

 return Output;
 }

And finally, my VertexFormat struct:
    internal Vector3 Position;
    internal int Color;
    internal Vector3 Normal;
    internal int Index;

    internal static VertexElement[] VertexElements = new VertexElement[]
    {
        new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
        new VertexElement(0, sizeof(float) * 3, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
        new VertexElement(0, sizeof(float) * 7, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Normal, 0),
        new VertexElement(0, sizeof(float) * 10, DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
        VertexElement.VertexDeclarationEnd
    };

    internal static VertexFormat Format
    {
        get { return VertexFormat.Position | VertexFormat.Diffuse | VertexFormat.Normal | VertexFormat.Texture1; }
    }

With this code, and an insane index value (10000 - I get a same picture, no matter what values I give in, 0, 1, or even when I put negative numbers in. It just dont care what I give in).
I get this picture:

Anybody have any idea where I make a mistake? I simply cant find where I misplaced some value. Tried a huge number of vertex declaration, changed everything in inside the shader - and now I offically ran out from ideas.
Any help is appreciated. Thank you :)

A: In DirectX, texture coordinates are always floats, usually a float2, but sometimes a float3 or float4 (you can specify a float1, but if you do you'll actually get a float2 in the assembly and the runtime will throw away the second channel). You're typing it on the CPU side as an int, and then in the vertex description as a float1, and finally in the shader as an int. I would recommend typing all of these as float2 to start.


text:
Q: Ubuntu 12.4 HDD files can't be seen by XP on an external USB drive Due to a power supply malfunction I rescued the hard drive and placed it into an external USB storage box and plugged it into an XP professional O/S computer to recover emails, music etc but XP cant see the files but does see the drive.
The system was working 100% and I am certain the files are there but XP cannot see any of Linux but the used disc is right. Any ideas anyone?

A: By default, Windows can't read ext2/3/4 file systems - unless you specifically went out of your way to format your drive in a different file system when you installed Ubuntu, your files are probably in one of those file systems.
You'll need to install software on Windows that can read those file systems.
This article suggests three tools that you can try, but I don't have any personal experience with them myself: http://www.howtogeek.com/112888/3-ways-to-access-your-linux-partitions-from-windows/
If you try to read them from another Linux machine, you should not have this problem.
Good luck!

A: You can also use a live CD, Mount the drive and recover your files that way
 cd mkdir /mnt/backup
 sudo mount /dev/sda1 /mnt/backup

You may need to change sda1 to match your actual settings.
Now you can access the drive from /mnt/backup
If you have a decent size usb drive, I would setup img on usb with persistence so you can recover your files of the flash later when you get Ubuntu back up.
If you want to be able to use the drive with Windows, you need a ntfs partition.

A: Thank you for your replies. I tried 2 of the "Howtogeek" options but having downloaded them neither could see the Ubuntu HDD either when on USB or mounted in the desk unit. After many tries I had to disconnect the XP HDD to get the Ubuntu 12.4 load as thr master and then select the files manually to copy to the USB key.
There were many visits to the internet to find where bookmarks, emails & address book files were hidden to copy. Then reconnect the XP drive and copy/paste or import the files where they ought to be after many more explorations of the web to discover where they needed to be.
There were a few things that didn't transfer or got corrupted but that's computers but 98% arrived where they were supposed to be after 48hrs of following advise given, my thanks as a complete novice I would either be at a computer engineer pleading for help and checking the bank account or on pills.
Lesson learnt BACK UP or PRINT important files and before taking anything apart copy files to another storage device!
Those younger than 50 probably could have done this in an afternoon, its a language thing in some cases, but those more creaky are fumbling around in the dark as the computer speak is totally alien and we're worried about breaking what we don't understand beyond repair.
Again my thanks its running!
P.S If the answers the computer what was the question?


text:
Q: How to observe changes for sliding page in Room database? What I mean, I want to create something like a sliding window/paginator with a fixed number of items for Room database. For example (look at the image below by link), I create any RecyclerView that should only show 4 elements of some data. If a new item was inserted in the database (fifth item), the window will automatically slide down (will remove the oldest item from list and insert the new item), and RecyclerView adapter will receive changes about deletion and insertion by callback. But the database will have 5 items. I know that there is PagedList for pagination, but I don't know how to use it correctly for this behavior.
It is possible to do this in the Realm database, making RealResults with some filter and observe changes using the listeners OrderedRealmCollectionChangeListener. I want to create such an analogue for Room database.
Is it possible to observe changes like that for Room database? Or is there some ready solution or library?
Picture to clarify the question


text:
Q: URL Rewriting from a Plugin based on custom values I am developing a plugin where Admin can integrate the plugin to a page where newly added products will be shown.. So, let's say user add the plugin to a page named my-page.
So, the main content of the plugin will be shown in mysite.com/my-page/
Users can upload products and their uploaded products will be shown in
    mysite.com/my-page/user/user-name
The admin will have the ability to add custom fields to the products. If admin create a custom field named category, mysite.com/my-page/category/category-name will show all the products with the category, category-name. All the pages will also have pagination support to restrict products per page. So, I need to create a rewrite rule on fly, every time Admin create a new custom field.
I know how to rewrite URL and add custom query variables but in this case I don't know the page name where it will be inserted and custom fields will be inserted in the database. So, basically I need dynamic URL rewriting. Is this kind of rewrite possible?

A: I have done it like this. From the plugin admin menu, I have created option where user can select the page where they want to install the plugin. Based on the value selected, the URL rewriting was done and the selected page id is stored as an option field. I created two custom variable for this. The plugin serve template file for that page based on the value of the custom variables.


text:
Q: KineticJS: Group vs. Layer Despite my best Google-fu, nowhere in the main tutorial or the KineticJS docs does it explicitly state the difference between a group and a layer. Kinetic's "Getting Started" page sort of addresses this--it mentions that layers have special renderers, although I don't quite understand what that means. So do groups not have those renderers? Can groups not be inside of layers? What makes layers (or groups) different than just a parent to a bunch of nodes for organization/transformation?
Essentially, what's the difference between a group and a layer?

A: Group is simply a collection of KineticJS defined objects within a layer, while each layer is a separate Canvas (or used to be until version 3.x of KineticJS) you can see the difference by adding multiple layers on a stage. Also, in the framework hierarchy, a group is contained inside a layer and not the other way around. So you can display/render multiple groups at one time but not multiple layers (only the topmost one is visible).


text:
Q: Network response too late? i have a registration function that registers a user in my app.
If registration is successfull, my webapi will return "success" otherwise "error".
this part will ALWAYS be "else" even if my status variable is "success":
if(register_response=="success") {

http://pastie.org/private/jizl7udishhbdgvf5qlb9q
How can that be? i cannot see the error :|

A: This is java related.
When comparing String you should use equals()


text:
Q: How do you save data to database using EXT: Form in TYPO3 8.7.1? I need to create a contact form to allow users to send emails. Data must be saved in the database and notification send to the user. So far, I've been using EXT: Powermail, which works fine. In current project I'm using TYPO3 8.7.1 and I'd like to use EXT: Form 8.7.0. I've a test installation based on Introduction Package. I'm using predefined "Contact Form", but in the edition mode, I can't select finisher "Save to database". The only finishers I can see are: email to sender, redirect to a page, delete uploads.

*

*how to enable finisher to save form data into database? and where to select "Storage Id"?

*is it possible to list all records (emails) in List module similar as it is in Powermail extension?

I've been searching for some tips in a documentation, but couldn't find that.

A: There is a SaveToDatabase-Finisher in the new Form Framework, but as far as I know you can only use it programmatically via YAML or API.
Here is the link to the corresponding doc: https://docs.typo3.org/typo3cms/drafts/code.tritum.de/TYPO3.CMS/Form_Documentation/ApiReference/Index.html#savetodatabase-finisher


text:
Q: The invertible polynomial are only the one of degree 1 ( with $\mathbb{Z}_n$ I mean $\frac{ \mathbb{Z} }{ n\mathbb{Z} }$ )

Theorem :
Let $\psi,\phi \in \mathbb{K}[x]$ be such that
$$\psi(\phi(x)) = x = \phi(\psi(x)) \; \forall x \in \mathbb{K}$$
Then there exists $m,q \in \mathbb{K}$
$$\psi(x) = mx + q \; \forall x \in \mathbb{K}$$

A way to prove this would be this one :
Let $\psi(x) = a_0 + a_1 + \dots + a_nx^n$ and $\phi(x) = b_0 + b_1x + \dots + b_mx^m$ with $a_n \neq 0 \neq b_m$.
Suppose by contradiction that $n \geq 2$, then $n^m \geq 2$
$$x = \phi(\psi(x)) = (\text{part of degree } \leq n^m - 1 ) + b_m(a_n)^m x^{n^m}$$
But this is a contradiction because if two polynomials are equal all the coefficients need to be equal so $b_m(a_n)^m = 0$ but I know that $b_m(a_n)^m \neq 0$.
The problem with this proof is that It works only on infinite fields $\mathbb{K}$
Take for example $\mathbb{Z}_3$, then the polynomials
$$\psi(x) = x^3$$
$$\phi(x) = x$$
Are inverses of each other, but $\psi$ is of degree $3$, In fact I have that
$$x = x^3 \; \forall x \in \mathbb{Z}_3$$
but clearly the coefficients aren't equal.
My question is : how can I prove the theorem?


text:
Q: Using selectors/filters on external collections - possible? I have a simple function that hides/shows nodes via a supplied filter parameter and the removal part works fine.  However I'm unable to apply the same filter on the collection of nodes I've already removed so I can restore just those ones. (Cytoscape newbie and my Javascript-fu is weak...)
  var hiddenOnes = cy.collection();

  var hideShow = function(selectorExpr, event) {

    if (event.target.checked == true) {
        var restoring = hiddenOnes(selectorExpr);  // problem is here!
        cy.add(restoring);
        } else {
            var nodesToHide = cy.nodes(selectorExpr);
            hiddenOnes = hiddenOnes.union( nodesToHide.remove() );
            }
  }

I understand why the selector expression can't be used on the hiddenOnes collection, I just want to know how to do it!

A: hiddenOnes can not be used like hiddenOnes(selector).  Use hiddenOnes.filter(selector).
Refer to the docs: https://js.cytoscape.org/#eles.filter
And the Chrome debugger docs are useful for identifying certain types of problems: https://developers.google.com/web/tools/chrome-devtools/javascript/


text:
Q: Hiding CloudFormation/SAM secret in Aws Console Template tab Suppose I have the following secret in a Cloud Formation (or SAM) template which I deploy to my AWS IAM account as part of a stack (with of course the sensitive value of the SecretString dynamically assigned by the script that runs the cloud formation deployment):
Resources:

  MySecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Name: MySecret
      Description: Embarssing fact I want to keep secret
      SecretString: "I_think_Twighlight_Sparkle_is_cool"

When I examine the stack page on the aws console I notice the "template" tab displays the whole template including this secret in plain text.
This seems very undesirable to me, and I am wondering if there is someway of mitigating it that I am missing. While only people with access to the IAM account can go to the aws console, it seems undesirable to have secrets pop up in plain text unless one is specifically requesting to see them.
Anybody know of a good way to mitigate this?

A: From your explanation I assume you only want to hide the plaintext value when viewing from console. The closest you can get using your method would be using NoEcho in parameters.
An example of what you could do is move the string you want to mask into a parameter then set the parameter property NoEcho to True, then you only need to reference that parameter value in your resource.
However, this won't solve your issue of the value being visible inside the template, as the docs point out:

"we recommend you use dynamic parameters in the stack template to reference sensitive information that is stored and managed outside of CloudFormation"

What this is saying is that using your current architecture you are unable to hide the value within the template. Instead you would need to reference the value outside of the template or create an elaborate custom resource which creates your secret value. Other than that, as you pointed out, can be restricted via IAM permissions.

A: Another option is to use Secrets Manager to manage secrets and use these secrets in CF templates.