text:
Q: Unexpected behavior of minimal flow in Spring Integration I'm creating a new flow and started from almost empty definition
@Bean
public IntegrationFlow routerFlow() {
    return IntegrationFlows
            .from(routerInputChannel())
            .channel(routerOutputChannel())
            .get();
}

So far so good. But if I add simple wireTap line
@Bean
public IntegrationFlow routerFlow() {
    return IntegrationFlows
            .from(routerInputChannel())
            .wireTap(m -> System.out.println(m))
            .channel(routerOutputChannel())
            .get();
}

I received exception
Caused by: org.springframework.beans.factory.BeanCreationException: The 'IntegrationFlow' can't consist of only one 'MessageChannel'. Add at lest '.bridge()' EIP-method before the end of flow.
    at org.springframework.integration.dsl.IntegrationFlowDefinition.get(IntegrationFlowDefinition.java:2670)
    at org.springframework.integration.dsl.IntegrationFlowBuilder.get(IntegrationFlowBuilder.java:26)
    at org.springframework.integration.dsl.IntegrationFlowDefinition.wireTap(IntegrationFlowDefinition.java:329)
    at org.springframework.integration.dsl.IntegrationFlowDefinition.wireTap(IntegrationFlowDefinition.java:263)
    at com.xxx.xxx.xxx.xxx.config.RootConfiguration.routerFlow(RootConfiguration.java:29)

What is the reason of such exception?
I use Spring Integration 4.3.7.RELEASE and Spring Integration Java DSL 1.1.4.RELEASE

A: Well, that is indeed unexpected.
The wireTap() has signature:
public B wireTap(IntegrationFlow flow) {

Where IntegrationFlow is functional interface and therefore can be specified by the Lambda. At the same time the argument of that Lambda can really be sent to the System.out.println(). If we convert your Lambda to the interface implementation we'll see:
.wireTap(new IntegrationFlow() {

        @Override
        public void configure(IntegrationFlowDefinition<?> x) {
            System.out.println(x);
        }

})

As you see there is really no anything about the message you would expect with your Lambda for .handle().
And you should see something like this in your logs:
org.springframework.integration.dsl.IntegrationFlowBuilder@6995bf68

That is exactly SOUT of the System.out.println(IntegrationFlowDefinition)...
So, to fix your problem we should have something like this:
.wireTap(flow -> flow.handle(System.out::println))

I don't know what we can do from the Framework perspective. I'm pretty sure any @FunctionalInterface-based construction suffers the same problem if we provide a Lambda with the Object.toString() signature. That is just some nasty side-effect of the syntax sugar IMO :-).


text:
Q: PDF::Create incorrectly converts french accented characters My Perl program can successfully convert english text to pdf using the PDF::Create module.  However, french accented characters do not display correctly in the PDF file.
Here is a line from the plain text file containing french characters:

VÉRIFIER DÉCLARATION DE DROITS-FORMALITÉS

Here is what the same line looks like in the PDF file:

VÉRIFIER DÉCLARATION DE DROITS-FORMALITÉS

Here is the relevant code:
$page = $pdf->new_page('MediaBox' => [0,0,$pdfWidth,$pdfHeight]);
$font1 = $pdf->font('Subtype'=>'Type1',Encoding'=>'WinAnsiEncoding','BaseFont'=>'Courier');
$page->string($font1, $fontSize, $leftMarg, $yCoord, $pdfLine);

where $pdfLine contains the plain text.
The program reads in a file with this content:

azAZàâäçèéê
ÉTAT DES DEMANDES INACTIVES - OPÉRATION DES BREVETS
TÂCHE
VÉRIFIER DÉCLARATION DE DROITS-FORMALITÉS
VÉRIFIER LISTAGE DES SÉQUENCE-FORMALITÉS

A: My guess is that $pdfLine is UTF-8 encoded. You would want to decode it into unicode code points before writing it to the PDF.
use Encode 'decode';
$page->string($font1, $fontSize, $leftMarg, $yCoord, decode("UTF-8",$pdfLine));

You could also handle decoding at the input filehandle with an encoding layer:
open my $fh, '<:encoding(UTF-8)', "file/that/contains/the/plain.txt";
...
$pdfLine = <$fh>;
...
$page->string($font1, $fontSize, $leftMarg, $yCoord, $pdfLine);

A: I fixed the problem by installing an old version of PDF::Create.  I was running version 1.42 and I installed version 1.31.  French accented characters display fine using version 1.31.  So, somewhere between 1.31 and 1.42 the conversion of accented characters was broken.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Correct way to define contextType in NexusJS while using NextJS I trying to get Prisma and Nexus working with NextJS, but I am having some trouble defining the contextType in the GraphQL schema.
I define the schema like this:
export const schema = makeSchema({
  types: [Query, User, Mutation],
  contextType: {
    module: require.resolve("./graphql/context"),
    export: "Context",
  },
  plugins: [nexusPrisma({ experimentalCRUD: true })],
  outputs: {
    typegen: path.join(process.cwd(), "generated", "nexus-typegen.ts"),
    schema: path.join(process.cwd(), "generated", "schema.graphql"),
  },
});

The error occurs when I start the development server by running npm run dev. The error is as follows:
Module not found: Can't resolve './graphql/context'
  46 |   types: [Query, User, Mutation],
  47 |   contextType: {
> 48 |     module: require.resolve("./graphql/context"),
     |            ^
  49 |     export: "Context",
  50 |   },
  51 |   plugins: [nexusPrisma({ experimentalCRUD: true })],

This is the context.ts file:
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export interface Context {
  prisma: PrismaClient;
}

export function createContext(): Context {
  return { prisma };
}

My dependencies are these:
  "dependencies": {
    "@prisma/client": "^2.13.1",
    "apollo-server-micro": "^2.19.1",
    "next": "latest",
    "nexus": "^1.0.0",
    "nexus-plugin-prisma": "^0.27.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
  },
  "devDependencies": {
    "@prisma/cli": "^2.13.1",
    "@types/node": "^12.12.21",
    "@types/react": "^16.9.16",
    "@types/react-dom": "^16.9.4",
    "typescript": "^4.1.3"
  },

I have been trying to look for a solution, but for now I am stuck. I think it might have something to do with NextJS and its Webpack configs, but I have absolutely no knowledge about those so I don't really know what to try.
Any help is appreciated.
Project tree:
root
├─ generated
│  ├─ nexus-typegen.ts
│  └─ schema.graphql
├─ graphql
│  ├─ context.ts
│  └─ schema.ts
├─ interfaces
│  └─ index.ts
├─ next-env.d.ts
├─ package-lock.json
├─ package.json
├─ pages
│  ├─ api
│  │  ├─ graphql.ts
├─ prisma
│  └─ schema.prisma
├─ tsconfig.json

A: I think the error is in the path you provided for your module. Assuming that you've defined the schema in ./schema.ts, your context type should look like this as it's the relative path that you need to specify
contextType: {
  module: require.resolve("./context"),
  export: "Context",
}

A: This way worked for me:
  contextType: {
    module: path.join(process.cwd(), "graphql", "context.ts"),
    export: "Context",
  }


text:
Q: list of supported operations on tensorflow post training quantization I am looking to compress/optimise my tensorflow NN model following tensorflow-lite's post training quantization guild, I am using Tensorflow 1.13.1 (NON GPU)
However, when I use the convert function I've met with a lot of error messages:
ConverterError: TOCO failed. See console for info.
2019-05-02 11:31:10.209374: I tensorflow/lite/toco/import_tensorflow.cc:1324] Converting unsupported operation: TensorArrayV3
2019-05-02 11:31:10.217858: I  tensorflow/lite/toco/import_tensorflow.cc:193] Unsupported data type in placeholder op: 20
2019-05-02 11:31:10.217893: I  tensorflow/lite/toco/import_tensorflow.cc:1324] Converting unsupported operation: TensorArrayV3
2019-05-02 11:31:10.217905: I  tensorflow/lite/toco/import_tensorflow.cc:193] Unsupported data type in placeholder op: 20
2019-05-02 11:31:10.217939: I  tensorflow/lite/toco/import_tensorflow.cc:1324] Converting unsupported operation: TensorArrayScatterV3
2019-05-02 11:31:10.217961: I  tensorflow/lite/toco/import_tensorflow.cc:1324] Converting unsupported operation: Enter
2019-05-02 11:31:10.217971: I  tensorflow/lite/toco/import_tensorflow.cc:1324] Converting unsupported operation: Enter
2019-05-02 11:31:10.217979: I  tensorflow/lite/toco/import_tensorflow.cc:1324] Converting unsupported operation: Enter
2019-05-02 11:31:10.217988: I  tensorflow/lite/toco/import_tensorflow.cc:1324] Converting unsupported operation: Enter
......
2019-05-02 11:31:10.223877: I tensorflow/lite/toco/graph_transformations/graph_transformations.cc:39] Before Removing unused ops: 236 operators, 384 arrays (0 quantized)
2019-05-02 11:31:10.226115: I tensorflow/lite/toco/graph_transformations/graph_transformations.cc:39] After Removing unused ops pass 1: 226 operators, 368 arrays (0 quantized)
2019-05-02 11:31:10.229770: I tensorflow/lite/toco/graph_transformations/graph_transformations.cc:39] Before general graph transformations: 226 operators, 368 arrays (0 quantized)
2019-05-02 11:31:10.232686: I tensorflow/lite/toco/graph_transformations/graph_transformations.cc:39] After general graph transformations pass 1: 177 operators, 280 arrays (0 quantized)
2019-05-02 11:31:10.235370: I tensorflow/lite/toco/graph_transformations/graph_transformations.cc:39] Before dequantization graph transformations: 177 operators, 280 arrays (0 quantized)
2019-05-02 11:31:10.237009: F tensorflow/lite/toco/tooling_util.cc:627] Check failed: dim >= 1 (0 vs. 1)
Aborted (core dumped)

Having Googled/SO around it seems this is because not all tensorflow operaions are supported by tf-lite. My model has customised operations such as attention, biLSTM etc.
How do I know which NN architectures are supported? For the errors I received, how do I know where is the source of the problem?  e.g.
Unsupported data type in placeholder op: 20

what is this 20 refers to?

A: The source of the problem is in ConvertDataType() function here.
The unsupported datatype 20 is
38: DT_RESOURCE = 20;


text:
Q: Is there a javascript equivalent of .= for self concatenating? Rather than doing
my_var = my_var+'extra string';

is there a shorthand method like .= in php?

A: Performance Tip (note — this advice is valid for IE6, but it's no longer worth worrying about in 2014)
If you're writing some Javascript code to build up a long string (say, a fairly big block of HTML, or a long parameter list for an ajax request), then don't get in the habit of doing this:
var longString = "";
for (var i = 0; i < someBigNumber; ++i) {
  if (i > 0) longString += "
" + whatever;
  longString += someMoreStuff();
}

As the longString gets longer and longer, Internet Explorer will puff harder and harder on each iteration of the loop. Even when someBigNumber isn't really that big, the performance of that loop can be really terrible.
Luckily, there's an easy alternative: use an array:
var accumulator = [];
for (var i = 0; i < someBigNumber; ++i) {
  accumulator.push(someMoreStuff());
}
var longString = accumulator.join("
" + whatever);

Way, way faster in Internet Explorer than repeated string appends.

A: Use +=
var s = 'begin';
s += 'ning';

A: +=

Example:
my_var += "extra string";

A: Yes: my_var += 'extra string';


text:
Q: Разделить строку не через char, а через string Имеется строка
string str = "123|&|321|&|323|&|121";

Нужно разделить данную строку посимвольно и записать в массив.
Я понимаю что можно создать функцию и т.д. Но можно как то перегрузить String.Split()
Конечный результат должен быть таким
{ 123, 321, 323, 121 }

A: str.Split(new string[] { "|&|" }, StringSplitOptions.None);

Доки по string array overload, руссиш версион


text:
Q: WebGL - Width, height parameters passed in validateCompressedTexSubDimensions() function? I am working on some compression support in WebGL-Webkit. So I was looking at existing S3TC support provided in WebGLRenderingContext.cpp file in Webkit code. What confuses me is the code written inside "validateCompressedTexSubDimensions(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, ArrayBufferView data)"
s3tc extension spec says that you should throw an error in your application if:
" plus  is not equal to texture width*";
Then how is it that in the existing webkit code for the function validateCompressedTexSubDimensions() for S3TC, the code goes on something like this:
 "if (width - xoffset > tex->getWidth(target, level) {synthesizeGLError("blah blah") }"
Is this code right? If so, then what is the meaning of "width", and "tex->getWidth()" in the webkit code.
Is width the width of the sub-image or the actual width of the complete tex2D texel array?
And what does the constant "TEXTURE_WIDTH" stand for?
Looking forward to your useful comments :)


text:
Q: How to make speech recognizer rwork on whole screen I am making an application for visually impaired people and for that I want that whenever user touches anywhere on screen the speech recognizer should start.
I have made speech recognizer and other things..but I am not able to make my speech recognizer to work on TouchListener...
TouchListener is not taking the activity as view. application crashes
Complete code is as below.
public class MainActivity extends Activity
{

private static final int REQUEST_CODE = 1234;
private ListView wordsList;
protected Button TextToSpeech;
/**
 * Called with the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.voice_recog);
Button speakButton = (Button) findViewById(R.id.speakButton);
Context context;
context = this.getApplicationContext();
Intent Inte = new Intent(context, FallDetection.class);
context.startService(Inte);
Intent Inte1 = new Intent(context, SmsSpeaker.class);
context.startService(Inte1);
Toast toast = Toast.makeText(getApplicationContext(), "Fall Detection Started", Toast.LENGTH_LONG);
toast.show();

 wordsList = (ListView) findViewById(R.id.list);
 LinearLayout myScreen = (LinearLayout) findViewById(R.id.myscreen);
// change LinearLayout to your framelayout if it is not a LinearLayout
//View view =(View) findViewById(R.layout.voice_recog);

//wordsList.setOnTouchListener(new View.OnTouchListener() {
 myScreen.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Toast toast = Toast.makeText(getApplicationContext(),"Touch recognised",Toast.LENGTH_LONG);
        toast.show();
        startVoiceRecognitionActivity();
    }
});

as of now I am using List for recignizing touch but that is also crashing application with Source not found exception
Layout xml file is as below
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/myscreen"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical">

A: layout xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/myscreen"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="4dip"
android:text="Click the button and start speaking" />

<Button android:id="@+id/speakButton"
android:layout_width="fill_parent"
android:onClick="speakButtonClicked"
android:layout_height="wrap_content"
android:text="Click Me!" />
<ScrollView
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical">
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="0.41" >
</ListView>
</ScrollView>
</LinearLayout>

Code
public class MainActivity extends Activity
{

    private static final int REQUEST_CODE = 1234;
    private ListView wordsList;
    protected Button TextToSpeech;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.voice_recog);
        Button speakButton = (Button) findViewById(R.id.speakButton);

        Intent Inte = new Intent(this, FallDetection.class);
         startService(Inte);
        Intent Inte1 = new Intent(this, SmsSpeaker.class);
        startService(Inte1);
        Toast toast = Toast.makeText(this, "Fall Detection Started", Toast.LENGTH_LONG);
        toast.show();

        wordsList = (ListView) findViewById(R.id.list);
        LinearLayout myScreen = (LinearLayout) findViewById(R.id.myscreen);

        myScreen.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
    // TODO Auto-generated method stub
          Toast toast = Toast.makeText(MainActivity.this,"Touch recognised",Toast.LENGTH_LONG);
         toast.show();
         startVoiceRecognitionActivity();
    }
  });
}


text:
Q: is LSA + cosine similarity the right approach to get the similarity between 2 documents? I am working on moodle plugin to autograde student essay answer with cosine similarity. The way it works is just to compare the key answer and student answer with cosine similarity and of course with its pre-processing such as text normalization, stopword removal, stemming, and tf-idf, and it is already done. But, i found some article and watch some youtube that LSA can improve the accuracy of the similarity, and of course I'm interested. But, I found some articles and maybe SO somewhere, that LSA needs to be like 10k documents to make it more useful. But my plugin only needs 2 documents. Is it good/reasonable to add LSA with cosine similarity? Thanks in advance
I am not an machine learning developer or something, I'm just regular programmer, in fact, this is my first time touching this subject. So, any help on this matter is appreciated.


text:
Q: pointer addresses in c struct #include <stdio.h>
#include<stdlib.h>

struct try {
    int x,*x_Ptr;
    float y,*y_Ptr;
    char q,*q_Ptr;
};  //integer, float character variables and their pointers are defined in the structures.
int main (void){

    struct try den1;
    struct try den2;
    struct try den3;

    den1.x=7;
    den2.x=8;
    den1.y=-.14;
    den2.y=23.45;
    den3.q='A';

    den1.x_Ptr=&den1.x; //pointer assignments for integer.
    den2.x_Ptr=&den2.x;

    den1.y_Ptr=&den1.y; //pointer assignments for float.
    den2.y_Ptr=&den2.y;

    den3.q_Ptr=&den3.q; //pointer assignments for character.
    system("clear");

    printf("The integer in den1:%d\nThe integer in den2:%d\nThe address of integer in den1:%p\nThe address of integer in den2:%p\nThe pointer address of integer in den1:%p\nThe pointer address of integer in den2:%p\n",den1.x,den2.x,&den1.x,&den2.x,&*den1.x_Ptr,&*den2.x_Ptr);

    printf("\n");
    printf("The float in den1:%f\nThe float in den2:%f\nThe address of float in den1:%p\nThe address of float in den2:%p\nThe pointer address of float in den1:%p\nThe pointer address of float in den2:%p\n",den1.y,den2.y,&den1.y,&den2.y,&*den1.y_Ptr,&*den2.y_Ptr);

    printf("\n");
    printf("The character in den3:%c\nThe address of character in den3:%p\nThe pointer address of character in den3:%p\n",den3.q,&den3.q,&*den3.q_Ptr);

    printf("\n");

    printf("\nThe whole address of the first struct{...\n...\n...\n...\t\t\t}den1:%p\n",&den1);
    printf("\nThe whole address of the second struct{...\n...\n...\n...\t\t\t}den2:%p\n",&den2);
    printf("\nThe whole address of the second struct{...\n...\n...\n...\t\t\t}den3:%p\n",&den3);

    return 0;
}

I realized that address of one of the integer in the struct and address of struct are the same. What is the reason?

A:
I realized that address of one of the integer in the struct and address of struct are the same. What is the reason?

Because they have the same address.
The struct takes up the combined space of all of its members. The address of an object is the address of its first byte. den1.x is the first member of den1, so it starts at the same byte at den1 starts at.
A picture is worth a thousand words:
address   data
00123458  07     \ <- address of x                 \  <- address of den1
00123459  00     |                                  |
0012345a  00     | space used by x                  |
0012345b  00     /                                  | space
0012345c  58   \ <- address of x_ptr                | used
0012345d  34   |                                    | by
0012345e  12   | space used by x_ptr                | den1
0012345f  00   /                                    |
00123460  29     \ <- address of y                  |
00123461  5c     |                                  |
00123462  0f     | space used by y                  |
00123463  be     /                                  |
00123464  60   \ <- address of y_ptr                |
00123465  34   |                                    |
00123466  12   | space used by y_ptr                |
00123467  00   /                                    |
00123468  41     } address of c                     |
00123469  00   \  (c only takes 1 byte)             |
0012346a  00   | padding so that c_ptr starts       |
0012346b  00   / on a multiple of 4 bytes           |
0012346c  68     \ <- address of c_ptr              |
0012346d  34     |                                  |
0012346e  12     | space used by c_ptr              |
0012346f  00     /                                  /


text:
Q: PHP Laravel - multi-locale routing with LaravelGettext? It seems I really got myself into the rabbit hole with this one. I'm tasked to implement localization into a Laravel project by using LaravelGettext (since this seems to be only one with PO file support). The routing requirements seem quite simple, everytime a page URL is called e.g. like this:
https://page.com/user

With e.g. de as fallback/cached session locale, it is supposed to redirect to:
https://page.com/de/user

unless a valid locale prefix is already defined inside the URL manually. Every subsequent URL from there on is supposed to have the same locale prefix, unless changed.
The concept seems simple, but implementing as required has turned into hours of googling for me for how to set up the routes correctly. Approaches like
routes\web.php

    Route::prefix('{locale?}')->middleware('locale')->group(function() {
        //all routes go here
    });

App\Middleware\Locale

    ...

    public function handle($request, Closure $next) {
        $locale = $request->segment(1);

        if (!in_array($locale, config('laravel-gettext.supported-locales'))) {
            $segments = $request->segments();
            $fallback = session('locale') ?: config('laravel-gettext.fallback-locale');
            $segments = array_prepend($segments, $fallback);
            return redirect()->to(implode('/', $segments));
        }

        session(['locale' => $locale]);
        app()->setLocale($locale);
        LaravelGettext::setLocale($locale);
        return $next($request);
    }

unfortunately fail with URLs having multiple segments, since the prefix misinterprets them. Optional prefixes aren't well recommended either.
Can someone recommend me a reliable solution? I'm getting really frustrated over this.

A: This should help. It is my old way when I was using gettext. This is routes.php
$locale = Request::segment(1);

if(in_array($locale, config('app.locales'))){
    Config::set('app.locale', $locale);
    if($locale=='bg') $gettext_locale = 'bg_BG';
    if($locale=='en') $gettext_locale = 'en_US';
    if($locale=='ru') $gettext_locale = 'ru_RU';
    if($locale=='ro') $gettext_locale = 'ro_RO';
    if($locale=='sk') $gettext_locale = 'sr_RS';
    if($locale=='mk') $gettext_locale = 'mk_MK';
    LaravelGettext::setLocale($gettext_locale);
}else{ // default locale
    Config::set('app.locale', 'bg');
    LaravelGettext::setLocale('bg_BG');

    $locale = '';
}
Route::group([
    'prefix' => $locale
], function(){...}

Now I am using database like this: https://gist.github.com/escapeboy/b50f252f095916963e8130bc9dc69f56


text:
Q: Update only the partial view I'm trying to submit the partial view, fire partial view validations and load the main view back (main view will not be the same all the time).Basically, I only want to update the partial view without affecting the main view. Right now when I submit the partial view it loads the partial view action.
Partial View:
@using (Ajax.BeginForm("LeaveReply", "Contactus", new AjaxOptions {  InsertionMode = InsertionMode.Replace,    UpdateTargetId = "respond"))
{

Leave a reply

                                Message (required)
                                @Html.ValidationMessageFor(o=>o.Message)
                                @Html.TextAreaFor(o => o.Message, new { @rows="6", @cols="80", @name="message",@class="form-control" })

                               Your Name (required)
                                @Html.ValidationMessageFor(o=>o.Name)
                                @Html.TextBoxFor(o=>o.Name, new { @class="form-control" })

                                Email (required)
                                @Html.ValidationMessageFor(o=>o.Email)
                                @Html.TextBoxFor(o=>o.Email, new { @class="form-control" })

                                 Website
                                @Html.ValidationMessageFor(o=>o.WebSite)
                                @Html.TextBoxFor(o=>o.WebSite, new { @class="form-control" })

                                <input type="submit" id="submit-contact" value="Submit">

@ViewBag.Message

       }

Main View:

  @{Html.RenderPartial("_MessagePartial", new Classified.ViewModels.MessageViewModel());}

ContactUs Controller
[HttpPost]
public PartialViewResult LeaveReply(MessageViewModel model)
  {
       JsonResult result = new JsonResult();
       if (ModelState.IsValid)
        {

        }

       return PartialView("_MessagePartial", model);
   }

Model:
public class MessageViewModel
    {
        [Key]
        public int ID { get; set; }
        public string MessageType { get; set; }
        [Required]
        public string Name { get; set; }
        [EmailAddress]
        [Required]
        public string Email { get; set; }
        public string WebSite { get; set; }
        [Required]
        public string Message { get; set; }
        public DateTime? AddedDateTime { get; set; }
        public int? UserID { get; set; }
    }

*Main view is bind to a different model.


text:
Q: Does amazon-kinesis-video-streams-webrtc-sdk-js support javascript v3 or AWS Kinesis Video Client SDK v3? I tried to check with AWS on Github. Issue: https://github.com/awslabs/amazon-kinesis-video-streams-webrtc-sdk-js/issues/153 but, did not get a reply on it.
Based on their documentation it says, its supports AWS SDK v2.5. However, we are trying to use the new AWS Modularized SDK client-kinesis-video(https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-kinesis-video/index.html) and it does not seem to work with it(getting black screen on one end but, the same code works with v2). I couldn't find a javascript v3 version of the kinesis-video-streams-webrtc-sdk-js online and hence, we tried checking on Github but, there is no answer.
Would like to know whether amazon-kinesis-video-streams-webrtc-sdk-js supported with https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-kinesis-video/index.html


text:
Q: What is the formula for Combination with indistinguishable objects? Take a look at the following question,

There is a group of $10$ objects, $2$ red, $3$ blue, and $5$ green. The objects are indistinguishable. In how many ways they can be arranged on a line?
Solution:
$\binom{10}{2}\cdot\binom{8}{3}\cdot\binom{5}{5} = \frac{10!~~~8!~~~5!}{2!8!3!5!5!0!} = \frac{10!}{2!3!5!} = 2520$

What is the formula for this kind of problems so that someone can directly apply the formula to find the result?

A: The general formula for the

*

*number of arrangements of $n = k_1 + \cdots + k_r$ objects consisting of

*$r$ groups of

*$k_1, \ldots , k_r$ indistinguishable objects within each group is
$$\frac{n!}{k_1! \cdot \ldots \cdot k_r!}$$

This fraction is also called multinomial coefficient and is written as
$\binom{n}{k_1, \ldots ,k_r}$.
By your example you can quickly understand why it works:

*

*$n=10=2+3+5$ objects can be arranged in $10!$ ways

*Consider a given arrangements, then any permutation of the $k_1=2$, $k_2=3$, and $k_3 = 5$ indistinguishable objects reproduces the same arrangement

So, a given permutation appears $k_1!\cdot k_2!\cdot k_3! = 2!\cdot 3! \cdot 5!$ times within the $n!= 10!$ arrangements of all $10$ objects. Hence, in your case it follows that the number of (distinguishable) arrangements is
$$\frac{10!}{2!\cdot 3! \cdot 5!}$$

A: That is usually known as multinomial coefficients.

A: It is Permutation of multisets. You can think of making different (unique) $10$ letter words from:
$$RRBBBGGGGG.$$
Note that there $10!$ permutations of all words in total, however not all unique, because switching places of two $R$s, three $B$s or five $G$s does not change the word. Therefore you must divide by $2!$, $3!$ and $5!$:
$$\frac{10!}{2!\cdot 3!\cdot 5!}.$$


text:
Q: return in functions with std::async I have a function that should always return A[0][1]. But I use std::async and gcc says:

test_fibonacci_method/1/main.cpp:147:1: warning: control reaches end of non-void function [-Wreturn-type]

Integer Fib_iterative_n_Matrix(const unsigned& n) {
    if (n < 2) return n; // Fib(0):=0 and Fib(1):=1
    std::array<std::array<Integer,2>,2> A = {1,0,0,1}, FIB = {1,1,1,0};

    auto a = std::async(std::launch::async, [&]() { Matrixpower_A_time_B_pow_x(A, FIB, n); return true; });

    if (a.get()) { // blocks
        return A[0][1]; // fib(n)
    }
}

How can I change the last IF with A[0][1]?

A: OK, I understand now that the if is unnecessary. And a.get() is also to much, because the result of the lambda is not used a.wait() is better.
Integer Fib_iterative_n_Matrix(const unsigned& n) {
    if (n < 2) return n; // Fib(0):=0 and Fib(1):=1
    std::array<std::array<Integer,2>,2> A = {1,0,0,1}, FIB = {1,1,1,0};

    auto a = std::async(std::launch::async, [&]() { Matrixpower_A_time_B_pow_x(A, FIB, n); return true; });

    a.wait(); // blocks
    return A[0][1]; // fib(n)
}


text:
Q: Jquery Determine if there are changes in the value of select box How can i determine the value is changed in the select box without clicking the select box itself.
My code is as follows:
JQUERY
            $("select").each(function() {
                $(this).change(function() {
                    if ($(this).val() === "-Select-"){
                        this.parent().addClass("highlightSelect");
                        this.parent().sibling().show();
                    }   else{
                        this.parent().removeClass("highlightSelect");
                        this.parent().sibling().hide();
                    }
                });
            });

HTML

<select id="add_savedAddressId" class="storedPaymentInput_size4 required savedAddress checkDropdown valid" onchange="changeSavedAddressType();generateSavedAddressAdd();" name="summaryData.usedAddress">
<option value="-Select-">-Select-</option>
<option value="O">Enter New Address</option>
<option value="3041">Home - 116 Parrot...</option>
<option value="22268">Other - rwara, aw...</option>
<option value="21372">Other - 1040..</option>
</select>

 Select item

Note: I have other buttons which affects the change of the value of the above select box

A: First - your code in question will not work.
It must be like this:
                $("select").change(function() {
                    if ($(this).val() === "-Select-"){
                        $(this).parent().addClass("highlightSelect");
                        $(this).parent().siblings().show();
                    }   else{
                        $(this).parent().removeClass("highlightSelect");
                        $(this).parent().siblings().hide();
                    }
                });

parent is jquery object function and not dom object function and this is a dom object which could be turned to jq object  like this: $(this). Also, thers is not sibling method in jquery, but there is siblings. Or, if you want to take next/previous sibling you can use .next()/.prev() instead of siblings which will return all siblings of an element
I removed each, but actually that is not required.  You may use it, but almost any jquery method will do an operation with set of methods, so $("select") may find few selects in page and $("select").change(...) will bind onchanged handler to all selects found by $("select").
And answerign your question: as I understand you want to call change handler after selected value is changed porgrammatically. You can do that like this: $("select").change(), but this way you will call change event on all selects, so you can do it like this: $("#add_savedAddressId").change(). In second case you will call a change even handler only for select with id add_savedAddressId


text:
Q: socket.on not working in client side I'm studying nodejs + vuejs + socket.io
Testing sending message and reciving on server side and client side.
On server side is working, I'm recieving the console(message: text)
But, the console.log on the client side is not working. Nothing appears.
index.html:

<%= title %>

{{subtitle}}

Welcome to <%= title %>

{{ subtitle }}

       <button v-on:click="sendMessage">Send Message</button>

app.js:
var socket = io();

var vm = new Vue({
 el: '#todo',
  data: {
   subtitle: 'Hello Vue.js!',
   text: 'Hello Friends',
   menssages: []
 },
 methods: {
  sendMessage: function () {
   socket.emit('chat message', this.text);
  }
}
});

socket.on('chat message', function(msg){
 console.log('Client side message: ' + msg)
});

nodejs server:
io.on( "connection", function( socket ) {
console.log( "A user connected" );

socket.on('chat message', function(msg){
  console.log('messagem: ' + msg);
});
});

I'm recieving the message on terminal server. But not recieving the console.log('Client side message: ' + msg) on the browser.

A: This is mainly a socket.io question. You are emitting an event from the client:
socket.emit('chat message', this.text);

and then listening on that event on the server:
socket.on('chat message', function(msg){
  console.log('messagem: ' + msg);
});

which makes sense and, as you say yourself, works fine: the message gets logged on the server.
However, listening on the chat message event on the client:
socket.on('chat message', function(msg){
 console.log('Client side message: ' + msg)
});

does not work until the server has emitted this event.
In other words, try executing:
socket.emit('chat message', 'Hello World.');

on the server to see Hello World logged on the client.


text:
Q: How much redundancy is needed to comfortably ensure an outcome of a probabilistic event? I'm playing a game where meteor showers periodically strike the surface of the planet. For protection, you can install defense systems that can fire one projectile per meteor shower which have an 80% chance to hit and destroy a meteor. In case of a miss, there is ample time for any redundant systems to shoot at any missed meteors.
However, the number of meteors in each shower is random. There is a 50% chance of one, 25% chance of two, 12.5% chance of 3, 6.25% chance of 4, and so on. What equation represents the probability that no meteors strike the planet in a meteor shower given $n$ defense systems?

A: The number of succesful defence systems can be seen as a $\operatorname{Binomial}(n,0.8)$ variable, although some of the defence systems might be shooting at thin air if there are no meteors left. The distribution of meteors follows a $\operatorname{Geometric}(\frac12)$ distribution, so the probability of having no meteor impacts would be
$$\mathbb{P}(X \geq M) , \quad  X \sim \operatorname{Binomial}(n,0.8)  , \quad M \sim \operatorname{Geometric}(\frac12),$$
where $X$ and $M$ are assumed to be independent. Note that we can calculate this using the law of total probability
\begin{align*}
\mathbb{P}(X\geq M) &= 1-\mathbb{P}(M>X) \\
                    &= 1- \sum_{k=0}^n \mathbb{P}(M>k\: | \: X=k)\mathbb{P}(X=k) \\
                    &= 1- \sum_{k=0}^n \mathbb{P}(M>k)\mathbb{P}(X=k) &\text{(by independence)} \\
                    &=1 - \sum_{k=0}^n (\frac{1}{2})^{k} \cdot {n \choose k}
(0.8)^k(0.2)^{n-k} &\text{(inserting the CDF and PMF)} \\
                    &= 1 - \sum_{k=0}^n  {n \choose k}
(0.4)^k(0.2)^{n-k} \\
                    &= 1 - (0.4 + 0.2)^n &\text{(using the binomial formula)}
\end{align*}
We see thus, that the probability of not getting hit by a meteor would be $1-(0.6)^n$. Note in particular, that the probability goes to $1$ as the number $n$ of defence systems goes to infinity.

A: I'll make a few additional assumptions to fully specify the scenario:

*

*The meteorites come in some "order" (one after the other)

*The defense systems employ a "greedy" approach: they always try to shoot down the meteorite that's closest to the surface. If they succeed, they move on to the second closest, and so on.

*To shoot down a single meteorite, the defense systems take turns in shooting until one succeeds or the projectiles run out (meaning that the meteorite strikes the surface).

Let $p$ be the probability of one trial: a single projectile taking down a single meteorite.
Then $1 - p$ is the probability of missing.
We want to compute the probability $\Pr(S)$ of a meteorite striking the surface given that there are $n$ defense systems ($n$ projectiles).
This could happen in a few different ways: let $A_k$ denote the event in which the meteorite shower has $k$ meteorites and one hits the surface, and let $B_{k,i}$ where $1 \le i \le k$ denote the event in which the $i$-th meteorite strikes the surface.
Then $S = \bigcup_{k=1}^\infty A_k$ and $A_k = \bigcup_{i = 1}^k B_{k,i}$, moreover these are disjoint unions.
For the first meteorite to hit the surface, all $n$ systems have to fail:
$$\Pr(B_{k, 1}) = (p - 1)^n $$
If it's the second one that strikes the surface, the first one must have been shot down after $j$ trials, and the rest must have failed on the second meteorite:
$$\Pr(B_{k, 2}) = \sum_{j = 1}^{n} (p-1)^{j-1}p(p-1)^{n - j} = \sum_{j = 1}^{n} (p-1)^{n-1}p = np(p -1)^{n-1} $$
We can generalise this.
If the $i$-th meteorite hits the surface, the first $i - 1$ must have been shot down.
There are ${n \choose i - 1}$ ways to choose the $i - 1$ projectiles in the sequence that were successful.
All the other projectiles missed.
Therefore:
$$\Pr(B_{k, i}) = {n \choose i - 1} p^{i - 1}(1 - p)^{n - (i - 1)} $$
Now we just have to sum up all these disjoint cases:
$$\Pr(A_k) = \sum_{i = 1}^k \Pr(B_{k, i}) = \sum_{i = 1}^k {n \choose i - 1} p^{i - 1}(1 - p)^{n - (i - 1)} = \sum_{i = 0}^{k-1} {n \choose i} p^{i}(1 - p)^{n - i}$$
As a sanity check, we can see that if $k > n$, i.e. if we have at least one more meteorite than there are projectiles ($k \ge n + 1$), then $\Pr(A_k)$ becomes $1$ (using the convention that ${n \choose i} =0$ if $i > n$):
$$\sum_{i = 0}^{k-1} {n \choose i} p^{i}(1 - p)^{n - i} = \sum_{i = 0}^{n} {n \choose i} p^{i}(1 - p)^{n - i} = (p + (1 - p))^n = 1^n = 1$$
I'm not sure how similar this is to the other answers posted here.


text:
Q: Google AdWords Conversion Tracking (Page Refresh Effect) I copied and pasted the Google AdWords conversion tracking code generated from Google AdWords onto my order confirmation page:

For the conversion count (1-per-click) what happens when the user refreshes the page? Does the count increase by 1 again?
I understand that for the conversion count (many-per-click) when the user refreshes the page. The count increases by 1 again.
Thanks!

A: 1-per-click conversions will only count 1 conversion per user no matter how many times they refresh the page.
You can read the official documentation here:
http://support.google.com/adwords/bin/answer.py?hl=en&answer=6365
"This type is useful for measuring conversions that count once per customer such as leads or sign-ups."


text:
Q: obtain dynamically executable path depending on script variable avoiding many ifs I want to run determined executable depending on a variable of my script cur_num
I have this code, where the paths are "random", meaning they have nothing to do with the secuential cur_num:
run() {
    if [ $cur_num = "0" ]
        then ~/pathDirName0/execFile0
    elif [ $cur_num = "1" ]
        then ~/pathDirName1/execFile1
    elif [ $cur_num = "2" ]
        then ~/pathDirName2/execFile2
    elif [ $cur_num = "3" ]
        then ~/pathDirName3/execFile3
    elif [ $cur_num = "4" ]
        then ~/pathDirName4/execFile4
    fi
}

In case there are lots more of cases, that resulys in a very long if - elif statement.
As there are no enums in bash to build the cur_num- path relation, is there a cleaner way to obtain the desired path dynamically instead of with lots of ifs?

A: Try case
case $cur_num in
      0) ~/pathDirName0/execFile0;;
      1) ~/pathDirName1/execFile1;;
      2) ~/pathDirName2/execFile2;;
      ...
esac

A: set allows you to create arrays in a portable manner, so you can use that to create an ordered array:
set -- ~/pathDirName0/execFile0 ~/pathDirName1/execFile1 ~/pathDirName2/execFile2 ~/pathDirName3/execFile3 ~/pathDirName4/execFile4
Then to access these items via an index you do $x where x is the index of the item.
Now your code would look something like this:
run() {
    original="$@"

    : $((cur_num+=1)) # Positional param indexing starts from 1

    set -- ~/pathDirName0/execFile0 ~/pathDirName1/execFile1 \
           ~/pathDirName2/execFile2 ~/pathDirName3/execFile3 \
           ~/pathDirName4/execFile4

    eval "$"$cur_num"" # cur_num = 1, accesses $1 == execFile0

    set -- $original # Restore original args
}

A method that is both less and more hacky that would work for indexes above 9 and not mess with the original positional parameters nor use eval
run() {
    count=0

    for item in "$@"; do
        [ "$count" = "$cur_num" ] && {
            "$item"
            return
        }

        : "$((count+=1))"
    done

    echo "No item found at index '$cur_num'"
}

cur_num="$1" # Assuming first arg of script.

run ~/pathDirName0/execFile0 ~/pathDirName1/execFile1 \
    ~/pathDirName2/execFile2 ~/pathDirName3/execFile3 \
    ~/pathDirName4/execFile4


text:
Q: How to send the notification to Bot using azure fucntion? I have built a bot with SDK v3 C# of Bot framework and I have also implemented the proactive message the conversation id will store in the azure table and all related information. when ever the user initiate the conversation the bot will identify the user. I want to send the notification to bot service using time trigger function everyday. But i am not able to find the bot framework in output bindings of azure function app.

How can i do it without bot framework as output bindings.

=============================Code Test======================================
I have tested the code and it is giving me the same error, kindly have a look.

==========================Integration=======================================
Here is my integration. if i remove the Http binding as output ERROR will remain the same

===============================Json file code================================
Here is my function json file code.

A: I had a scenario like this: Need a teams conversation bot to send proactive message to a group chat at a specific time everyday.
And my method is : Set a time trigger in function and when it triggered, my function will call an API which is created by myself and this API will execute the sending proactive message method.
Here's my function code, and wish it would help you:
#r "Newtonsoft.Json"
using System.Net;
using System.IO;
using System.IO.Compression;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static void Run(TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxxxxx.azurewebsites.net/api/sendProactiveMesg");
request.Method = "GET";

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();

}

============UPDATE===========
According to your error message, it seems that you have miss configuring in some place, but I don't know why it happened. I'll share my experience in creating time trigger. After saving the code, it will be triggered once a minute. If this doesn't help, could you pls describe your configuration? Because I never met an error on time trigger on 'none value'.

=========================UPDATE 2 =============================
My code:

public async Task sendtoPersonal()
        {
            string teamInternalId = "19:3fxxx7d8c@unq.gbl.spaces";
            string serviceUrl = "https://smba.trafficmanager.net/amer/";
            string mentionUserPrincipalName = "xxx";
            string tenantId = "72fxxxx47";
            string botClientID = "e8caxxxx8c";
            string botClientSecret = "5zxxxxJA";
            AppCredentials.TrustServiceUrl(serviceUrl);
            ConnectorClient connectorClient = new ConnectorClient(new Uri(serviceUrl), new MicrosoftAppCredentials(botClientID, botClientSecret), true);
            TeamsChannelAccount user2 = (await connectorClient.Conversations.GetConversationMembersAsync(teamInternalId)).Select((ChannelAccount channelAccount) => JObject.FromObject(channelAccount).ToObject<TeamsChannelAccount>()).First((TeamsChannelAccount user) => user.UserPrincipalName == mentionUserPrincipalName);
            //Activity personalMessageActivity = MessageFactory.Text("Personal message from the Bot!");
            IMessageActivity personalMessageActivity = await showTeamStatus();
            ConversationParameters conversationParameters = new ConversationParameters
            {
                Members = new List<ChannelAccount>
            {
                user2
            },
                ChannelData = new TeamsChannelData
                {
                    Tenant = new TenantInfo
                    {
                        Id = tenantId
                    }
                }
            };
            ConversationResourceResponse response = await connectorClient.Conversations.CreateConversationAsync(conversationParameters);
            await connectorClient.Conversations.SendToConversationAsync(response.Id, (Activity)personalMessageActivity);
        }


text:
Q: Reskit parse multiple type of data for the same field I just want to ask if there is a way to parse the following field "mods" in Reskit:
post_count: false,
sitename: "Mercury",
mods: false,
admin_email: "maystro@test.com",

here mods has a boolean value and in the next example it has an object as a value:
post_count: false,
sitename: "Mercury",
mods: {
0: false,
author_blocks: {
enabled: {
placebo: "placebo"
},
disabled: {
2: "jbckmn",
placebo: "placebo"
}
},
backups: null,
smof_init: "Wed, 14 May 2014 18:53:58 +0000",
custom_logo: "",
custom_logo_height: "1",
custom_login_logo: "",
custom_login_logo_height: "1",
custom_favicon: ""
}

In the same JSON response we're receiving this type of data, sometimes mods has a boolean value and sometimes it has an object. Does anyone knows if there is a way to do a dynamic mapping using Restkit to handle such cases?
Thanks in advance

A: Indeed yes. You want to use an RKDynamicMapping, and return the actual mapping you want to use from that; something like:
RKDynamicMapping *dynamicMapping = [RKDynamicMapping new];

[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
    if ([representation valueForKey:@"MyKey"] isKindOfClass:[NSNumber class]])
    {
        return aMappingWhenTheFieldIsANumber;
    }
    else
    {
        return aMappingWhenTheFieldIsNotANumber;
    }
}];

In this manner, you get to pick the mapping to use when you have the data in hand. Just check the data for the field type, and return a normal RKObjectMapping appropriate for the field types.


text:
Q: Best practice for switching between UINavigationController stacks in Storyboard In our storyboard we have multiple UINavigationController stacks. For example, the LoginViewController stack is completely separate from the SWRevealViewController stack.
What's the best practice for switching between them? When I press the logout button (the logout button is on the SWRevealController stack) and then try to present the LoginViewController stack, I get an error like this:
Warning: Attempt to present LoginViewController on SWRevealViewController whose view is not in the window hierarchy!

Even though I'm specifically setting self.window.rootViewController to the Login View Controller's UINavigationController in App Delegate like this:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Spitfire" bundle:nil];
UINavigationController *nav = [storyboard instantiateViewControllerWithIdentifier:@"LoginNavigationController"];
LoginViewController *loginVC = [storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];

self.window.rootViewController = nav;
[nav presentViewController:loginVC animated:NO completion:nil];

Is there a way I can "dismiss" the current UINavigationController stack and use a new one? Or maybe I shouldn't be calling this code in my app delegate?

A: I had not played with SWRevealViewController before your question, so my previous response was a little more generic. I've created a sample app here that does its best to throw around as many navigation stacks as possible; I'm sure I've covered your use case.
A few things I'll draw your attention to:

*

*The "main flow" from my previous answer is right smack in the middle of the storyboard; that should help orient you.

*SWRevealViewController.m can be used in conjunction with Storyboards and has a very clever hack to do so, but the documentation for it is buried in the implementation. It took me a while to figure out what the hell was happening, but my example app illustrates the usage (two segues, one for "front" and the other for "back", could have a third for "right").

*The app's main flow gets completely swapped out for the alternate flow. This is by design of SWRevealViewController. You are essentially switching to an entirely new app.

*All sub-flows that are presented modally disrupt the flow.

*The author of SWRevealViewController has not provided UIStoryboardSegue subclasses for the replacement of front, rear, and right view controllers. This would be trivial to implement, but I've elected to do the swapping manually in FHKSettingsViewController's implementation.

*I repeated code and made dinky classes to make sure what I was doing was obvious.

A: You should wait to call presentViewController until viewDidAppear on rootViewController.
See here for more discussion: whose view is not in the window hierarchy

A: Edit:
call presentViewController from your UINavigationcontroller's rootviewController in viewDidAppear: method
-(void)viewDidAppear:(BOOL)animated {

   LoginViewController *loginVC = [storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
   [self presentViewController:loginVC animated:NO completion:nil];
   [super viewDidAppear:YES];
}


text:
Q: Setting Properties In Once Class, Accessing From Another My question is basically this:
If I set dynamic data from one class, can I access that same data from another
class? Below is the rough pseudocode of what I am trying to do:
Public Class Person
{
  public string ID { get; set; }
  public string Name { get; set; }

}

And, I do the below:
Public Class SomeClass
{

   private void SomeMethod()
   {

        List<Person> p = new List<Person>();

         loop {
           p.Add(id[i], name[i]);
           Timer t = new Timer();
          t.Interval = 1000;
         }
}

Can I access the values set in SomeClass
from SomeOtherClass such that:
Public SomeOtherClass
{

  private List<Person> SomeOtherMethod(string id)
  {
      // HERE, THE RESPONSE VALUES MAY CHANGE BASED ON
      // WHERE IN THE LOOP SomeClass.SomeMethod HAS SET
      // THE VALUES IN Person.

      var query = from p in Person
                  where p.ID == id
                  select p;

      return query.ToList();

  }

}

Thanks for your thoughts...

A: You can access the members (ID, Name) for those properties, since you declared them as public.
When you say "Person", you're referring to a Type - the Person type.
In order to access a member of a specific Person, you need to use an instance of Person.
Person thePersonInstance = new Person(5, "Joe");
thePersonInstance.ID = 3; // This is fine, since it's public

However, in your example, you would need to provide a specific collection of "Person" instances to your method in SomeOtherClass.  Something like:
Public SomeOtherClass
{

    // You need to provide some collection of Person instances!
    public List<Person> SomeOtherMethod(string id, IEnumerable<Person> people)
    {
        var query = from p in people
              where p.ID == id
              select p;

        return query.ToList();
    }
}

You could then use this somewhere else, like:
void SomeMethod()
{
      List<Person> people = new List<Person>();
      people.Add(new Person(1, "Name1");
      people.Add(new Person(2, "Name2");

      SomeOtherClass other = new SomeOtherClass();
      List<Person> filteredPeople = other.SomeOtherMethod(1);
 }


text:
Q: Regex: filter html elements from a large string c# I am not good at regex and was trying to read some stuff but it is getting me nowhere.
I have a large html string something like with string like:
<input data-val="true" data-val-required="The SearchType field is required." id="SearchType" name="UserSearchType" type="hidden" value="something">

I am trying to write a regex using which i can find all the  strings
and then replace the type to label from any other type.
even if i can get a colletion of strings from regex then that will be great.
For e.g
 string testHtml =
    "abc <input data-val='true' data-val-required='The SearchType field is required.'  id='UserSearchType' name='UserSearchType' type='hidden' value='Scos'> abc <input data-val='true' data-val-required='The UserSearchType field is required.' id='UserSearchType' name='SearchType' type='hidden' value='sco'>";

I am trying to
find <input ....> and create a collection or
find <input ..type='text'..> and change it to <input ..type='label'..>
Please let me know if the question is vague and need any details

A: you can do something like this. you will get a lot of pushback for parsing xml with regex but this should work for your example.
Regex r = new Regex("(<[^>]*type=['\"])([a-zA-Z])+(['\"][^>]*>)");
string text = "abc <input data-val='true' data-val-required='The SearchType field is required.'  id='UserSearchType' name='UserSearchType' type='hidden' value='Scos'> abc <input data-val='true' data-val-required='The UserSearchType field is required.' id='UserSearchType' name='SearchType' type='hidden' value='sco'>";
string replaced = r.Replace(text,"$1label$3");

A: Give this a try (and see the regular expression in action here):
<((?:[^=]+=(?:"(?:[^\\][^"])+"|'(?:[^\\][^'])+'|[^'"\s]+?)\s+)*)type=(?:"(?:[^\\][^"])+?"|'(?:[^\\][^'])+?'|[^'"\s]+?)([^//>]*?/?)>

In C#, you would use:
string testHtml = "abc <input data-val='true' data-val-required='The SearchType field is required.'  id='UserSearchType' name='UserSearchType' type='hidden' value='Scos'> abc <input data-val='true' data-val-required='The UserSearchType field is required.' id='UserSearchType' name='SearchType' type='hidden' value='sco'>";
string pattern = "<((?:[^=]+=(?:\"(?:[^\\\\][^\"])+\"|'(?:[^\\\\][^'])+'|[^'\"\\\s]+?)\\\s+)*)type=(?:\"(?:[^\\\\][^\"])+?\"|'(?:[^\\\\][^'])+?'|[^'\"\\\s]+?)([^/>]*?/?)>";
Regex rgx = new Regex(pattern);
string newHtml = rgx.Replace(testHtml, "<$1type='label'$2>");

This is a pretty hefty regular expression. It accounts for however many other attributes the HTML tags might have, whether their attribute values are enclosed in double quotes ("), single quotes ('), or no quotes, and so on. Let me know if it helps!


text:
Q: how to unit test method using "Spring Data JPA" Specifications I was playing with org.springframework.data.jpa.domain.Specifications, it's just a basic search :
 public Optional<List<Article>> rechercheArticle(String code, String libelle) {
    List<Article> result = null;

    if(StringUtils.isNotEmpty(code) && StringUtils.isNotEmpty(libelle)){
        result = articleRepository.findAll(Specifications.where(ArticleSpecifications.egaliteCode(code)).and(ArticleSpecifications.egaliteLibelle(libelle)));
    }else{
        if(StringUtils.isNotEmpty(code)){
            result= articleRepository.findAll(Specifications.where(ArticleSpecifications.egaliteCode(code)));
        }else{
            result = articleRepository.findAll(Specifications.where(ArticleSpecifications.egaliteLibelle(libelle)));
        }
    }

    if(result.isEmpty()){
        return Optional.empty();
    }else{
        return Optional.of(result);
    }
}

And that's actually working fine but I'd like to write  unit tests for this method and I can't figure out how to check specifications passed to my articleRepository.findAll()
At the moment my unit test looks like :
@Test
public void rechercheArticle_okTousCriteres() throws FacturationServiceException {
    String code = "code";
    String libelle = "libelle";
    List<Article> articles = new ArrayList<>();
    Article a1 = new Article();
    articles.add(a1);
    Mockito.when(articleRepository.findAll(Mockito.any(Specifications.class))).thenReturn(articles);

    Optional<List<Article>> result = articleManager.rechercheArticle(code, libelle);

    Assert.assertTrue(result.isPresent());
    //ArgumentCaptor<Specifications> argument = ArgumentCaptor.forClass(Specifications.class);
    Mockito.verify(articleRepository).findAll(Specifications.where(ArticleSpecifications.egaliteCode(code)).and(ArticleSpecifications.egaliteLibelle(libelle)));
    //argument.getValue().toPredicate(root, query, builder);

}

Any idea?

A: I was having almost the same problems as you had, and I changed my class that contains Specifications to be an object instead of just one class with static methods. This way I can easily mock it, use dependency injection to pass it, and test which methods were called (without using PowerMockito to mock static methods).
If you wanna do like I did, I recommend you to test the correctness of specifications with integration tests, and for the rest, just if the right method was called.
For example:
public class CdrSpecs {

public Specification<Cdr> calledBetween(LocalDateTime start, LocalDateTime end) {
    return (root, query, cb) -> cb.between(root.get(Cdr_.callDate), start, end);
}
}

Then you have an integration test for this method, which will test whether the method is right or not:
@RunWith(SpringRunner.class)
@DataJpaTest
@Sql("/cdr-test-data.sql")
public class CdrIntegrationTest {

@Autowired
private CdrRepository cdrRepository;

private CdrSpecs specs = new CdrSpecs();

@Test
public void findByPeriod() throws Exception {
    LocalDateTime today = LocalDateTime.now();
    LocalDateTime firstDayOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
    LocalDateTime lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
    List<Cdr> cdrList = cdrRepository.findAll(specs.calledBetween(firstDayOfMonth, lastDayOfMonth));
    assertThat(cdrList).isNotEmpty().hasSize(2);
}

And now when you wanna unit test other components, you can test like this, for example:
@RunWith(JUnit4.class)
public class CdrSearchServiceTest {

@Mock
private CdrSpecs specs;
@Mock
private CdrRepository repo;

private CdrSearchService searchService;

@Before
public void setUp() throws Exception {
    initMocks(this);
    searchService = new CdrSearchService(repo, specs);
}

@Test
public void testSearch() throws Exception {

    // some code here that interact with searchService

    verify(specs).calledBetween(any(LocalDateTime.class), any(LocalDateTime.class));
   // and you can verify any other method of specs that should have been called
}

And of course, inside the Service you can still use the where and and static methods of Specifications class.
I hope this can help you.

A: If you are writing Unit Tests then you should probably mock the call to findAll() method of articleRepository Class using a mocking framework like Mockito or PowerMock.
There is a method verify() using which you can check if the mock is invoked for the particular parameters.
For Example, if you are mocking the findAll() method of articleRepository Class and want to know if this method is called with particular arguments then you can do something like:
Mokito.verify(mymock, Mockito.times(1)).findAll(/* Provide Arguments */);

This will fail the test if mock has not been called for the arguments that you provided.

A: Your problem is that you are doing too many things within that one method. You should have three different methods that work on articleRepository.
Then you can use mocking as the others suggest:

*

*setup your mocks so that you know which call on articleRepository should be made

*verify that exactly the expected calls are happening

Please note: these three methods should be internal; the main point there is: you can't test this method with ONE call from the outside; as it is doing more than one thing, depending on the input that you provide. Thus you need to create at least one test method for each of the potential paths in your code. And that becomes easier (from a conceptual point of view) when you separate your code into different methods.


text:
Q: Iterate through folders (with spaces in names) and change file name inside to folder name Im trying to solve the issue to automate file rename process from:
/subfolder 1/0123.txt
/subfolder 2/13134.txt

to:
/subfolder 1/subfolder 1.txt
/subfolder 2/subfolder 2.txt

I tried things like:
OIFS="$IFS"
IFS=$'\n'
for dir in */; do mv "${dir}"*.txt "${dir}"`echo "${dir%\}"`.txt; done
IFS="$OIFS"

or:
for dir in */; do   mv "${dir}"/*.txt "${dir}"/"${dir}".txt; done

but I end up with problem of either spaces or trailing "/" in folder name

A: I think you get a more tweakable code with find (this one is GNU version):
find . -maxdepth 2 -mindepth 2 -type f -name "*.txt" -exec sh -c '
    file=$1
    fulldir=$(dirname "$file")
    dir=${fulldir##*/}
    mv "$file" "$fulldir/$dir.txt"
' findshell {} \;

This finds all .txt files in the directories one level below the current one, as specified by -maxdepth and -mindepth. So it will find ./subfolder 1/0123.txt but not ./x.txt nor ./subfolder 1/subsubfolder 1/0123.txt.


text:
Q: Memory issues with as.dist function in R/rpy2 I'm trying to perform a hierarchical clustering using a custom distance measure. I perform all the calculations in Python and then pass the data structures to R to do the clustering
import rpy2.robjects as robjects
r=robjects.r
from rpy2.robjects.packages import importr
stats = importr('stats')

m = r.matrix(robjects.FloatVector(list_of_data), ncol=size, byrow=True)
dist_mat=stats.as_dist(m)
hc=stats.hclust(new_dist_mat)

So my distance measures are held in a Python list, converted to an R matrix, which is then converted into a dist object required for the clustering. This works to an extent. However, when the matrix becomes too big and I get this error:
python(18944,0xb0081000) malloc: *** mmap(size=168898560) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Error: cannot allocate vector of size 161.1 Mb

This occurs at the point where I convert to a dist object (as.dist). I haven't tested at what size it falls apart, but it works with 3000x3000 matrix, but fails with a 6500x6500 matrix, so somewhere in-between.
I'm using the del function in Python to try remove any unnecessary objects from memory, but from what I've read this doesn't guarantee that the memory will become immediately available for use.
So, ultimately, is there a more memory efficient way to get a dist object? Or is there perhaps an alternative method I could use? I've found some other methods in R's cluster library, which do not use a dist object, but these methods use built-in distance metrics.
Thanks in advance!

A: Calling Python's del() does not guarantee that the memory is becoming immediately available for use. Calling the garbage collector explicitly helps. The answer to an other question here (Clearing memory used by rpy2) points to the relevant section in the rpy2 documentation.
Regarding clustering algorithms hierachical clustering with hclust() does require a "distance" matrix (of size n * (n + 1) / 2 ; R saves a bit of memory since the matrix is symetrical). There exists other clustering algorithms, or if keen on hierachical clustering tricks to minimize the size of the starting matrix by creating initial blocks, but that's outside the scope of a programming-related question.


text:
Q: Filter on specific value dataframe pandas/ python I want to create a function that filter on a specific value in a column of an dataframe(
My dataframe has the follow columns and value:

Zoekterm
High_bias

Man
1

Man
1

Vrouw
1

kind
0

I wrote a function that filter on a specific value see below
Def most_likey_bias():
bias = data['high_bias'] == 1
if bias.any():
  print(data.loc[bias,['High_bias','Zoekterm']
print(most_likey_bias())

The outcome of the table is:

Zoekterm
High_bias

vrouw
1

kind
1

This table gives back which "Zoekterm" has a value of 1
But because the " Zoekterm" has duplicates of the same name i want a table that gives me a count of each zoekterm
So the table that i want is:
This means a table where it counts for each "Zoekterm" how much "High bias" it has based on an specific value (1)

Zoekterm
High_bias

Man
4

Vrouw
2

kind
5

I tried with groupby or with count, but i don't get it. Could someone give me some tips.

A: Use GroupBy.size with filtered rows and convert Series to DataFrame by Series.reset_index:
def most_likey_bias():
    bias = data['high_bias'] == 1
    if bias.any():
        return data[bias].groupby('Zoekterm').size().reset_index(name='High_bias')

Similar idea is aggregate sum:
def most_likey_bias():
    bias = data['High_bias'] == 1
    if bias.any():
        return data[bias].groupby('Zoekterm')['High_bias'].sum().reset_index(name='High_bias')

print (most_likey_bias())
  Zoekterm  High_bias
0      Man          2
1    Vrouw          1


text:
Q: R - write.foreign to SPSS => console hangs? When I run below write.foreign command in R, the console shows a plus sign, not the command prompt, and stays that way until I hit escape.
x<-(1:5)
y<-c("y","y","y","n","n")
testdat<-data.frame(x,y)
names(testdat)<-c("var1","var2")
setwd("C:\\temp")
write.foreign(testdat, "mydata.sav", "mydata.sps",   package="SPSS)

I'm new to R so maybe I am missing something obvious?
I'm running R Studio on a 64 bit windows 7 machine
R version 3.1.1
Thanks

A: Two issues

*

*missing closing " after "SPSS (thanks nrussel-.

*foreign needs an explicit path to the to be saved files
This works:
write.foreign(testdat, "C:\\temp\\mydata.dat", "C:\\temp\\mydata.sps",   package="SPSS")

You need the path for the mydata.sps file to work.


text:
Q: group by consecutive values in r I've got a dataset coming from a support ticketing system that logs each click made by an agent in classifying and responding to customer requests. The system assigns a new hist_id to each click, but an agent will click several fields, triggering several rows in the table, in what they consider a single "interaction".
My goal is to calculate a handle time for each of these interaction by doing a diff on the first and last modify_time values in each group.
I'm stuck currently because an agent will have multiple interactions with a case throughout the day.
Here's a sample dataframe:
hist_id <- c(1234, 2345, 3456, 4567, 5678, 6789, 7890)
case_id <- c(1, 1, 1, 1, 1, 1, 1)
agent_name <- c("John", "John", "John", "Paul", "Paul", "John", "John")
modify_time <- as.POSIXct(c(1510095120, 1510095180, 1510095240, 1510098600, 1510098720, 1510135200, 1510135320), origin = "1970-01-01")
df <- data.frame(hist_id, case_id, agent_name, modify_time)

Using group by on the case_id and agent_name groups all rows that match the criteria, as expected:
df %>% group_by(case_id, agent_name) %>% mutate(first = first(modify_time), last = last(modify_time), diff = min(difftime(last, first)))

Which gives me this:
    # A tibble: 7 x 7
# Groups:   case_id, agent_name [2]
  hist_id case_id agent_name         modify_time               first                last       diff
    <dbl>   <dbl>     <fctr>              <dttm>              <dttm>              <dttm>     <time>
1    1234       1       John 2017-11-07 16:52:00 2017-11-07 16:52:00 2017-11-08 04:02:00 40200 secs
2    2345       1       John 2017-11-07 16:53:00 2017-11-07 16:52:00 2017-11-08 04:02:00 40200 secs
3    3456       1       John 2017-11-07 16:54:00 2017-11-07 16:52:00 2017-11-08 04:02:00 40200 secs
4    4567       1       Paul 2017-11-07 17:50:00 2017-11-07 17:50:00 2017-11-07 17:52:00   120 secs
5    5678       1       Paul 2017-11-07 17:52:00 2017-11-07 17:50:00 2017-11-07 17:52:00   120 secs
6    6789       1       John 2017-11-08 04:00:00 2017-11-07 16:52:00 2017-11-08 04:02:00 40200 secs
7    7890       1       John 2017-11-08 04:02:00 2017-11-07 16:52:00 2017-11-08 04:02:00 40200 secs

Where John's true first and last modify_times are returned. However, I need to group the consecutive matches of case_id and agent_name, so that Paul's interaction is considered. So three interactions are recorded here: one from John, one from Paul, and a second by John.
Desired output would be something like this:
    # A tibble: 7 x 7
# Groups:   case_id, agent_name [2]
  hist_id case_id agent_name         modify_time               first                last       diff
    <dbl>   <dbl>     <fctr>              <dttm>              <dttm>              <dttm>     <time>
1    1234       1       John 2017-11-07 16:52:00 2017-11-07 16:52:00 2017-11-07 16:54:00 120 secs
2    2345       1       John 2017-11-07 16:53:00 2017-11-07 16:52:00 2017-11-07 16:54:00 120 secs
3    3456       1       John 2017-11-07 16:54:00 2017-11-07 16:52:00 2017-11-07 16:54:00 120 secs
4    4567       1       Paul 2017-11-07 17:50:00 2017-11-07 17:50:00 2017-11-07 17:52:00 120 secs
5    5678       1       Paul 2017-11-07 17:52:00 2017-11-07 17:50:00 2017-11-07 17:52:00 120 secs
6    6789       1       John 2017-11-08 04:00:00 2017-11-08 04:00:00 2017-11-08 04:02:00 120 secs
7    7890       1       John 2017-11-08 04:02:00 2017-11-08 04:00:00 2017-11-08 04:02:00 120 secs

A: Here is a tidyverse approach that partitions the groups by the processing cluster identity, as well as case_id, and agent_name:
Arranging all the click in sequence, generate a new id flag for each time that a hist_id sequence encounters a transition to a new agent_name. cumsum those flags to generate a unique prcl_id per case, per agent, per cluster processing chunk. With all three id's you can then run your chosen mutations within the desired partitions.
df %>%
    arrange(hist_id) %>%  # to ensure there are no wrinkles
    mutate(ag_chg_flg = ifelse(lag(agent_name) != agent_name, 1, 0) %>%
               coalesce(0) # to reassign the first click in a case_id to 0 (from NA)
           ) %>%
    group_by(case_id, agent_name) %>%
    mutate(prcl_id = cumsum(ag_chg_flg) + 1) %>%  # generate the proc_clst_id (starting at 1)
    group_by(case_id, agent_name, prcl_id) %>%  # group by the complete composite id
    mutate(first = first(modify_time),
           last = last(modify_time),
           diff = min(difftime(last, first))
           )

Which gets you:

# A tibble: 7 x 9
# Groups:   case_id, agent_name, prcl_id [3]
  hist_id case_id agent_name         modify_time ag_chg_flg prcl_id               first                last   diff
    <dbl>   <dbl>     <fctr>              <dttm>      <dbl>   <dbl>              <dttm>              <dttm> <time>
1    1234       1       John 2017-11-07 14:52:00          0       1 2017-11-07 14:52:00 2017-11-07 14:54:00 2 mins
2    2345       1       John 2017-11-07 14:53:00          0       1 2017-11-07 14:52:00 2017-11-07 14:54:00 2 mins
3    3456       1       John 2017-11-07 14:54:00          0       1 2017-11-07 14:52:00 2017-11-07 14:54:00 2 mins
4    4567       1       Paul 2017-11-07 15:50:00          1       2 2017-11-07 15:50:00 2017-11-07 15:52:00 2 mins
5    5678       1       Paul 2017-11-07 15:52:00          0       2 2017-11-07 15:50:00 2017-11-07 15:52:00 2 mins
6    6789       1       John 2017-11-08 02:00:00          1       2 2017-11-08 02:00:00 2017-11-08 02:02:00 2 mins
7    7890       1       John 2017-11-08 02:02:00          0       2 2017-11-08 02:00:00 2017-11-08 02:02:00 2 mins


text:
Q: Importing functions in R In Python we have chance to import a certain function from a library with a command "import function from library as smth. Do we have something similar in R?
I know that we can call the function like "library::function()", my question mostly refers to the "as" part.

A: It is not common and not necessary to do this in R. The assignment operator <- can be used to give a new name to an existing function. For example, one could define a function that does exactly the same as lubridate's, year() function with:
asYear <- lubridate::year

One could argue that, by doing so, the year() function has been "imported" from the lubridate package and that it is now called asYear(). In fact, the new function does just the same (which is no surprise, simply because it is the same):
asYear(Sys.Date())
#[1] 2016

So it is possible to construct an analogy to "from package import as", but it is not a good idea to do this. Here are a few reasons I can think of:

*

*Debugging a code where library functions have been renamed will be
much more difficult.

*The documentation is not available for the renamed function. In this example, ?asYear won't work, in contrast to ?lubridate::year or library(lubridate); help(year).

*The function is not only renamed but it is copied, which clutters the environment and is inefficient in terms of memory usage.

*The maintenance of the code becomes unnecessarily difficult. If another programmer (or the original programmer a few years later) looks at a code containing such a redefinition of a function, it will be harder for her or him to understand what this function is doing.

There are probably more reasons, but I hope that this is sufficient to discourage the use of such a construction. Different programming languages have different peculiarities, and as a programmer it is necessary to adapt to them. What is common in Python can be awkward in R, and vice versa.
A simple and commonly used way to handle such a standard situation in R is to use library() to load the entire namespace of the package containing the requested function:
library (lubridate)
year(Sys.Date())

However, one should be aware of possible namespace clashes, especially if many libraries are loaded simultaneously. Different functions could be defined with the same name in different packages. A well-known example thereof are the contrasting implementations of the lag() function in the dplyr and stats package.
In such cases one can use the double colon operator :: to resolve the namespace that should be addressed. This would be similar to the use of "from" in the case of "import", but such a specification would be needed each time the function is called.
lubridate::year(Sys.Date())
#[1] 2016


text:
Q: Почему не работает функция для получения значения ключей, getKeys? Есть массивы объектов: posts, albums. Есть функция getPost() которая возвращает в результат значение определенных ключей, определенных юзеров.
 Есть функция getKey() которая в теории дает возможность возвращать значения ключей новых массивов,без повторения кода. Если раскомментировать вызов //getPhotos(1) тогда функция getKey() не сработает, вопрос почему?

let posts = [
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 2,
"id": 11,
"title": "et ea vero quia laudantium autem",
"body": "delectus reiciendis molestiae occaecati non minima eveniet qui voluptatibus\naccusamus in eum beatae sit\nvel qui neque voluptates ut commodi qui incidunt\nut animi commodi"
},
{
"userId": 3,
"id": 22,
"title": "dolor sint quo a velit explicabo quia nam",
"body": "eos qui et ipsum ipsam suscipit aut\nsed omnis non odio\nexpedita earum mollitia molestiae aut atque rem suscipit\nnam impedit esse"
}]
let albums = [
{
"userId": 1,
"id": 1,
"title": "quidem molestiae enim"
},
{
"userId": 2,
"id": 11,
"title": "quam nostrum impedit mollitia quod et dolor"
},
 {
"userId": 3,
"id": 22,
"title": "et rem non provident vel ut"
}]
let state = {
posts: [],
albums: []
};

function getPost(userId) {
 let post = posts.reduce(function(acc, item) {
 if(item.userId === userId) {
  acc.push(item['title'])
 }
  return acc;
 }, [])

state.posts = post
return state.posts
}

function getKey(le, arr, get, key) {
var le = arr.reduce(function(acc,item) {
 if(item.get === get) {
  acc.push(item[key])
 }
 return acc;
},[])

state.arr = le
return state.arr
}

function getPhotos(albumId) {

  getKey(p, photos, albumId, "url"); // вызываю функцию с нужными параметрами

}

getPost(1) // вызывает пост userId = 1
//getPhotos(1) // не вызывается
console.log(state)

A: В коде очень много воды, поэтому я постараюсь тебе помочь реализовать то, что ты хотел, не отвечая на твой вопрос:

*

*Есть функция getPost, которая по userId должна получать пост, тогда я не понимаю, зачем ты изменяешь state? Функция с префиксом get в названии явно ничего не должна менять.
function getPostByUserId(array, userId) {
  return array.find(post => post.userId == userId)
}

так код намного короче и понятнее.

*Вторая функция getKey не отражает того, что она действительно делает на самом деле, в твоем случае логичнее ее назвать getItemByKey, ее реализация примет следующий вид
getItemByKeyValue(array, key, value) {
  return array.find(item => item[key] === value);
}

Функция вернет тебе нужный объект по заданному ключу с определенным значением.
Если ты перепишешь свой код с использованием этих подходов, то я думаю, что твоя проблема решится. А вообще, когда работаешь со state в любой абстракции, то его нельзя менять на прямую, это плохая практика. State обычно изменяется путем присваивания нового state.


text:
Q: Solve the triple integral Let $V = \{(x,y,z) \mid x^2+y^2 \le 4x, z \le x^2+y^2\}$
I need to solve the following triple integral:
$$\iiint_V \,dx\,dy\,dz$$
What I've done:
$$\iiint_V \,dx\,dy\,dz = \int_0^{16}dz \bigg( \int_{V_1}dx\,dy + \int_{V_2}dx\,dy \bigg),$$
where $V_1 = \{(x,y,z) \mid 0 \le x \le \frac{\sqrt{z}}{4}, -\sqrt{4-(x-2)^2} \le y \le \sqrt{4-(x-2)^2} \}$
and $V_2 = \{(x,y,z) \mid \frac{\sqrt{z}}{4} \le x \le \sqrt{z}, -\sqrt{z-x^2} \le y \le \sqrt{z-x^2} \}$
But it looks so ugly, I think I should use polar (or other) substitution. How I can use it in this case?

A: Hint. Use cylindrical coordinates. Note that
$$ x^2+y^2 \le 4x\implies r\leq 4\cos(\theta).$$
Moreover I guess that you need also $z\geq 0$. Then
$$V=\int_{\theta=-\pi/2}^{\pi/2}\int_{r=0}^{4\cos(\theta)}\int_{z=0}^{r^2} 1\, (dz\, r dr\, d\theta).$$


text:
Q: Confused with a simple example of paging and panning. Obj-C Studying iOs Development by - The Big Nerd Ranch Guide" (Conway and Hillegass)
Chapter "Subclassing UIView and UIScrollView"; Panning and paging.
The following chunk of code being typed in  the
- (BOOL)application: didFinishLaunchingWithOptions: method.
(HypnosisView - is a custom made class that actually performs the drawing on the screen.)
Can't understand following code:
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

//-------Adding a scrool option-----------

CGRect screenRect=[[self window] bounds];

//  create the UIScrollView to have the size of the window, matching its size
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:screenRect];

[scrollView setPagingEnabled:YES];
[[self window] addSubview:scrollView];

//  create the HypnosisView with a frame that is twice the size of the screen (with a big
// width)
CGRect bigRect = screenRect;
bigRect.size.width *=2.0;

HypnosisView *view=[[HypnosisView alloc] initWithFrame:screenRect];

//  add the HypnosisView as a subview of the scrollView istead of the window
[scrollView addSubview:view];

// move the ractangle for the other HypnosisView to the right, just off the screen
screenRect.origin.x = screenRect.size.width;
HypnosisView *anotherView = [[HypnosisView alloc] initWithFrame:screenRect];
[scrollView addSubview:anotherView];

// tell the scrollView how big its virtual world is
[scrollView setContentSize:bigRect.size];

So our goal is to create a view instance with an width bigger than the iphone screen.

*

*First we are declaring new variable "screenRect" that has bounds of a "window".

*Then we are creating an instance of "UIScrollView" that has frame dimensions same as the
"screenRect" same as the window.

*Making paging enabled.

*Adding our newly created "scrollView" to the hierarchy of views.
So we have parent "window" and child "scrollView" (that has same dimensions as our main window)

*Declaring a new variable "bigRect", and making it equal to our previously declared "screenRect".

*Setting bigRect's "width" property to be twice as much.

*Creating a new "view" object that is an instance of  our custom made Hypnosis class that actually performs the drawing. We set our view's frame to be the same as our "screenRect" frame.

*Adding our newly created "view" to the hierarchy of views. Now we have 3 level hierarchy: UIWindow--> UIScrollView-->HypnosysView
9.Now here, I don't understand what this line of code does and why do we need it (screenRect.origin.x = screenRect.size.width;)
10). Why are we creating another instance of HypnosisView in the next line?
11). at the end we notify scrollView about how big its size.

A: 9.Now here, I don't understand what this line of code does and why do we need it (screenRect.origin.x = screenRect.size.width;)

10). Why are we creating another instance of HypnosisView in the next line?

The example will display 2 HypnosisViews which are side by side in a scroll view. The second one is off screen. So you have to drag/page the scroll view to see it.
screenRect.origin.x = screenRect.size.width

This just positions the 2nd hypnosis view to the right of the fist one.


text:
Q: Is it possible to have a single regular expression that matches against multiple expressions? I have a date that I'm allowing to be in multiple formats:
24-01-12
january 24 2013
etc

is there a way to combine 2 or more distinct regular expressions into one using pipes or another method? I tried nesting brackets but this doesn't work, of course:
[regex | regex]

A: Yea, try this:
(\d\d-\d\d-\d\d)|([a-z]*)

// So basically:
(regex)|(regex)

This matches all words, and the date in the first line.
(use (?:regex) if you want non-capturing groups, instead of capturing ones.)
If you were literally placing your regexes in the [], then that was the problem.


text:
Q: How to prove that $x^n-x^{n-1}-....-x-1=0$ has one real root when $n$ is odd and two real roots when $n$ is even Let $NF(n)$ denote the $n$-bonacci number such that $$NF(n)^n-NF(n)^{n-1}-...-NF(n)-1=0$$ Prove that if $2|n$ then there are two real solutions to the above equation, else there is one real solution. I was able to prove that the $n$-bonacci numbers are solutions to $NF(n)^{n+1}-2NF(n)^n+1=0$ which simplifies the polynomial. But I don't know how to approach my question.

A: Hint:
Rewrite it $x^n−\frac{x^n−1}{x−1}$ and study the numerator $x^{n+1}−2x^n+1$
The sign of its derivative should be easy to find as this factors well.
Show it has $2$ or $3$ roots, but the trivial root $x=1$ is spurious for the original problem.


text:
Q: How to compile code from stdin? The code is quite simple :
test$ cat test.cpp

int main()
{
}

Is there a way to compile the code that is coming from a standard output?
I have tried this :
cat test.cpp | g++ -

and some variations, but none produced executable.

Just some clarifications. I have a program which preprocess a file, and produces another file which I want to compile. I thought about not creating this intermediate file, but to instead produce the object file directly.

A: The compiler would have probably told you:
-E or -x required when input is from standard input

Try
cat test.cpp | g++ -x c++ -

A: Did you try this ?
$ cat tst.cpp | g++ -x c++ -

I have just tried it under Cygwin and had no problem.


text:
Q: Paypal Plugin Cordova not creating build(Intel XDK) I am working on PayPal (Intel XDk Cordova) . For this I came to  this link. According to the instruction I created Cordova Project , added platform android and IOS , added Plugin PayPal and then build my project. Now at this time I have A full Cordova Project containing the this link's PayPal plugin.
Then I created Intel XDK project . Included all the permission . Then in www folder I place the PAyPal Cordova project which I created before(above). Included the example code and necessary file of js to www folder. Two buttons as describe in example and all necessary Paypal keys . Now In :"Add Plugin" of project I added the local plugin with these details:
Name: PayPalMobile
id: com.paypal.cordova.mobilesdk
location: myPathtoHomeDirectory/IntelProjects/PayPalIntel/www/PayPalMobileCordovaPluginProject
After all this I build my intel project . But I am not getting successful build. Getting error messages.Log is given below. Any help will be appriciated.
I am unable to upload the attachment because of large size of project.
The build failed. An error occurred while building the application. Verify your build assets are correct and try again.
Build Log:
Building a Cordova 3.3 application.
Plugin "PayPalMobilePlugin" installed.
Updated "debuggable" to "false"
An unexpected error occured while attempting to build the application.////////////////////////////////This Error

A: It is going to be difficult to debug your build given just the build output. As you can see, the build output is not comprehensive. We are looking to get this resolved. In the meantime, you may have to share some screen shots of the project tab for your app to get the best assistance.


text:
Q: mongodb 3.0.3 Ubuntu 14.04.2 AWS m3.medium Upstart PID mismatch Is it possible to run mongod via upstart and keep track of the PID via start-stop-daemon or otherwise?
After following these instructions on the mongodb docs page for ubuntu installation:
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org

All remnants of the ubuntu package have been removed prior to this.
I now have a running instance of mongod on boot, via Upstart. But for some reason Upstart and initctl do not know about it. It starts up fine, but initctl thinks it's in stop/waiting state.
To wit:
My /etc/mongod.conf.yml:
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  path: /var/log/mongodb/mongod.log
  logAppend: true
  logRotate: rename
  component:
    accessControl:
      verbosity: 2

net:
   bindIp: 127.0.0.1
   port: 27017

processManagement:
  fork: true

setParameter:
   enableLocalhostAuthBypass: false

security:
  authorization: disabled

My /etc/init/mongod.conf upstart script (renamed mongodb.pid to mongod.pid):
# Ubuntu upstart file at /etc/init/mongod.conf

# Recommended ulimit values for mongod or mongos
# See http://docs.mongodb.org/manual/reference/ulimit/#recommended-settings
#
limit fsize unlimited unlimited
limit cpu unlimited unlimited
limit as unlimited unlimited
limit nofile 64000 64000
limit rss unlimited unlimited
limit nproc 32000 32000

kill timeout 300 # wait 300s between SIGTERM and SIGKILL.

pre-start script
  DAEMONUSER=${DAEMONUSER:-mongodb}
  if [ ! -d /var/lib/mongod ]; then
    mkdir -p /var/lib/mongodb && chown mongodb:mongodb /var/lib/mongodb
  fi
  if [ ! -d /var/log/mongod ]; then
    mkdir -p /var/log/mongodb && chown mongodb:mongodb /var/log/mongodb
  fi

  touch /var/run/mongod.pid

  chown $DAEMONUSER /var/run/mongod.pid;

  if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
    echo never > /sys/kernel/mm/transparent_hugepage/enabled
  fi

  if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
    echo never > /sys/kernel/mm/transparent_hugepage/defrag
  fi

end script

start on runlevel [2345]
stop on runlevel [06]

script
  ENABLE_MONGOD="yes"
  CONF=/etc/mongod.conf.yml
  DAEMON=/usr/bin/mongod
  DAEMONUSER=${DAEMONUSER:-mongodb}

  if [ -f /etc/default/mongod ]; then . /etc/default/mongod; fi

  # Handle NUMA access to CPUs (SERVER-3574)
  # This verifies the existence of numactl as well as testing that the command works
  NUMACTL_ARGS="--interleave=all"
  if which numactl >/dev/null 2>/dev/null && numactl $NUMACTL_ARGS ls / >/dev/null 2>/dev/null
  then
    NUMACTL="$(which numactl) -- $NUMACTL_ARGS"
    DAEMON_OPTS=${DAEMON_OPTS:-"--config $CONF"}
  else
    NUMACTL=""
    DAEMON_OPTS="-- "${DAEMON_OPTS:-"--config $CONF"}
  fi

  if [ "x$ENABLE_MONGOD" = "xyes" ]
  then
    exec start-stop-daemon --start \
        --chuid $DAEMONUSER \
        --pidfile /var/run/mongod.pid \
        --make-pidfile \
        --exec $NUMACTL $DAEMON $DAEMON_OPTS
  fi
end script

After a reboot I see this:
$ ps aux | grep mongo
mongodb   1085  0.2  1.1 363764 46704 ?        Sl   11:57   0:06 /usr/bin/mongod --config /etc/mongod.conf.yml

And everything appears to be fine. But the mongod.pid file does not store the same pid as the process:
$ cat /var/run/mongod.pid
985

Should be 1085.
What is the best way to fix this so Upstart has access to the actual PID?
UPDATE: tried to add expect daemon and expect fork with some change in behavior: initctl now sees a PID and denotes that mongod is running, but has the wrong PID. This means any subsequent command like sudo stop mongod or sudo start mongod will hang. Neither fork or daemon seems to fix this; what am I missing?

A: Ok so a bit of egg on my face - I was overlooking the fact that my shiny new /etc/mongod.conf.yml contained processManagement.fork: true. Setting this to false allows start-stop-daemon to capture the appropriate PID.


text:
Q: i want to prevent my browser can't able to resize My application is not a responsive web application, so if resize the browser size that design is misaligned. I want to prevent user can't able to resize or minimize the browser window when they are in my application option.
I can avoid when they opened any popup on my application but that is working in browser window.
How can i solve it or is it possible ?

A: It is not possible.
Browser is can be controlled by end user and you can't stop end user to resize it browser windows.
Note: This case is similar to prevent user from closing browser window which is also not possible.


text:
Q: Bootswatch theme font not working after publishing to Azure? Working on a basic ASP.NET MVC 5 project.I've read similar posts but couldn't find a solution that helps me.
I'm using a bootswatch theme (where you basically overwrite the bootstrap.css file http://bootswatch.com/) and after I publish my project to azure it simply defaults to some standard (ugly) font. It works fine when I run it locally in debug mode.
I tried different solutions but I can't figure out why it isn't working. Does anyone have any suggestions?


text:
Q: Retrieve Values From List In Entity Framework There are two different models in my project: Movie and Actor.  Movie has a list of actors and Actor has a list of movies.  What I want to do is given a movie, get all of the actors, and then for each actor examine their movies acted in.
So, to get the information, I use:
var movie = context.Movies.Include("Cast.ActingCredits").FirstOrDefault(m => m.Key == key);

The problem is that while the list ActingCredits is not null, there are no values in it.  Is there something that I am missing to load the values in the list?  ActingCredits is an ICollection<Movie>.
 public class Actor : ModelBase
 {
     public ICollection<Movie> ActingCredits { get; set; }
 }

public class Movie : ModelBase
{
    public string Title { get; set; }
    public DateTime Year { get; set; }
    public Genre Genre { get; set; }
    public int RunTime { get; set; }
    public int Sales { get; set; }
    public ICollection<Actor> Cast { get; set; }
}

EDIT: It has come to my attention that this may be wrong and is the cause of the issue.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany();
        modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany();
    }

A: You are not typing the correct name of the property in the include.
Try this:
    var movie = context.Movies.Include("Cast").FirstOrDefault(m => m.Key == key);

Also, make sure that your database is populated before executing this. I tested this and it works, it retrieves everything.

A: The problem was with the database and how I initialized it.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany(p => p.ActingCredits);
        modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany(m => m.Cast);

    }

Thanks to all who commented. I believe I understand entity framework a whole lot more now.

A: I suggest adding this:
using System.Data.Entity;

And then you can do the Include with strongly typed variables
var movie = context.Movies.Include(r => r.Cast)

However what I think you really want is to use Select instead of Include?
var movie = context.Movies.Select(r => r.Cast).SelectMany(r => r.ActingCredits);


text:
Q: Opportunities to clear Filter Input Field On Button Click using Angular first of all, iam pretty new to angular and web development in general. Moreover my english sucks but I try my best to express myself clearly.
I got the following scenario:
My tool presents a mat-table to the user that has a textfilter row above it.
The textfilter row is a simple input field that listens for the keyup event which will trigger the following function:

applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

This works fine. Now I want to give the user the opportunity to clear the input field by pressing a "Clear" button next to it.I have no idea how i can access the input field and change its value (to "") via typescript.
is it possible to use ViewChild and Element Ref here?
Probably a pretty dumb question but thanks in advance.

A: Why do you use keyup event listener on input fields in angular2+? I would take the advantage of two-way-binding. That's really powerful.
Have a look at the sandbox I made for you: https://codesandbox.io/s/icy-breeze-zcrcy
app.component.html:

  <input
    class="form-check-input"
    type="text"
    name="filterInput"
    [(ngModel)]="inputData"
  />
  <button (click)="clearInput()">CLEAR INPUT</button>

    Here is my inputData: {{ inputData }}

app.component.ts:
import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  public inputData: string = "";
  title = "CodeSandbox";

  clearInput() {
    this.inputData = "";
  }
}

and don't forget to add the FormsModule to your app.module.ts:
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";

import { AppComponent } from "./app.component";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, FormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Please keep in mind, ngModel is part of the FormsModule. That is why you have to import the FormsModule to your app.module.ts.

A: Well here is how i solved it. Is this way clean? I dont feel like it is^^
#filterField - added to  in template
@ViewChild('filterField', {static: false}) filterField: ElementRef; - added to the component.
Implemented this function for the Clear button click:
clearFilter(){
    this.filterField.nativeElement.value = "";
    this.applyFilter("");
  }


text:
Q: Sorting a String ArrayList Alphabetically Error Java I am getting these two errors when setting 2 strings equal to one another in a sorting algorithm. Does anyone know why this error is occurring and how to fix it?
Thanks
Picture of the errors: https://i.stack.imgur.com/0xYQD.png

A: You can't assign a value to a method. Instead, you want to call the set method: ArrayList#set(index, value).