text:
Q: How to find out in Vim which command is triggered by some shortcut I try to execute a command in some plugin by pushing it's keyboard shortcut F2. But some other command is executed, instead. But that command gives an error. So it is not clear where the key mapping of that interfering command is defined. I want to change the mapping of that shortcut. To do this I need to find out what that interfering command is.
Is there a way to find out which command is triggered by some keyboard shortcut?

A: verbose map <F2>

will give you information about both {rhs} and place where this mapping was defined. For insert mode mappings replace map with imap, same for other mapping modes.

A: You can check the shortcuts in ~/.vimrc file and ~/.vim/plugin/[you plugin name], maybe you find which action is bound to the F2 key.


text:
Q: Additional Column Created using Angular2 and Bootstrap 4 table This is my HTML for table

                 {{th}}

                {{i}}

Attached is my output image.
With the value of i its clear i got only 9 columns but the generated columns were 10. You could see a blank column after city.
Why is that? How can i overcome that blank column.

A: Though it was a miss in  I would like to recommend a better way of handling a common table Component which can be used across application would be as
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `

Hello {{name}}

              {{column.title}}

  `,
})
export class App {
  name:string;
  tableConfiguration:TableConfiguration;
  constructor() {
    this.tableConfiguration ={
      columns:new Array<Column>()
    }
    this.tableConfiguration.columns=
         [{title: 'First Name',columnSize:3},
          {title: 'Last Name',columnSize:3},
          {title: 'Contact Number',columnSize:2},
          {title: 'Gender',columnSize:2},
          {title: 'City',columnSize:2}];

    this.name = 'Angular2 Dynamic table'
  }
}
export interface TableConfiguration{
    columns:Array<Column>;
}
export interface Column{
  title:string;
  columnSize:number;
}
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

LIVE DEMO
Note:

*

*Change the selector as you wish

*ColumnSize should add to 12 as it is default in bootstrap

*Use this to wrap across application by using it inside a CommonModule

redpajama_set_name: RedPajamaStackExchange


text:
Q: History expansion in fish I want to run the previous command with part of it replaced. In bash, I can use the history expansion feature: ^x^y runs the previous command again, except with x replaced by y. I tried it in fish and it gave the following error:
^x^y
Expected a command, but instead found a redirection

Are there any ways to re-run a command with modifications in fish?


text:
Q: Angular (ionic): rendering component with loop: component's view doesn't update When using *ngFor to render a component multiple times, the components rendered are not updating in DOM as expected.
Rendering the component in an ionic page:
<ion-row *ngFor="let file of files; let i = index">
   <app-add-file (fileEvent)="fileEventHandler(i, $event)"></app-add-file>   //component
</ion-row>

components appear as expected, but when something changes in the component, the change doesn't reflect in the DOM.
Is there a way to force the rerender?
Should I use ChangeDetectorRef inside the component?
Versions:
"@ionic/angular": "^4.7.1",
"@angular/common": "^7.2.2",

would love to provide more data if needed.
Thanks!

A: Default change detector has trouble to detect change in array because it compares the instance of the array not the content. If you push something in the array, it remains the same instance so Angular won't start a change dectection.
Fastest solution is the use the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax to force the change dectection by changing the instance of the array.
myArray.push(data); // won't trigger change detection.
myArray = [...myArray]; // will trigger change detection.

Best solution would be to change the detection strategy of your component to OnPush. You can find more on this solution online.


text:
Q: React Native + Firebase: Is it possible to render multiple data value in different ref? Data Structure example:
  "post": {
    "postId": {
      "name": ".....",
      "data1": "....",
    },
  "users": {
    "userId": {
      "username": "....",
      "data2"
   }
  }

Is it possible to render (data1/data2) in the same listview?
like this:
_renderList(lists) {
  return(
     <View>
       <Text>{lists.data1}</Text>
       <Text>{lists.data2}</Text>
     </View>
  )
}

I try to set two ref() in constructor, but it doesn`t work:
constructor(props){
  super(props);
  this.state = {
   dataSource: new ListView.DataSource({
      rowHasChanges: (row1, row2) => row1 !==row2,
    }),
  }
  this.listsRef = firebase.database().ref('post');
  this.listsUserRef = firebase.database().ref('users').child(uid)
}


text:
Q: iPhone camera live steaming I have downloaded ffmpeg lib file and complied it for armv7. I added ffmpeg lib files in my project successfully. i am able to get iphone camera live streams using AVFoundation.
Now the problem is how will i convert iphone camera streams output as a input of ffmpeg for decode? Check my code
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {

CMBlockBufferRef bufferData = CMSampleBufferGetDataBuffer(sampleBuffer);
size_t lengthAtOffset;
size_t totalLength; char* data;

if(CMBlockBufferGetDataPointer(bufferData, 0, &lengthAtOffset, &totalLength, &data ) != noErr ){
       NSLog(@"error!");
      }
  }

Kindly suggested me which function of ffmpeg lib is used for decoding and how will i put CMBlockBufferRef as a input of this??
Thanks

A: you can use OPenTok for live video straming
https://github.com/opentok/opentok-ios-sdk


text:
Q: Find document by key only, in Firestore I am currently converting my Firebase real-time live database to use the new version, Firestore.
I would like to find a document by key. Previously, in Firebase real-time I could do something like this:
getSingleRouteById (key) {
   const ref = firebaseDb.ref('/data/')
   // now search for data with that key several nested layers down
   return ref.child(key)
      .once('value')
      .then((snapshot) => {
         return snapshot.val()
     })
}

After reading the new docs I can't find a way to achieve this in Firestore. Please, note I only know the key, so I need to search all documents, without knowing the actual path/reference.

A: There isn't a native way to do this. Part of the issue is there is no uniqueness to key across multiple paths, so when looking for the key 'key' in /data/ you could have /data/123/key and /data/231/key, meaning there are multiple possible answers.
The only way to achieve this would be to create your own inverted index. Whenever you create a document, use say Cloud Functions to automatically add a document to /keys/ with the id of key and update a field called paths to include the full path the key. paths should be map.
You can support deletions to by listening for that event and updating the inverted index.
For the above example, you would then have a document in /keys/ with the following:
Id: key
paths: {'/data/123/key' = true,
        '/data/231/key' = true}


text:
Q: Django and Postgres: psycopg2.errors.UniqueViolation: could not create unique index "main_customuser_pkey" DETAIL: Key (token)=(Key) is duplicated this error show up when i migrate to db using python manage.py migrate, model:
class CustomUser(AbstractUser):
    username = models.CharField(max_length=322,unique=True)
    email = models.EmailField(max_length=320,unique=True)
    token = models.UUIDField(primary_key=True,default=uuid.uuid1,editable=False)
    USERNAME_FIELD ='email'
    REQUIRED_FIELDS = ['username']


text:
Q: OnCheckedChangeListener is not working for the check box I am giving a check box to my action bar. this checkbox will be  used to select all the items of my listactivity. butsetOnCheckedChangeListener is not working for this check box.
  I have created a seperate layout for my action bar and inflate it dynamically through java code.(in oncreate()).
  Below is my code for ListActivity: I have to also call the webservice on send button click in my custom layout of action bar. Please give me a solution if anyone have.
package com.logiquemantra.frapps;

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

import com.logiquemantra.frapps.R;
import com.logiquemantra.frapps.adapter.ApplicationAdapter;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class AllAppsActivity extends ListActivity{

    private PackageManager packageManager = null;
    private List<ApplicationInfo> applist = null;
    private ApplicationAdapter listadaptor = null;
    CheckBox selectAll;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listofapps);
        packageManager = getPackageManager();
        new LoadApplications().execute();
        ActionBar mActionBar = getActionBar();
        mActionBar.setDisplayShowHomeEnabled(true);
        mActionBar.setDisplayShowTitleEnabled(false);
        LayoutInflater mInflater = LayoutInflater.from(this);

        View mCustomView = mInflater.inflate(R.layout.custom_app_share_action_bar, null);
        selectAll = (CheckBox)mCustomView.findViewById(R.id.selectAll);
        mActionBar.setCustomView(mCustomView);
        mActionBar.setDisplayShowCustomEnabled(true);
        selectAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if(isChecked){

                    for(int i = 0 ; i<applist.size(); i++){
                        getListView().setItemChecked(i, true);
                    }
                }else{
                    for(int i = 0 ; i<applist.size(); i++){
                        getListView().setItemChecked(i, false);
                    }
                }
            }
        });

    }

    /*@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.share_app_info, menu);
        return super.onCreateOptionsMenu(menu);
    } */

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        ApplicationInfo app = applist.get(position);
        try {
            Intent intent = packageManager
                    .getLaunchIntentForPackage(app.packageName);

            if (null != intent) {
                startActivity(intent);
            }
        } catch (ActivityNotFoundException e) {
            Toast.makeText(AllAppsActivity.this, e.getMessage(),
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(AllAppsActivity.this, e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }
    }

    private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
        ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
        for (ApplicationInfo info : list) {
            try {
                if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
                    applist.add(info);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return applist;
    }

    class LoadApplications extends AsyncTask<Void, Void, Void>{

        private ProgressDialog progress = null;

        @Override
        protected Void doInBackground(Void... params) {
            applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
            listadaptor = new ApplicationAdapter(AllAppsActivity.this,R.layout.listofapps, applist);

            return null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(Void result) {
            setListAdapter(listadaptor);
            progress.dismiss();
            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            progress = ProgressDialog.show(AllAppsActivity.this, null,
                    "Loading application info...");
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

    }

}

Here is my custom layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#000"
    android:gravity="center_vertical">

    <TextView
        android:id="@+id/title_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:textColor="#fff"
        android:text="Applications"
        android:textSize="18sp"
        android:paddingTop="3dp"
        />

    <LinearLayout android:id="@+id/ll"
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:layout_alignParentRight="true"
        >
          <CheckBox android:id="@+id/selectAll"
              android:text="@string/selectall"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignParentRight="true"
              android:checked="true"
              android:textColor="#fff"
              android:paddingRight="15dp"
              />

          <ImageButton
              android:id="@+id/imageButton"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignRight="@id/selectAll"
              android:layout_centerVertical="true"
              android:layout_marginRight="8dp"
              android:background="@null"
              android:src="@drawable/ic_action_send_now"
             />
    </LinearLayout>

</RelativeLayout>

A: I have just met this problem. You can't get the CheckBox's view this way.
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.custom_app_share_action_bar, null);
selectAll =  (CheckBox)mCustomView.findViewById(R.id.selectAll);

You should change it to:
View mCustomView=getActionBar().getCustomView();
selectAll =  (CheckBox)mCustomView.findViewById(R.id.selectAll);

I hope it can work for you.


text:
Q: Large Files in File Upload control taking very long time to send the request I am implementing progress bar functionality to file upload control, I've noticed is that going into any event handler after browsing to a large file, takes a long time, even if the handler's code has nothing to do with the upload. I'm not really sure how the FileUpload control works, but it seems as if some copying is going on before it even gets to my handler.
Can anybody explain me what is happening there and how can i reduce the sending time of post request.

A: You can't use a FileUpload control for what you want to do. When a user POSTs a file, you have to think of it like a querystring parameter. It goes as one Http Request. If you want to do a progress bar you'll want to look into something that can interact with the server asynchronously.

A: For large files you have to upload asynchronously. You can use the AJAX control tool kit to do that.
Go to this link and download the toolkit.
 AJAX Control Tool Kit


text:
Q: Crop rounded image from onPictureTaken result I have below situation:

I have full screen SurfaceView and in the first half I have my circle where I want to get my final resul from Image Cropping process.
below is the method where I get my bitmap image:
 @Override
    public void onPictureTaken(byte[] data, Camera camera)
    {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        //opts.inSampleSize = 2;
        Bitmap img = BitmapFactory.decodeByteArray(data, 0, data.length, opts);

//here I have to crop my image to be fit and have the same place like my circle.
}

Thanks!

A: There are two ways to do this

*

*Programmatically: can use a method like getRoundedShapeImage which crop image in rounded shape.

*Using Design: can use a square shape image having circular from inside and transparent inside circle, then set it as src of your imageView and set picture to background of imageView

I think 2nd one is better, because it will take less time and it is easy as compare to first one.

A: You can use custom circleimageview.
I found this library. Github link: https://github.com/hdodenhof/CircleImageView
usage
<de.hdodenhof.circleimageview.CircleImageView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/circle_image"
    android:layout_width="96dp"
    android:layout_height="96dp"
    app:border_width="2dp"
    app:border_color="#FF000000"/>

After you can set bitmap to circle imageview in pictureTaken method.
CircleImageView iv=(CircleImageView)findViewById(R.id.circle_image);
iv.setImageBitmap(bmp);


text:
Q: textual content without metadata from Tika via SolrCell Using Solr 3.6 and the ExtractionRequestHandler (aka Tika), is it possible to map just the textual content (of a PDF) to a field minus the metadata? The "content" field produced by Tika unfortunately contains all the metadata munged in with the text content of the document.
I would like to provide some snippet highlighting of the content and the subject metadata within the content field is skewing the highlight results.
UPDATE: Screenshot of Tika output as indexed by Solr. Highlighted portion is the block of metadata that gets prepended as a block of text to the PDF content.

The ExtractingRequestHandler in solrconfig.xml:
<requestHandler name="/update/extract" startup="lazy" class="solr.extraction.ExtractingRequestHandler">
    <lst name="defaults">
    <str name="lowernames">true</str>
    <str name="uprefix">ignored_</str>
    </lst>
</requestHandler>

Schema.xml fields. Note "content" receives Tika's content output directly. The "page" and "collection" fields are set with literal values when a doc is posted to the handler.
<field name="id" type="string" indexed="true" stored="true" required="true"/>
<field name="title" type="text_general" indexed="true" stored="true" multiValued="true"/>
<field name="subject" type="text_general" indexed="true" stored="true" multiValued="true"/>
<field name="content" type="text_general" indexed="true" stored="true" multiValued="true"/>
<field name="collection" type="text_general" indexed="true" stored="true"/>
<field name="page" type="tint" indexed="true" stored="true"/>
<field name="timestamp" type="date" indexed="true" stored="true" default="NOW" multiValued="false"/>

A: As all other answers are completely irrelevant, I'll post mine:
I have experienced exactly the same problem as OP describes, (Solr 4.3.0, custom config, custom schema, etc. I'm not newbie or something and understand Solr internals pretty well)
This was my ERH config:
  <requestHandler name="/update/extract"
                  startup="lazy"
                  class="solr.extraction.ExtractingRequestHandler" >
    <lst name="defaults">
      <str name="uprefix">ignored_</str>
      <str name="fmap.a">ignored_</str>
      <str name="fmap.div">ignored_</str>
      <str name="fmap.content">text</str>
      <str name="captureAttr">false</str>

      <str name="lowernames">true</str>
      <bool name="ignoreTikaException">true</bool>
    </lst>
  </requestHandler>

It was basically configured to ignore everything except the content (i believe it's reasonable for many people).
After careful investigation i found out, that
<str name="captureAttr">false</str>

was the thing caused OP's issue. By default it is turned on, but i turned it off as i did not need it anyway. And that was my mistake. I have no idea why, but it causes Solr to put extracted attributes into fmap.content field altogether with extracted text.
So the solution is to turn it back on.
Final ERH:
  <requestHandler name="/update/extract"
                  startup="lazy"
                  class="solr.extraction.ExtractingRequestHandler" >
    <lst name="defaults">
      <str name="uprefix">ignored_</str>
      <str name="fmap.a">ignored_</str>
      <str name="fmap.div">ignored_</str>
      <str name="fmap.content">text</str>
      <str name="captureAttr">true</str>

      <str name="lowernames">true</str>
      <bool name="ignoreTikaException">true</bool>
    </lst>
  </requestHandler>

Now, only extracted text is put to fmap.content field.
Unfortunately i have not found any piece of documentation which can explain this. Either bug or just stupid behavior

A: Tika with Solr produces different fields for the content and the metadata.
If you use the Standard ExtractingRequestHandler -
  <requestHandler name="/update/extract"
                  startup="lazy"
                  class="solr.extraction.ExtractingRequestHandler" >
    <lst name="defaults">
      <!-- All the main content goes into "text"... if you need to return
           the extracted text or do highlighting, use a stored field. -->
      <str name="fmap.content">text</str>
      <str name="lowernames">true</str>
      <str name="uprefix">ignored_</str>

      <!-- capture link hrefs but ignore div attributes -->
      <str name="captureAttr">true</str>
      <str name="fmap.a">links</str>
      <str name="fmap.div">ignored_</str>
    </lst>
</requestHandler>

The field map content is set to text field which should be only the content of your pdf.
The other metadata fields can be easily checked by modifying the schema.xml.
mark stored true for igonred field type
<fieldtype name="ignored" stored="true" indexed="false" multiValued="true" class="solr.StrField" />

Capture all fields -
   <dynamicField name="*" type="ignored" multiValued="true" />

Tika adds lot of fields for the metadata with the content being set separately e.g. response when fed extract handler with a ppt.
<doc>
    <arr name="application_name">
        <str>Microsoft PowerPoint</str>
    </arr>
    <str name="category">POT - US</str>
    <str name="comments">version 1.1</str>
    <arr name="company">
        <str>
        </str>
    </arr>
    <arr name="content_type">
        <str>application/vnd.ms-powerpoint</str>
    </arr>
    <arr name="creation_date">
        <str>2000-03-15T16:57:27Z</str>
    </arr>
    <arr name="custom_delivery_date">
        <str>
        </str>
    </arr>
    <arr name="custom_docid">
        <str>
        </str>
    </arr>
    <arr name="custom_docidinslide">
        <str>true</str>
    </arr>
    <arr name="custom_docidintitle">
        <str>true</str>
    </arr>
    <arr name="custom_docidposition">
        <str>0</str>
    </arr>
    <arr name="custom_event">
        <str>
        </str>
    </arr>
    <arr name="custom_final">
        <str>false</str>
    </arr>
    <arr name="custom_mckpapersize">
        <str>US</str>
    </arr>
    <arr name="custom_notespagelayout">
        <str>Lower</str>
    </arr>
    <arr name="custom_title">
        <str>Lower Universal Template US</str>
    </arr>
    <arr name="custom_universal_objects">
        <str>true</str>
    </arr>
    <arr name="edit_time">
        <str>284587970000</str>
    </arr>
    <str name="id">101</str>
    <arr name="ignored_">
        <str>slideShow</str>
        <str>slide</str>
        <str>slide</str>
        <str>slideNotes</str>
    </arr>
    <str name="keywords">test</str>
    <arr name="last_author">
        <str>Corporate</str>
    </arr>
    <arr name="last_printed">
        <str>2000-03-17T20:28:57Z</str>
    </arr>
    <arr name="last_save_date">
        <str>2009-03-24T16:52:26Z</str>
    </arr>
    <arr name="manager">
        <str>
        </str>
    </arr>
    <arr name="meta">
        <str>stream_source_info</str>
        <str>file:/C:/temp/nuggets/100000.ppt</str>
        <str>Last-Author</str>
        <str>Corporate</str>
        <str>Slide-Count</str>
        <str>2</str>
        <str>custom:DocIDPosition</str>
        <str>0</str>
        <str>Application-Name</str>
        <str>Microsoft PowerPoint</str>
        <str>custom:Delivery Date</str>
        <str>
        </str>
        <str>custom:Event</str>
        <str>
        </str>
        <str>Edit-Time</str>
        <str>284587970000</str>
        <str>Word-Count</str>
        <str>120</str>
        <str>Creation-Date</str>
        <str>2000-03-15T16:57:27Z</str>
        <str>stream_size</str>
        <str>181248</str>
        <str>Manager</str>
        <str>
        </str>
        <str>stream_name</str>
        <str>100000.ppt</str>
        <str>Company</str>
        <str>
        </str>
        <str>Keywords</str>
        <str>test</str>
        <str>Last-Save-Date</str>
        <str>2009-03-24T16:52:26Z</str>
        <str>Revision-Number</str>
        <str>91</str>
        <str>Last-Printed</str>
        <str>2000-03-17T20:28:57Z</str>
        <str>Comments</str>
        <str>version 1.1</str>
        <str>Template</str>
        <str>
        </str>
        <str>custom:PaperSize</str>
        <str>US</str>
        <str>custom:DocID</str>
        <str>
        </str>
        <str>xmpTPg:NPages</str>
        <str>2</str>
        <str>custom:NotesPageLayout</str>
        <str>Lower</str>
        <str>custom:DocIDinSlide</str>
        <str>true</str>
        <str>Category</str>
        <str>POT - US</str>
        <str>custom:Universal Objects</str>
        <str>true</str>
        <str>custom:Final</str>
        <str>false</str>
        <str>custom:DocIDinTitle</str>
        <str>true</str>
        <str>Content-Type</str>
        <str>application/vnd.ms-powerpoint</str>
        <str>custom:Title</str>
        <str>test</str>
    </arr>
    <arr name="p">
        <str>slide-content</str>
        <str>slide-content</str>
    </arr>
    <arr name="revision_number">
        <str>91</str>
    </arr>
    <arr name="slide_count">
        <str>2</str>
    </arr>
    <arr name="stream_name">
        <str>100000.ppt</str>
    </arr>
    <arr name="stream_size">
        <str>181248</str>
    </arr>
    <arr name="stream_source_info">
        <str>file:/C:/temp/test/100000.ppt</str>
    </arr>
    <arr name="template">
        <str>
        </str>
    </arr>
    <!-- Content field -->
    <arr name="text">
        <str>test Test test test test tes t</str>
    </arr>
    <arr name="title">
        <str>test</str>
    </arr>
    <arr name="word_count">
        <str>120</str>
    </arr>
    <arr name="xmptpg_npages">
        <str>2</str>
    </arr>
</doc>

A: I no longer have the problem I described above. Since asking the question, I have updated to Solr 4.0 alpha and recreated schema.xml from the Solr Cell example that ships with the 4.0a package. I suspect my original schema was copying the metadata fields' content to the text field, so it was most likely my own error.

A: In the solrconfig.xml, where the request handler is defined, add this line below
<str name="fmap.title">ignored_</str>

This tells Tika to simply ignore the title attribute (or which ever attributes you want ignored) it finds embedded within the PDF.

A: In my case, <str name="xpath">/xhtml:html/xhtml:body//node()</str> allowed extraction of content without the meta.
<requestHandler name="/update/extract" startup="lazy" class="solr.extraction.ExtractingRequestHandler" >
    <lst name="defaults">
      <str name="lowernames">true</str>
      <str name="fmap.meta">ignored_</str>
      <str name="fmap.content">content</str>
      <!-- Specify where content should be extracted exactly -->
      <str name="xpath">/xhtml:html/xhtml:body//node()</str>
    </lst>
</requestHandler>


text:
Q: React with TS, eslint error import/no-unresolved
*

*I have next ESLINT issue:
Unable to resolve path to module 'lib-name'  import/no-unresolved

*App tech is React with Typescript

*On running eslint got a bounch above error

*Tried a lot of different solution and still has the same problem
this is .eslintrc.js file
const sharedRules = {
  // import
  'import/prefer-default-export': 'off',
  'import/no-extraneous-dependencies': 'off', // This is useful for lodash imports like "import get from lodash/get"
  'import/extensions': [
    'error',
    'ignorePackages',
    {
      js: 'never',
      jsx: 'never',
      ts: 'never',
      tsx: 'never',
    },
  ],
  // js
  'curly': 2,
  'no-use-before-define': 'off', // must disable base rule to use proper typescript-eslint rule
  'camelcase': 'off', // This is unavoidable in data coming from the BE
  'max-classes-per-file': 'off',
  'no-octal': 'off',
  'no-shadow': 'off',
  'no-underscore-dangle': 'off',
  // react
  'react-hooks/exhaustive-deps': 'warn',
  'react/jsx-filename-extension': 'off',
  'react/jsx-one-expression-per-line': 'off',
  'react/jsx-props-no-spreading': 'off',
  'react/prop-types': 'off',
  'react/no-unused-prop-types': 'off',
  'react/require-default-props': 'off',
  'react/react-in-jsx-scope': 'off', // https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html
  // a11y
  'jsx-a11y/anchor-is-valid': 'off',
  'jsx-a11y/label-has-associated-control': 'off', // Just a hassle, you can nest inputs inside labels and it works fine. Check checkbox component for example.
  'jsx-a11y/control-has-associated-label': 'off',
  'jsx-a11y/no-noninteractive-tabindex': 'off',
  'jsx-a11y/click-events-have-key-events': 'off',
  'jsx-a11y/no-static-element-interactions': 'off',
  'import/no-unresolved': [2, { caseSensitive: false }],
};

const typeScriptRules = {
  '@typescript-eslint/no-explicit-any': 'warn',
  '@typescript-eslint/ban-ts-comment': 'warn',
  '@typescript-eslint/explicit-function-return-type': 'off',
  '@typescript-eslint/no-use-before-define': ['error'],
  '@typescript-eslint/no-non-null-assertion': 'off',
  ...sharedRules,
};

module.exports = {
  env: {
    browser: true,
    es6: true,
    jest: true,
  },
  extends: ['airbnb', 'airbnb/hooks', 'prettier'],
  globals: {
    createMockHttpRequest: true,
    createStore: true,
    mockAjaxRequest: true,
  },
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 11,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint', 'eslint-plugin-prettier'],
  rules: { ...sharedRules },
  overrides: [
    {
      extends: [
        'airbnb',
        'airbnb/hooks',
        'plugin:@typescript-eslint/eslint-recommended',
        'plugin:@typescript-eslint/recommended',
        'prettier',
        'prettier/@typescript-eslint',
        'prettier/react',
      ],
      files: ['**/*.ts', '**/*.tsx'],
      rules: { ...typeScriptRules },
      settings: {
        'import/resolver': {
          node: {
            extensions: ['.js', '.jsx', '.ts', '.tsx'],
          },
        },
      },
    },
  ],
};

-- I have also next file in repo eslintrc.json
{
  "root": true,
  "plugins": ["@nrwl/nx", "react", "react-hooks"],
  "overrides": [
    {
      "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
      "rules": {
        "@nrwl/nx/enforce-module-boundaries": [
          "error",
          {
            "enforceBuildableLibDependency": true,
            "allow": [],
            "depConstraints": [
              {
                "sourceTag": "*",
                "onlyDependOnLibsWithTags": ["*"]
              }
            ]
          }
        ]
      },
    },
    {
      "files": ["*.ts", "*.tsx"],
      "extends": ["plugin:@nrwl/nx/typescript"],
      "rules": {}
    },
    {
      "files": ["*.js", "*.jsx"],
      "extends": ["plugin:@nrwl/nx/javascript"],
      "rules": {}
    }
  ]
}

Any help is welcome!! :)

A: I fixed this one on my Nx project by adding this to the .eslintrc.json at the root of the project:
"settings": {
  "import/parsers": {
    "@typescript-eslint/parser": [".ts", ".tsx"]
  },
  "import/resolver": {
    "typescript": {
      "project": ["tsconfig.base.json"]
    },
    "node": {
      "project": ["tsconfig.base.json"]
    }
  }
}


text:
Q: React/D3: Graph will not display In another component I am displaying the contents of data on the screen with no problem. However, I am having problems using that same data to build a graph. When I click submit a graph is to be displayed on the screen but the browser just keep crashing.  Can someone help me figure out what in the code is causing this thanks?
In the console data contains what looks like a JSON file:
{data:{action:[action: "changed", timestamp: 12345678], ...}

Display Component:
class Graph extends Component {

    constructor({nodes}) {
    const times = d3.extent(nodes.action.map(action => {action.action}))
    const range = [50, 450]
    super({nodes})
    this.state = {nodes, times, range}
    }

    componentDidMount() {
        let group
        const { nodes, times, range } = this.state
        const { target } = this.refs
        const scale = d3.scaleTime().domain(times).range(range)

        d3.select(target)
            .append('svg')
            .attr('height', 200)
            .attr('width', 500)

        group = d3.select(target.children[0])
            .selectAll('g')
            .data(nodes)
            .enter()
            .append('g')
            .attr(
                'transform',
                (d, i) => 'translate(' + scale(d.timestamp) + ', 0)'
            )

        group.append('circle')
            .attr('cy', 160)
            .attr('r', 5)
            .style('fill', 'blue')

        group.append('text')
            .text(d => d.timestamp + " - " + d.action)
            .style('font-size', 10)
            .attr('y', 115)
            .attr('x', -95)
            .attr('transform', 'rotate(-45)')

    }

    render() {
        return (
            <Graph name="Timeline"/>

        )
    }

}

export default Graph;


text:
Q: Using Weierstrass's Factorization Theorem I am trying to factorize $\sin(x)\over x$ which by Taylor series expansion and using the roots is $$a \cdot \left(1 - \frac{x}{\pi} \right) \left(1 + \frac{x}{\pi} \right) \left(1 -  \frac{x}{2\pi} \right) \left(1 + \frac{x}{2\pi} \right) \left(1 - \frac{x}{3\pi} \right) \left(1 + \frac{x}{3\pi} \right) \cdots$$
Now I was told that this nasty factor $a$ conveniently becomes $1$ due to Weierstrass's Factorization Theorem which is a transcendental generalization of the Fundamental Theorem of Algebra.
My question
Could you please show me how $a$ is being neutralized using this theorem? Or don't you even need this theorem to do so?

A: The value of this product for small x's is the product of $(1-x^2/(n \pi)^2)$ which, when you take logs (and due to the second power in x), behaves like the sum over n of $-x^2/(n\pi)^2$, which approaches 0 as x approaches 0.

A: The Weierstrass factorization theorem as usually stated tells you only that $a=e^{g(x)}$ for some entire function $g(x)$.  Hadamard's refinement says a little more, based on the growth rate of the function.  In your case, since $\left| \frac{\sin x}{x} \right| < \exp\left(|x|^{1+o(1)} \right)$ as the complex number $x$ grows, Hadamard tells you that $g(x)$ is a polynomial of degree at most $1$.  Since $\frac{\sin x}{x}$ and $\prod_{n=1}^{\infty} \left(1 - \frac{x^2}{n^2 \pi^2} \right)$ are both even functions, so is $e^{g(x)}$.  Thus $g(-x)-g(x)$ is a (constant) integer multiple of $2\pi i$.  Hence $g(x)$ is constant, and so is $a$.  Finally, as everyone else has pointed out, taking the limit as $x$ goes to $0$ shows that $a=1$.
See Ahlfors, Complex analysis for more about Hadamard's refinement, which relates the "order" and "genus" of an entire function.


text:
Q: PHP e-commerce site talking to internal database for stock / ordering? I'm working on an e-commerce site (either bespoke with PHP, or using Drupal/Ubercart), and I'd like to investigate the site interacting with an internal (filemaker) database we use to manage stock and orders. Currently we manually transfer orders from the web site to our own database, and the site does not check or record changes in stock.
My plan to allow the 2 to interact is as follows:

*

*Make the internal database available externaly on a machine with a fixed IP

*Allow external access from the site only

*Connect to the internal database using ODBC (or similar)

*Use simple queries to check stock / record stock changes / record order details

Am I missing something here as this sounds quite straight forward?
Is there another solution I should be taking a look at?
Thanks in advance for any help or comments.

A: Your plan sounds completely straightforward.  You might want to consider making sure that end-users can never take an immediate action that updates the backend.  Backend stuff should only be modified when a backend user takes an action, i.e. approves of an order.  I'm not sure how your preferred e-commerce solutions work, though.


text:
Q: Not able to create a command in eclipse plugin I have created a plugin in eclipse, but I want to add a new command in it. As per an online tutorial, I should go to plugin.xml and then select Extensions and then add commands. But I am not able to right click on it.
Can any one please tell me why I am not able to right click and add a new command in my plugin.


text:
Q: IIF When Using Similar Criteria Their are 2 different jobstatuses that I want to display the same way, my IIF statement changes the display, BUT I would like for only one entry to be returned for both.  For example, I want it to show like this
JobStatus
---------
Inactive
Let Go

But the returned result set I get is
JobStatus
---------
Active
Inactive
Let Go
Let Go

What do I need to change in my query to make it show like I need? (and I need this to be done via a query not vba)
jobstatus1: IIf([jobstatus]="Terminated","Let Go",IIf([jobstatus]="Fired","Let Go",[jobstatus]))

EDIT -- Full Syntax.  The IIF statement I need to use is for the alpha.jobstatus line right after the Select
SELECT alpha.jobstatus, Count(beta.ID) AS CountOfID
FROM alpha LEFT JOIN beta ON alpha.jobstatus = beta.jobstatus
GROUP BY alpha.jobstatus, alpha.order
HAVING (((alpha.jobstatus) Not In (Select [jobstatus] From tbl_Valid)))
ORDER BY alpha.order;

A: Use SELECT DISTINCT to return only distinct values.
Also you can use a simpler expression for that calculated field --- one with a single IIf instead of nested IIf's.  Switch your query to SQL View and revise the start of the statement text to this ...
SELECT DISTINCT IIf([jobstatus] IN ('Terminated', 'Fired'), 'Let Go', [jobstatus]) AS jobstatus1


text:
Q: How can we check if string is a version number or not How to check if a string contains version in numberic/decimal format in shell script
for eg we have 1.2.3.5 or 2.3.5
What if we do not have a constraint on the number of characters we have in here. It could x.x.x.x or x.x as well.

A: If you're using bash, you can use the =~ regex match binary operator, for example:
pax> if [[ 1.x20.3 =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] ; then echo yes ; fi

pax> if [[ 1.20.3 =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] ; then echo yes ; fi
yes

For your particular test data, the following regex will do the trick:
^[0-9]+(\.[0-9]+)*$

(a number followed by any quantity of .<number> extensions) although, if you want to handle edge cases like 1.2-rc7 or 4.5-special, you'll need something a little more complex.

A: Using bash regular expressions:
echo -n "Test: "
read i

if [[ $i =~ ^[0-9]+(\.[0-9]+){2,3}$ ]];
then
  echo Yes
fi

This accepts digits.digits.digits or digits.digits.digits.digits
Change {2,3} to shrink or enlarge the acceptable number of .digits (or  {2,} for "at least 2")

*

*^ means beginning of string

*[0-9]+ means at least one digit

*\. is a dot

*(...){2,3} accepts 2 or 3 of what's inside the ()

*$ means end of string

A: And if you're truly restricted to the Bourne shell, then use expr:
if expr 1.2.3.4.5 : '^[0-9][.0-9]*[0-9]$' > /dev/null; then
  echo "yep, it's a version number"
fi

I'm sure there are solutions involving awk or sed, but this will do.

A: Flip the logic: check if it contains an "invalid" character:
$ str=1.2.3.4.5; [[ $str == *[^0-9.]* ]] && echo nope || echo yup
yup
$ str=123x4.5;   [[ $str == *[^0-9.]* ]] && echo nope || echo yup
nope

Downside to this answer:
$ str=123....; [[ $str == *[^0-9.]* ]] && echo nope || echo yup
yup


text:
Q: cramp framework sync 'render' correct way using em-synchrony To describe my problem I attach simple Cramp http://cramp.in/ class.
I add some modification but its mainly work like https://github.com/lifo/cramp-pub-sub-chat-demo/blob/master/app/actions/chat_action.rb
class ChatAction < Cramp::Websocket

  use_fiber_pool

  on_start :create_redis
  on_finish :handle_leave, :destroy_redis
  on_data :received_data

  def create_redis
    @redis = EM::Hiredis.connect('redis://127.0.0.1:6379/0')
  end

  def destroy_redis
    @redis.pubsub.close_connection
    @redis.close_connection
  end

  def received_data(data)
    msg = parse_json(data)
    case msg[:action]
    when 'join'
      handle_join(msg)
    when 'message'
      handle_message(msg)
    else
      # skip
    end
  end

  def handle_join(msg)
    @user = msg[:user]
    subscribe
    publish(:action => 'control', :user => @user, :message => 'joined the chat room')
  end

  def handle_leave
    publish :action => 'control', :user => @user, :message => 'left the chat room'
  end

  def handle_message(msg)
    publish(msg.merge(:user => @user))
    # added only for inline sync tests
    render_json(:action => 'message', :user => @user, :message => "this info should appear after published message")
  end

  private

  def subscribe
    @redis.pubsub.subscribe('chat') do |message|
      render(message)
    end
  end

  def publish(message)
    @redis.publish('chat', encode_json(message))
  end

  def encode_json(obj)
    Yajl::Encoder.encode(obj)
  end

  def parse_json(str)
    Yajl::Parser.parse(str, :symbolize_keys => true)
  end

  def render_json(hash)
    render encode_json(hash)
  end
end

More about what i try to do is in handle_message method.
I try send messages to client in correct order. First publish message to all subscribers, second render some internal info only for current connected client.
For above code client receives:
{"action":"message","user":"user1","message":"this info should appear after published message"}
{"action":"message","message":"simple message","user":"user1"}

Its not synchronized, because of em-hiredis defferable responses, probably.
So I try to synchronized it this way:
def handle_message(msg)
  EM::Synchrony.sync publish(msg.merge(:user => @user))
  EM::Synchrony.next_tick do # if I comment this block messages order is still incorrect
     render_json(:action => 'message', :user => @user, :message => "this info should appear after published message")
  end
end

Now, client handle messages with correct order.
{"action":"message","message":"simple message","user":"user1"}
{"action":"message","user":"user1","message":"this info should appear after published message"}

My questions are:

*

*When I comment EM::Synchrony.next_tick block, messages order is still incorrect. What meaning have EM::Synchrony.next_tick block in this example?

*Is this good way to handle inline sync with Cramp or EventMachine ?

*Is there a better, clearer way to handle it ?

Thank you!

A: I found solution of this problem, em-synchrony should work inline out of the box by requiring this library:
require 'em-synchrony/em-hiredis'

class ChatAction < Cramp::Websocket

Using EM::Synchrony.next_tick block is bad idea, with big help of em-synchrony community I add em-hiredis 0.2.1 compatibility patch on github
So now handle_message method looks like this:
def handle_message(msg)
   publish(msg.merge(:user => @user))
   render_json(:action => 'message', :user => @user, :message => "this info should appear after published message")
end

Don`t forget to take this gem from github
gem 'em-synchrony', :git=> 'git://github.com/igrigorik/em-synchrony.git'

Hope it helps someone.


text:
Q: What are these Negative Lumps for? I seem to get a lot of Negative Lumps while cleaning up my Chakras. I can't use them from my backpack - do they serve any sort of purpose? Or can I just sell them for Meat?

A: Negative Lumps along with Chakra Sludges can be used to buy items from the Crimbo Lumps Shop.
They can be sold for 16 Meat each.


text:
Q: Django admin gives a suspiciouserror when trying to upload an image with imagefield I know this is a question asked several times but it seems that this one is a weird issue.
I set settings.py's MEDIA_ROOT = '/home/siteowner/proj/proj/static/product_photos/'
and then I created a photo = models.ImageField("logo", upload_to="", blank=True, null=True) model attribute.
Of course I've created the right path (the one specified in MEDIA_ROOT) and I gave it chmod 775.
Despite this when I try to submit the data I always get:
SuspiciousOperation at /admin/catalogo/catalog/add/
Attempted access to './image.jpg' denied.

As you may see I'm not prepending any slash to upload_to (that seems to be the most common error for this kind of model field).
I'm running django with mod_wsgi in a virtualenv (because I'm on ubuntu 10.04 using py2.7) if this might help (everything is working fine btw, django works as expected).
Any idea?

A: 'upload_to' can't be blank as far as I know. I would set the MEDIA_ROOT to:
'/home/siteowner/proj/proj/static/'
and then specify 'product_photos' as the upload_to property.


text:
Q: Are "can't see the difference" "don't see the difference" interchangeable? In one of my posts (Are "passive participle" and " Passive voice" the same in Modern English?), I said

I can't see the difference between ex_1 and ex_2.

Actually, I am not sure whether I used the right preposition. Another option could be "I don't"

I don't see the difference between ex_1 and ex_2.

Both "can't see the difference" and "don't see the difference" have some hits on ELL. I guess both of them are interchangeable in any situations.
Google Ngram also verifies this.

Is my understanding right?

A: Yes, your understanding is correct.
"Don't see the difference" denotes you present state of not seeing, while "can't see the difference" denotes your inability to see.
In practice, they are interchangeable.
By the way, "can't" and "don't" are contractions of verbs with the word "not" ("can not" and "do not"). They aren't prepositions, that is, words like in, on, over, under, between etc.

A: Honestly,

*

*Don´t you see - means by your brain

*Can´t you see - means by your eyes

So there is a slightly different meaning.


text:
Q: Clearing Print in Python So I'm pretty new to both coding and this website, so please bear with me if this is stupid:
I'm working on a personal project and would like to find a way to clear "print()" statements in python 3.6. For example:
print("The user would see this text.")

but if I continue
print("The user would see this text.")
print("They would also see this text.")

Is there a way to make it so a user would only see the second print statement?
I have seen "os.system('cls')" and "os.system('clear')" recommended, but I get these errors for each:
os.system('cls')

resulting in
sh: 1: cls: not found
and
os.system('clear')

resulting in
TERM environment variable not set.
Obviously I'm missing something, but if you know what it'd be much appreciated. If you know of another way to do what I'm thinking, that would also be awesome. Thank you for taking the time to read this, and thanks for any help.
Edit: I'm using Repl.it as my IDE. Could this be an issue with that site specifically?
Edit: Downloaded a new IDE to check, and the reply worked. If you are new and using Repl.it, be aware that some code does not function properly.

A: The method that I've used in the past to 'reprint' something on an existing line is to make use of the standard output directly, coupled with a carriage return to bring the printed statement's cursor back to the start of the line (\r = carriage return), instead of relying on the print function.
In pseudocode:
# Send what you want to print initially to standard output, with a carriage return appended to the front of it.
# Flush the contents of standard output.
# Send the second thing you want to print to standard output.

A working example in Python:
import sys

sys.stdout.write('\rThe user would see this text')
sys.stdout.flush()
sys.stdout.write('\rThe user would also see this text')

Edit
Figured I'd add an example where you can actually see the code working, since the working example above is going to execute so quickly that you'll never see the original line. The below code incorporates a sleep so that you can see it print the first line, wait, then reprint the line using the second string:
import sys
from time import sleep

sys.stdout.write('\rThe user would see this text')
sys.stdout.flush()

sleep(2)

sys.stdout.write('\rThe user would also see this text')


text:
Q: C# Search for value inside Array I want to search for values inside some arrays, e.g. lets say I have 3 arrays:
int[] Year = {1930, 2000, 2020};

string[] Months = {"January", "May", "December"};

int[] NumOfCars = {10, 5, 200};

So lets say I want to find how many cars there are in the year 2000, I want to be able to get a result like:
RESULT: 2000, May, 5

How would I be able to do this.
Thanks
edited:
I want the user to search for the value without them knowing the values, for e.g. Console.WriteLine("Search a Year"); and they put the year 2000 and then the program displays the Result.
RESULT: 2000, May, 5

A: If your structure is simple, then Kevin's answer is enough.
But if you have more complicated structures you could
//Make a model of you data
public class L {
    public int Year {get; set;}
    public string Months {get; set;}
    public int NumOfCars {get; set;}
}

void Main()
{

    List<L> myList = new List<L>();

   //Load you arrays into the structure
    myList.Add(new L { Year = 1930, Months = "January", NumOfCars = 10});
    myList.Add(new L { Year = 2000, Months = "May", NumOfCars = 5});
    myList.Add(new L { Year = 2030, Months = "December", NumOfCars = 30});

    //Use LINQ
    var r = myList.Where(x => x.Year == 2000).Select(x => x);

    Console.Write(r);
}

A: Based on your arrays and your description, it sounds like you want to find the value in one array and then look up information in the other two based on the position you found in the first.
public string LookUpValues(string year)
{

    for(var ii = 0; ii < Year.Length; ii++)
    {
       if(Year[ii] == year)
       {
         return Year[ii] + ", " + Months[ii] + ", " + NumOfCars[ii]

       }
    }
}

A: You can do the search with simple linear search as follows
using System;
class Find
{
    public static void Main()
    {
        int[] Year = {1930, 2000, 2020};
        string[] Months = {"January", "May", "December"};

        int k;

        int[] NumOfCars = {10, 5, 200};

        Console.Write("enter the year");

        year=int.Parse(Console.ReadLine());

        //Console.Write("search the year");

        for(int i=0;i<Year.Length-1;i++)
        {
            if(year==Year[i])
                k=i;
        }

        Console.Write("Result{0},{1],{2}",Year[k],Months[k],NumOfCars[k]);

   }

}


text:
Q: How to add wcf functionality to an existing asp.net website project I have several asp.net website projects for various sites.
Currently I want to add REST API's to these projects so I can start developing mobile apps (using HTML5/JavaScript/CSS3 and PhoneGap) that make use of these webservices.
Since WCF is far more powerful than regular asp.net webservices (among others with control over the service and authentication/authorization), I'd love to add these to my existing website project.
I did a Google search but cant find anywhere a step-by-step tutorial how this can be done. And also if there's any functionality I'd possibly loose when adding WCF functionality
I was also thinking of creating a new project specifically for WCF, but  think I'd rather add it to an existing website project.
Can anyone help me with this?

A: Depending on exactly what your needs are and how your current web site is configured, there are two approaches.
If you are using a Web Site Project, then you should create your WCF service in a different application:
1) Create a new ASP.Net Web Application Project.
2) Add a new item to the project and select the type of WCF Service or WCF Data Service.
When you deploy this project, you will deploy it to your web server, but not as part of your web site since configuring the web.config will be a large manual effort.
If you are using a Web Application Project, then you could add the WCF Service directly to your existing project. However, I only recommend this approach if you are Silverlight applets within the web site that rely on the user's authenticated credentials.

A: WCF can be configured with a lot of bindings and it can be configured to return xml or json(.net 4.0). Try to create a wcf service configured to use basichttpbinding or wsHttpBinding and to format the response as json and use jquery to interact with the wcf service. This article might help you http://www.codeproject.com/KB/aspnet/Cross_Domain_Call.aspx


text:
Q: PhoneGap jQuery-Mobile app using both local and server pages I've got a basic PhoneGap / jQuery-Mobile app on iOS that initially loads up the index.html page that is part of the app.  On that page there is a link that points to a page on our mobile site (not deployed as part of the app).  This works as I wanted because when I click the link it loads the mobile page in my app (I updated the PhoneGap.plist ExternalHosts so it would load in my app instead of in Safari).
My question is whether from the mobile page displayed in my app, but not part of my app, can I link back to a page that is part of my app?  Is this even possible?  If not, what are my options for achieving this same behavior?
The basic design that I would like for my app is to have some sort of menu that is always visible with buttons that take you back to the menu of different pages in the app (e.g. Home, Mobile Site, Camera, etc.). Clicking a menu link loads the mobile web page below the nav bar, and this page could be local to the Phonegap app OR a remote page on our server.  (optionally, the menu/nav bar could be part of the mobile site -- but this would only work if the Home button on the mobile site page menu would load the app's index.html page).
The plan is to maintain one code base for apps on iOS and Android and still access the phone's capabilities, such as the camera, with PhoneGap. However, rather than having to write .ajax calls for every server side exchange of information (retrieval, db updates, etc.), we could leverage some of our existing server side forms and pages already hosted as .aspx pages by serving them INTO our Phonegap app.  Being able to link back and forth between pages in my app and on my mobile site (all using JQuery Mobile) would be ideal if possible.  Being able to include phonegap.js on our remote server pages and include javascript API calls to phonegap from inside those pages would be another big bonus if it can be done.
Hopefully this makes sense.
Thanks in advance!

A: Yes, we did. We used ChildBrowser as I described below. We had to modify the ChildBrowser user interface on both iOS and Android to hide the address bar and toolbar. It took a little bit of effort to get our mobile site header / menu bar to match our native header bar. The end result is a seamless experience -- you literally can't tell whether you are viewing a native page or a page served up from our mobile site.

A: I would suspect a href could point to the file:///asset/www locally and it should load. If you linked a realitive URL as its switched hosts it will load from the server so the best bet is local paths. You could always runa  browser check on your server and output the paths relating to IOS,Android etc.
Have you also checked yet if the app will be approved by apple if its a wrapper loading content from your site?


text:
Q: How to calculate mean on second axis until row-specific column in Pytorch? I am looking for a fast way to calculate the mean for each row of a 2d matrix but only until a specific column. The remaining values of each row can be ignored. The column is different for each row.
In Numpy, it could be coded like this. However, I am hoping to find a solution without a for loop which also does not break the gradients.
import numpy as np

arr = np.linspace(0, 10, 15).reshape(3,5)
cols = [2,0,4]

for row, col in enumerate(cols):
    arr[row, col+1:] = np.nan

result = np.nanmean(arr, axis=1)

Any suggestions?
Edit: Best solution I have found so far:
result = torch.stack([arr[i, 0:cols[i]+1].mean() for i in range(len(arr))])

But I would still like to avoid the for loop.

A: Try creating a mask:
t = torch.tensor(arr)
mask = torch.arange(t.shape[1]) <= torch.tensor(cols).unsqueeze(-1)

result = (t*mask).sum(1)/mask.sum(1)

Output:
tensor([0.7143, 3.5714, 8.5714], dtype=torch.float64)


text:
Q: Joomla progressive cache doesn't handle modules with variable output I have a module which allows the user to choose a category, which is then used for filtering the component's output.  So when the user first clicks on the menu item, the view shows items from all categories, then as they click on the module, a param such as &catid=69 etc. is added to the url and used to filter the items displayed.
A system plugin complements the behaviour by registering the extra catid param i.e.
$registeredurlparams->catid = 'INT';
$app->set('registeredurlparams', $registeredurlparams);

The module uses the category id to create the cache id, and shows the top-level categories + the subcategories of the category that was chosen.
This works fine with both conservative cache enabled in the system configuration and the System Cache plugin enabled.
My concern is that I cannot get it to work with progressive cache: even though the component output is cached correctly, the module doesn't get updated (so I never see the subcategories).
Eventually I plan to make the extension available on the JED, and I'd like to be compatible with all possible cache configurations. Is there any possibility to force the progressive cache to add the parameters I want to the cache id?
Workarounds such as sending the full category tree and doing it with ajax will not be accepted.

A: One thing you could look at is ContentModelArticle in the back end. You will notice that cleanCache()
forcibly clears the content modules that could be impacted by a save or create.
protected function cleanCache($group = null, $client_id = 0)
{
    parent::cleanCache('com_content');
    parent::cleanCache('mod_articles_archive');
    parent::cleanCache('mod_articles_categories');
    parent::cleanCache('mod_articles_category');
    parent::cleanCache('mod_articles_latest');
    parent::cleanCache('mod_articles_news');
    parent::cleanCache('mod_articles_popular');
}

I've always thought this was a sledge hammer/kludge since it doesn't let the webmaster control whether or not to do this,  but you could do something along the lines of making a custom cleanCache() for your model.


text:
Q: Restler: Internal actions Is there a way to perform REST actions in the middle of executing an action? For example, if I perform GET /index.php/book/1 I might receive the following:
[{
    "id" : 1,
    "title" : "This is a book.",
    "owner_id" : 4
}]

But what I'd like to do is before returning the above object, perform a GET /index.php/user/4 so the end result is:
[{
    "id" : 1,
    "title" : "This is a book.",
    "owner" : {
        "id" : 4,
        "name" : "John Smith",
        "age" : 40
    }
}]

A: There is even simple way of doing this with Restler by internally calling another api method directly instead of wasting one call to the server
class User{
    public function get($id, $includeOwner = true){
        $result = getUserFromDB($id)
        if($includeOwner){
            $result['owner'] = $this->get(getOwnerIdFromDB($id),false);
        }
    }
    return $result;
}

HTH


text:
Q: communicating between fragments through activity I have two fragments FGames and FGamesDetail. which display the list of Games and when clicked should populate the FGamesDetail fragment. I am using MVP pattern.
I am trying to implement MultiPane layout for tablet to have list and detail view next to each other.
I am getting a null pointer exception at 'mListener.onGameSelected(gameEntity);' in FGames. I know I have not initialised it at this place but should I be initialising it every method I go through in MVP pattern.
GamesAdapter - RecyclerView Adapter.
      @OnClick(R.id.row_container)
            void rowClick(){
                GamesPresenter gamesPresenter = new GamesPresenterImpl();
                gamesPresenter.showGameDetail(data.get(getLayoutPosition()));
                Toast.makeText(context, "itemClicked " + data.get(getLayoutPosition()), Toast.LENGTH_SHORT).show();
            }

GamesPresenter - Interface
    public interface GamesPresenter {
        void initUi();
        void showGameDetail(GameEntity gameEntity);

    }

GamesPresenterImpl -
    public class GamesPresenterImpl implements GamesPresenter {

    GamesView gamesView;
    private ApiInterface apiInterface;
    /**
     * Collects all subscriptions to unsubscribe later
     */
    @NonNull
    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();

    public GamesPresenterImpl() {}

    public GamesPresenterImpl(GamesView gamesView) {
        this.gamesView = gamesView;
    }

    @Override
    public void initUi() {
        getGamesData();
    }

    @Override
    public void showGameDetail(GameEntity gameEntity) {
       //gamesView was null so initialised here
        GamesView gamesView = new FGames();
        gamesView.onListItemClick(gameEntity);

      }
    }

GamesView - interface
    public interface GamesView {

        /**
         * Initialise the recycler view to list Games data
         * @param gameEntities
         */
        void initRecyclerView(List<GameEntity> gameEntities);

        void showToast(String message);

        void onListItemClick(GameEntity gameEntity);
    }
#

FGames - has all the implementation for the Fragment
    public class FGames extends Fragment implements GamesView {

        @BindView(R.id.rv_games)
        RecyclerView rvGames;
        private GamesAdapter gamesAdapter;
        private GamesPresenterImpl presenter;
        OnGameSelectedListener mListener;
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.games_layout, container, false);
            ButterKnife.bind(this, view);
            presenter = new GamesPresenterImpl(this);
            return view;
        }

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            try {
                mListener = (OnGameSelectedListener) context;
            } catch (ClassCastException e) {
                throw new ClassCastException(context.toString() + " must implement OnArticleSelectedListener");
            }
        }

        @Override
        public void onActivityCreated(@Nullable Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            presenter.initUi();
        }

        @Override
        public void initRecyclerView(List<GameEntity> gameEntities) {
            gamesAdapter = new GamesAdapter(getActivity(), gameEntities);
            rvGames.setAdapter(gamesAdapter);
            rvGames.setLayoutManager(new LinearLayoutManager(getActivity()));
        }

        @Override
        public void showToast(String message) {
            Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onListItemClick(GameEntity gameEntity) {
          //Here is where the NUll pointer exception is
            mListener.onGameSelected(gameEntity);
        }

        public interface OnGameSelectedListener{
            public void onGameSelected(GameEntity gameEntity);
        }
    }

MainActivity - which displays the performs the game selected operation to update the UI if detail fragment is available. I followed Android documentation to do this.
public class MainActivity extends AppCompatActivity implements FGames.OnGameSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //FGames fGames = new FGames();
        //getSupportFragmentManager().beginTransaction().add(R.id.games_container, fGames).commit();
    }

    @Override
    public void onGameSelected(GameEntity gameEntity) {
        FGameDetail gameDetailFrag = (FGameDetail) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_fGameDetail);
        if (gameDetailFrag == null) {
            // DisplayFragment (Fragment B) is not in the layout (handset layout),
        } else {
            // DisplayFragment (Fragment B) is in the layout (tablet layout),
            // so tell the fragment to update
            gameDetailFrag.updateContent(gameEntity);
        }
    }
}

ErrorLog
Process: com.example.rao.igttest, PID: 21481
                                                                         java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.rao.igttest.Games.View.FGames$OnGameSelectedListener.onGameSelected(com.example.rao.igttest.Games.Entity.GameEntity)' on a null object reference
                                                                             at com.example.rao.igttest.Games.View.FGames.onListItemClick(FGames.java:73)
                                                                             at com.example.rao.igttest.Games.Presenter.GamesPresenterImpl.showGameDetail(GamesPresenterImpl.java:53)
                                                                             at com.example.rao.igttest.Games.View.GamesAdapter$GamesViewHolder.rowClick(GamesAdapter.java:72)
                                                                             at com.example.rao.igttest.Games.View.GamesAdapter$GamesViewHolder_ViewBinding$1.doClick(GamesAdapter$GamesViewHolder_ViewBinding.java:33)
                                                                             at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22)
                                                                             at android.view.View.performClick(View.java:5637)
                                                                             at android.view.View$PerformClick.run(View.java:22429)
                                                                             at android.os.Handler.handleCallback(Handler.java:751)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)


text:
Q: Permission error: The process cannot access the file because it is being used by another process I'm using windows 10, I'm using tesseract latest version for text recognition, below is the sample code I'm using now. But sometimes for some images, it gives the following.
import cv2
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-
OCR\tesseract.exe'
config = ("-l eng --oem 1 --psm 7")

text=pytesseract.image_to_string(cv2.imread(r'C:\Users\Kesavan\Desktop\project\text Recogniton\opencv-text-recognition\images\cat.jpg'),config=config)
print(text)
Traceback (most recent call last):
  File "C:/Users/Kesavan/PycharmProjects/Project/text recogniton/tester.py", line 6, in <module>
    text=pytesseract.image_to_string(cv2.imread(r'C:\Users\Kesavan\Desktop\project\text Recogniton\opencv-text-recognition\images\cat.jpg'),config=config)
  File "C:\Users\Kesavan\PycharmProjects\learning\venv\Learnings\lib\site-packages\pytesseract\pytesseract.py", line 350, in image_to_string
    }[output_type]()
  File "C:\Users\Kesavan\PycharmProjects\learning\venv\Learnings\lib\site-packages\pytesseract\pytesseract.py", line 349, in <lambda>
    Output.STRING: lambda: run_and_get_output(*args),
  File "C:\Users\Kesavan\PycharmProjects\learning\venv\Learnings\lib\site-packages\pytesseract\pytesseract.py", line 265, in run_and_get_output
    return output_file.read().decode('utf-8').strip()
  File "C:\Users\Kesavan\AppData\Local\Programs\Python\Python37\lib\contextlib.py", line 119, in __exit__
    next(self.gen)
  File "C:\Users\Kesavan\PycharmProjects\learning\venv\Learnings\lib\site-packages\pytesseract\pytesseract.py", line 177, in save
    cleanup(f.name)
  File "C:\Users\Kesavan\PycharmProjects\learning\venv\Learnings\lib\site-packages\pytesseract\pytesseract.py", line 134, in cleanup
    raise e
  File "C:\Users\Kesavan\PycharmProjects\learning\venv\Learnings\lib\site-packages\pytesseract\pytesseract.py", line 131, in cleanup
    remove(filename)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\Kesavan\\AppData\\Local\\Temp\\tess_jjp7wfoq.txt'

This is the image for which I'm facing the issue
Thanks in advance

A: try to upgrade to the latest pytesseract version or follow this workaround:
https://groups.google.com/d/msg/tesseract-ocr/IyPpisQ1E4U/tl3IP3gqAwAJ


text:
Q: Rectangle Clicking on Pygame What i'm trying to do is draw a new screen when the user clicks 'start', 'controls' or quit. The first screen welcomes the user and asks them to 'click here to start the game', which is stated over a button. Even though the user advances to the next page, the previous button isn't visible but if you click where the button previously was, it still brings you to the next page even though I want the 'start' button to be that function. I currently have the next pages as screen.fill(RED) just to test the code.
#Main Menu Loop

while not done and display_menu:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if rect4.collidepoint(event.pos):
                    start_page +1
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if rect1.collidepoint(event.pos):
                    start_page +=1
                if rect2.collidepoint(event.pos):
                    start_page +=2
                    if start_page == 4:
                        display_menu = False

    # Set the screen background
    screen.fill(BLACK)

    if start_page == 1:

        screen.blit(bg2, (0, 0))
        pygame.draw.rect(screen, RED, rect4)
        text = font3.render("Click HERE to start Game!", True, WHITE)
        screen.blit(text, [125, 400])

    if start_page == 2:

        screen.blit(bg, (0, 0))

        #Drawing the Button
        pygame.draw.rect(screen, BLACK, rect1)
        pygame.draw.rect(screen, BLACK, rect2)
        pygame.draw.rect(screen, BLACK, rect3)

        #Text in Button
        text = font3.render("START", True, WHITE)
        screen.blit(text, [335, 325])
        text = font4.render("CONTROLS", True, WHITE)
        screen.blit(text, [320, 425])
        text = font3.render("QUIT", True, WHITE)
        screen.blit(text, [335, 525])

    if start_page == 3:

        screen.fill(GREEN)

    if start_page == 4:

        screen.fill(RED)

    clock.tick(60)

    pygame.display.flip()

I'm open for any suggestions. Thanks


text:
Q: Replicating database structure locally In my setup for a web application using PHP and MySQL, I am using separate databases for each user's private data. So in essence, every authenticated user will have access to only two different databases myappdb_public and myappdb_user_###. User credentials will be saved in a separate database myappdb_creds. The idea behind this setup is to increase the security of private data while maintaining a shared data resource.

*

*Is there a way to create a new database from a "template" of another database structural setup.

*Is there a way to update all "child" databases structures when the template is updated?

I have used replication before, but that was a totally different setup and not sure if there is a way to replicate structure only across multiple databases on the same local server.

A: Replication
"Database Replication" refers to dynamically copying any incoming insert/update/delete statements being made to one database to another identical database. The primary and secondary databases are considered "replicas" because at all times they contain the same data produced by the same history, though the secondary may be delayed by a small stretch of time. The secondary may be used for read-only queries in place of the primary. And the secondary may be transformed into a primary in case of fail-over.
Migration
What you are seeking is loosely called  "Database Migration", also called schema migration. The idea here is to reproduce the same structure (DDL) as another database. But each produced database is independent of the others, each having different users' data stored in them.

*

*A prime example example is multi-tenancy.

*Another use might be as part of a vertical-market app being licensed to various customers where on each new sale you need to establish a fresh database in a certain configuration as expected by the app.

Migration tools
Developers and DBAs used to do this migration work manually, devising their own ad-hoc solutions or habits. Fortunately we now have a choice of tools to help with this tedious though crucial chore.
Flyway
My favorite tool is Flyway. Built in Java, but wrapped as command-line  executables so you can use from scripts or other tools.
Flyway runs through a collection of SQL scripts, and optionally certain Java libraries you may write. The order of execution is determined by a certain file naming scheme.
A table is automatically created within the database to track scripts run. When new scripts are encountered, Flyway detects them and appropriately runs those that have not yet been applied to that particular database.
Flyway or other such tools are extremely helpful not only in production but also in testing and development. You can recreate a throw-away database automatically, and even bring it up to any particular point in the history of its schema evolution.
Anyone considering Flyway should also consider another quite similar product: Liquibase.
Other choices exist as well, such as the commercial tool Redgate.
Templates
Some databases such as Postgres provide for templates where you can create some tables and indexes and so in a database. After that, you can create a fresh new database whose initial state is copied from that state.
Indeed, Postgres always works that way, where template0 and template1 databases are used transparently by default when you ask for a database without explicitly specifying any other template.
Templates only solve the genesis problem, getting started. You will almost certainly evolve your database later. You'll add or drop tables, columns, indexes, and so on. You may need to run code to convert or update existing data en masse. For this you'll want to use migration tools, as the templates cannot help you after that initial genesis. So in my opinion, I would not bother with defining a template, instead using migration scripts for all that initial setup.


text:
Q: Jquery Select2 4.0 Bootstrap Styling I am using Select2 in a project, its styling sticks out like a sore thumb from other bootstrap(ed) components. Personally I like the way select2 looks but need to create consistency. In earlier versions I have used select2 boostrap css 3 from here
This doesnt work on Select2 4.0, anyone has any ideas or hints ? At the very least, I would like to adjust the height of Select2.
Much appreciated...

A: just use a regular select2 from https://select2.github.io/examples.html and override the style with !important declaration, for example
.select2-container .select2-selection--single {height: 50px !important;}


text:
Q: A question related to a Jordan curve : Is there an elementary proof? Let $f : [0, 1] \rightarrow \mathbb{R}^2$ be a Jordan curve, $\textit{i.e.}$,
$f$ is an injective continuous function with $f(0) = f(1)$.
Let $C$ be the set $f([0,1])$.
Assume that $p$ is an arbitrary point in $\mathbb{R}^2 \setminus C$.
Let $S(p)$ denote the set $\{ \, |f(t) - p| \, : \, ~ 0 \leq t \leq 1 \, \}$, $\textit{i.e.}$,
$S(p)$ is the collection of lengths from $p$ to any points in $C$.
Then it is clear that $S(p) \subset (0, \infty)$.
It is my question : Is there an elementary way to prove that $0 < \inf S(p)$?
It is equivalent that we can choose a small ball $B(p;r)$, the ball whose center is $p$
and radius is $r$, which is contained in $\mathbb{R}^2 \setminus C$.
In other words, if we can prove that $C$ is a closed set in $\mathbb{R}^2$, then this problem is proved.


text:
Q: Wrap full filepath in double quotes I have a file which I need to FTP using VBA and I have figured most part of it except last one where I need to insert " in the file name but not able to do.
csvPath = "C:\Users\10613527\Desktop\test\"
sWorkingDirectory = csvPath
sFileToSend = "Price_Change_10-08-15 20-35-49.csv"

iFreeFile = FreeFile
Open sWorkingDirectory & FTP_BATCH_FILE_NAME For Output As #iFreeFile
Print #iFreeFile, "open " & FTP_ADDRESS
Print #iFreeFile, FTP_USERID
Print #iFreeFile, FTP_PASSWORD
Print #iFreeFile, "ASCII"
Print #iFreeFile, "put " & sWorkingDirectory & sFileToSend
Print #iFreeFile, "dir"
Close #iFreeFile

'Shell command the FTP file to the server
Shell "ftp -i -w:20480 -s:" & sWorkingDirectory & FTP_BATCH_FILE_NAME

In the above code , I get the error that the file is not found.

The reason is that the file path and name is not in "", for example this code is writing another script file and executing that one.
So it needs to be
open ftp path
username
password
ASCII
put "C:\Users\10613527\Desktop\test\Price_Change_10-08-15 20-35-49.csv"
dir

and not
open ftp path
username
password
ASCII
put C:\Users\10613527\Desktop\test\Price_Change_10-08-15 20-35-49.csv
dir

Notice the " " in the PUT statement, I have no idea how to place them there.

A: Use "" to escape " in a vb string.
So
Print #iFreeFile, "put """ & sWorkingDirectory & sFileToSend & """"


text:
Q: Magento Error - missing class when accessing cart page? After upgrading to Magento Community 1.6.1.0 (stable) whenever I try and access the cart page, I'm getting this error:
Fatal error: Class 'Mage_Checkout_Block_Multishipping_Link' not found in /data01/director/public_html/xxxxx/app/code/core/Mage/Core/Model/Layout.php on line 465

If you google the first part of the error a number of other sites appear sporting the same error, but there is no mention of any solution.
Help?
The Layout.php file hasn't been changed (tried re-uploading the original file)

A: I solved the problem.
I had tried emptying caches, deleting browser cookies, different browsers, different themes and so on with no luck. In the end, re-uploading the 1.6.1.0 files did the trick (even though I hadn't modified any files outside the theming directories).
Hope this is useful for someone.


text:
Q: How list indexing works in Jinja I have a simple flask application where I need to show 2 images in a html page, all the images are stored in a static folder
While rendering the html page I am passing image file names as a list and on html page I am using jinja logic to show the images
img_lst = [filename1, filename2]
return render_template("index.html", img_lst=img_lst)

I can easily loop over the list and show images using below logic
{% for image in img_lst %}

{% endfor %}

but if I index a particulr file from a list I am getting an error
jinja2.exceptions.UndefinedError: 'img_lst' is undefined

I want to individually access filenames from list instead of looping over

A: i don't see any problem with your code above, but i'm guessing you need to force flask to reload templates, so jinja2 will take in consideration your variable img_lst the next reload.
add this config below and let me know if it works:
app.config["TEMPLATES_AUTO_RELOAD"] = True

Update
Your code works and i didn't get that error, so my guess probably you are working on other view/template and you forgot to pass img_lst in the context in render function.


text:
Q: How to migrate domain account to local account? How can I safely migrate an account from domain to standard local account ? I have a plenty of software installed within this account and I do not want to reinstall it again. I assume there are so many entries in registry that have to be preserved.

A: Like @Tim, I'm assuming you're talking about the user profile and not actually the account SID, since that's "fixed" and can't be "migrated".
The "official" tool provided by Microsoft for this purpose is the User State Migration Tool. It can be used to migrate local accounts to domain accounts.
If you're feeling particularly brave you can use one of a variety of unsupported methods, a couple of which I'll list here:

*

*The old "copy the profile" trick

*Swap the SID in the registry trick


text:
Q: Jedi USB project read and write Delphi I am using the Jedi usb hid component to connect to, read and write from a HID device. I have been unable to write to the device. I have been using this code.
type
TReport = Packed record
 ReportID: byte;
 Data: array [0..64] of byte;
 end;

procedure TForm1.Button1Click(Sender: TObject);
var
 I:integer;
 HidData:TReport;
 written:DWORD;
begin
hiddata.ReportID:=0;
hiddata.Data[0]:=0;
hiddata.Data[1]:=$80;
  for I := 2 to 64 do
    hiddata.Data[I]:=$FF;
currentdevice.WriteFile(hiddata,currentdevice.Caps.OutputReportByteLength,written);
end;

A: I made a test platform which you can use :
unit BasicMain;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, StdCtrls, Forms, Dialogs,
JvHidControllerClass, JvComponentBase;

type

TReport = packed record
  ReportID: byte;
  Data: array [0..64] of byte;
end;

TMainForm = class(TForm)
  HidCtl: TJvHidDeviceController;
  DeviceList: TListBox;
  Label1: TLabel;
  Label2: TLabel;
  Button1: TButton;
  procedure HidCtlDeviceChange(Sender: TObject);
  function HidCtlEnumerate(HidDev: TJvHidDevice;const Idx: Integer): Boolean;
  procedure Button1Click(Sender: TObject);
  procedure FormCreate( Sender : TObject);
  procedure DeviceRemoval(HidDev: TJvHidDevice);
  procedure DeviceArrival(HidDev: TJvHidDevice);
  public
end;

var
  MainForm: TMainForm;
  MyDevice: TJvHidDevice;

implementation

{$R *.dfm}
{ ***************************************************************************** }

Const
  MyVendorID = $04D8;   // Put in your matching VendorID
  MyProductID = $003F;  // Put in your matching ProductID

procedure TMainForm.FormCreate( Sender : TObject);
begin
  HidCtl.OnArrival:= DeviceArrival;
  HidCtl.OnRemoval:= DeviceRemoval;
end;

procedure TMainForm.DeviceRemoval(HidDev: TJvHidDevice);
begin
  if ((Assigned(MyDevice)) and (NOT MyDevice.IsPluggedIn)) then
  begin
    HidCtl.CheckIn(MyDevice);
  end;
end;

procedure TMainForm.DeviceArrival(HidDev: TJvHidDevice);
begin
  if ((HidDev.Attributes.VendorID = MyVendorID) AND
     (HidDev.Attributes.ProductID = MyProductID) AND
     (HidDev.Caps.OutputReportByteLength = SizeOf(TReport)) ) then
  begin
    if HidDev.CheckOut then
    begin
      MyDevice := HidDev;
    end;
  end;
end;

procedure TMainForm.HidCtlDeviceChange(Sender: TObject);
begin
  Label1.Caption := '-';
  Label2.Caption := '-';
  MyDevice := nil;
  DeviceList.Clear;
  HidCtl.Enumerate;
end;

function TMainForm.HidCtlEnumerate(HidDev: TJvHidDevice;const Idx: Integer): Boolean;
begin
  DeviceList.Items.Add(
  Format('%.4x/%.4x', [HidDev.Attributes.VendorID,HidDev.Attributes.ProductID]));
  if (HidDev.Attributes.VendorID = MyVendorID) and (HidDev.Attributes.ProductID =         MyProductID) then
  begin
    HidCtl.CheckOut(HidDev);
    MyDevice := HidDev;
    Label1.Caption := Format('%.4x/%.4x', [MyDevice.Attributes.VendorID ,   MyDevice.Attributes.ProductID]);
    Label2.Caption := 'Length = '+ IntToStr(MyDevice.Caps.OutputReportByteLength) + ' ' + IntToStr(MyDevice.Caps.InputReportByteLength);
  end;
  Result := True;
end;

procedure TMainForm.Button1Click(Sender: TObject);
var
  HidData : TReport;
  written : DWORD;
begin
  HidData.ReportID:=0;
  HidData.Data[0]:=$80;
  // Fill with more data

  MyDevice.WriteFile(HidData, MyDevice.Caps.OutputReportByteLength, Written);
  MyDevice.ReadFile(HidData, MyDevice.Caps.InputReportByteLength, Written);
end;

end.

object MainForm: TMainForm
  Left = 0
  Top = 0
  Caption = 'MainForm'
  ClientHeight = 341
  ClientWidth = 535
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
  object Label1: TLabel
    Left = 48
    Top = 8
    Width = 31
    Height = 13
    Caption = 'Label1'
  end
  object Label2: TLabel
    Left = 48
    Top = 27
    Width = 31
    Height = 13
    Caption = 'Label2'
  end
  object Button1: TButton
    Left = 48
    Top = 46
    Width = 75
    Height = 25
    Caption = 'Button1'
    TabOrder = 0
    OnClick = Button1Click
  end
  object ListBox1: TListBox
    Left = 48
    Top = 96
    Width = 465
    Height = 97
    ItemHeight = 13
    TabOrder = 1
  end
end

Fill in your VendorID and ProductID and the output data.

A: Effictivly one line do the trick that the writefile method is accepted or not :
ToWrite := TheDev.Caps.OutputReportByteLength;
TheDev.WriteFile(buffer,towrite,written);

The device accept only write of the correct buffer length. It doesn't work if you write only a part of the buffer length.


text:
Q: Flex box layout I am developing a layout with bootstrap and some flex containers and can't seem to find out why my box would always grow larger than its container. I created a fiddle to illustrate the problem:
example fiddle
.
The html part looks like this:

      const

        some very very very very very very very very very very very big content

      const

And the css is the following:
.const-width {
  max-width: 100px !important;
  min-width: 100px !important;
}

.bigcontent {
  background: #aaaaaa;
  white-space: nowrap;
}

As you can see, I have two constant width boxes on the sides and a flexible box that should take up the rest of the space between the other two. If the content of the flexible-width box grows too big, the rightmost box get's pushed off-screen. What I want instead is, that the content of the flexible-width box gets scrollable and everything remains on-screen.
I tried this by wrapping the content in another div, but couldn't get it to work.
Any help is appreciated! :)

A: Look like this?

.row {
  background: #f8f9fa;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
  overflow-x:auto!important;
}

.const-width {
  max-width: 100px !important;
  min-width: 100px !important;
}

.bigcontent {
  background: #aaaaaa;
  min-width: 500px;
  white-space: nowrap;

}

      <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css">

      <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">

      const

        some very very very very very very very very very very very very very very very very big content

      const

I delete scroll div and apply overflow-x to .col class auto with !important rule


text:
Q: Do we have the following "devissage commutative diagram" in K-theory? Let $X$ be a non-reduced Noetherian scheme. We define $K^0(X)$ to be the Grothendieck group of the derived category $Perf(X)$ and $K_0(X)$ to be the  Grothendieck group of the derived category $D^b_{coh}(X)$. Then we have a natural Cartan homomorphism
$$
K^0(X)\to K_0(X).
$$
given by inclusion of the derived categories $Perf(X)\subset D^b_{coh}(X)$.
Next we consider the associated reduced scheme $X_{red}$ with $f: X_{red}\to X$ and we have $K^0(X_{red})$ and $K_0(X_{red})$ also.
Moreover there are natural maps
$$
f^*:K^0(X)\to K^0(X_{red})
$$
and
$$
f_*:K_0(X_{red})\to K_0(X).
$$
By the devissage theorem in K-theory, $f_*:K_0(X_{red})\to K_0(X)$ is an isomorphism but this is not true for $f^*$.
My question is: do we have the following commutative diagram
$$\begin{array}[c]{ccc}
K^0(X)&{\rightarrow}&K_0(X)\\
\downarrow\scriptstyle{f^*}&&\uparrow\scriptstyle{\cong}\\
K^0(X_{red})&{\rightarrow}&K_0(X_{red})?
\end{array}$$


text:
Q: How to write a dos batch script to create a folder structure? I would like to be able to have a dos batch script that I could utilize to create a specific folder structure below what ever directory I may be in at any given time.
The specific folder structure that I need is:
[Directory:\] _Documentation
[Directory:\] _ProjectManagement
[Directory:\] Releases
[Directory:\] Source
[Directory:\] Source -> Trunk
[Directory:\] Source -> Trunk -> Library
[Directory:\] Source -> Trunk -> Projects
[Directory:\] Source -> Trunk -> Tests

A: Erm...is this a trick question, it looks kinda straightforward? if not then perhaps try the following in a batchfile somewhere in your path;
md _Documentation
md _ProjectManagement
md Releases
md Source
md Source\Trunk
md Source\Trunk\Library
md Source\Trunk\Projects
md Source\Trunk\Tests
Best of luck.


text:
Q: Initialising State in React Redux app with data in server I am working on my first React Redux project.
The project depends on a server to get its data and therefore there is also a server API that needs to be called in order to get those data.
My question is about initialising state.
There are 2 ways I can think of initialising state:
1.) First pass an empty object {} as the initialised state of the Redux store then inside componentDidMount that is where I call the API to access the data in the server and then update the state of the store/app then.
2.) In the reducer of the Redux app call all relevant server method (e.g. getCategories(), getPosts(), etc.) then compose a object with all of the data e.g. {categories: categories, posts: posts} then pass this object to the reducer as the initial state.
Which way is the recommended way for Redux when dealing with data stored in the server?
If there is a 3rd or 4th way that is the Redux way or the recommended way then please share your knowledge.  Thank you.

A: The way I work with data coming from the back end, and as far as I know is also the suggested way, is this:

*

*In the componentDidMount method call a thunk action creator. you can read more about them in this link.

*Inside that thunk action creator you first dispatch a REQUEST action, then perform a fetch to access the back end and when the response arrives you handle it on either the success or error handlers. Depending on the handler executed you dispatch either a SUCCESS or an ERROR action (and you attach to it all the relevant information that is coming from the back end so the reducer can access it).

*In your reducer you write code to handle all the above actions (REQUEST, SUCCESS and ERROR). Each handler will transition your state, for instance the REQUEST can set an isFetching flag to true that will let you show a spinner in the UI, and the SUCCESS can set that flag to false and populate the state with the data coming from the back end and passed to the reducer using the action dispatched.

*Once your reducer is updated, you will access that updated state from the UI, for instance using the connect react-redux function.
Regarding the initial state, it should represent a default state. for instance, it will have the isFetching flag in false and, if you are fetching a list of foods from the back end, then that list could be an empty list in your initial state. This is just a for instance of course. You need to set an initial state that makes sense to your app.
I hope this helps you.

A: The first way is the better way of initializing state. Your component makes the necessary API calls in componentDidMount and passes the data to Redux as payload of actions which the reducers use to update the state of your application.
The second way is not advisable. According to the Redux docs:

The reducer is a pure function that takes the previous state and an action, and returns the next state.
(previousState, action) => newState
...
  It's very important that the reducer stays pure. Things you should never do inside a reducer:

*

*Mutate its arguments;

*Perform side effects like API calls and routing transitions;

*Call non-pure functions, e.g. Date.now() or Math.random().

Edit:
You can also use thunk middleware and async actions to do API calls as explained in the Redux docs and @DiegoTArg's answer.


text:
Q: trying to create a new entry in the address book via the ABUnknownPersonViewController on iOS In iOS I'm trying to create a new entry in the address book via the ABUnknownPersonViewController with this code (it's an UITableViewController):
- (void)                       tableView:(UITableView *)tableView
accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *phoneNumber = [[cell textLabel] text];
    ABRecordRef record = ABPersonCreate();
    CFErrorRef error = NULL;
    ABMutableMultiValueRef phone =
            ABMultiValueCreateMutable(kABPersonPhoneProperty);
    ABMultiValueAddValueAndLabel
            (phone, phoneNumber, kABPersonPhoneMobileLabel, NULL);
    bool didSet = ABRecordSetValue(record, kABPersonPhoneProperty, phone,
            &error);

    if (!didSet) {
        return;
    }
    ABUnknownPersonViewController *viewController =
            [[[ABUnknownPersonViewController alloc] init] autorelease];

    [viewController setUnknownPersonViewDelegate:self];
    [viewController setAllowsAddingToAddressBook:YES];
    [viewController setAllowsActions:NO];
    [viewController setDisplayedPerson:record];
    [[self navigationController] setNavigationBarHidden:NO animated:NO];
    [[self navigationController] pushViewController:viewController
            animated:YES];
    CFRelease(record);
    CFRelease(phone);
}

Edit:
but it crashes apparently because the phoneNumber is formatted before is added to the address book (e.j. "987654321" becomes "987 654 321"). If I replace the phoneNumber with a constant string (@"987654321") everything runs alright. Also if I add value not for the ABPersonPhoneProperty but for ABPersonEmailProperty runs properly.
Any help?

A: It's working while I replace:
ABMutableMultiValueRef phone = ABMultiValueCreateMutable(kABPersonPhoneProperty);

with:
ABMutableMultiValueRef phone = ABMultiValueCreateMutable(kABPersonEmailProperty);

It's not ideal but works.


text:
Q: Nginx error log shows strange results Here's my Nginx config, in brief:
...

server {
    listen   80;
    server_name whatever;
    root /var/www/;

    location /api/1.0 {
        ...
        `proxy_pass http://localhost:8000/;
    }

    location /api/2.0 {
        ...
        proxy_pass http://localhost:8080/;
    }

    location / {
        root /var/www/static/;
        default_type text/html;
        try_files  $uri $uri/index.html index.html;
    }
}

If I now go to localhost, and append a random name that doesn't correspond to anything in my static files, or mean anything in either of two applications (e.g. http://localhost/whatever), I get a strange error in my log:

2013/09/14 20:58:20 [error] 28731#0: *2 open() "/var/wwwindex.html" failed (2: No such file or directory), client: 127.0.0.1, server: ec2-54-234-175-21.compute-1.amazonaws.com, request: "GET /whatever HTTP/1.1", host: "localhost"

I'm thinking this must just reflect my lack of understanding, because I really have no idea why nginx is trying to access "/var/wwwindex.html". Note that I don't want this request to succeed, I just want it to fail in a way I understand. What exactly is happening? Thoughts appreciated, thanks in advance!

A: Your try_files ends with index.html, which is appended to the root (and the trailing / on the root is ignored). Add a / to it.
        try_files  $uri $uri/index.html /index.html;