问:
How to unit test a "disk full" scenario with Ruby RSpec?
I need to unit test scenarios like the following:

The disk has 1MB free space. I try to copy 2MB of file(s) to the disk.

What's the best way to do this with Ruby RSpec?

For further information, I need to unit test the following file cache method, since it appears to have some issue:

```<code>def set first_key, second_key='', files=[]
  # If cache exists already, overwrite it.
  content_dir = get first_key, second_key
  second_key_file = nil

  begin
    if (content_dir.nil?)

      # Check the size of cache, and evict entries if too large
      check_cache_size if (rand(100) < check_size_percent)

      # Make sure cache dir doesn't exist already
      first_cache_dir = File.join(dir, first_key)
      if (File.exist?first_cache_dir)
        raise "BuildCache directory #{first_cache_dir} should be a directory" unless File.directory?(first_cache_dir)
      else
        FileUtils.mkpath(first_cache_dir)
      end
      num_second_dirs = Dir[first_cache_dir + '/*'].length
      cache_dir = File.join(first_cache_dir, num_second_dirs.to_s)
      # If cache directory already exists, then a directory must have been evicted here, so we pick another name
      while File.directory?cache_dir
        cache_dir = File.join(first_cache_dir, rand(num_second_dirs).to_s)
      end
      content_dir = File.join(cache_dir, '/content')
      FileUtils.mkpath(content_dir)

      # Create 'last_used' file
      last_used_filename = File.join(cache_dir, 'last_used')
      FileUtils.touch last_used_filename
      FileUtils.chmod(permissions, last_used_filename)

      # Copy second key
      second_key_file = File.open(cache_dir + '/second_key', 'w+')
      second_key_file.flock(File::LOCK_EX)
      second_key_file.write(second_key)

    else
      log "overwriting cache #{content_dir}"

      FileUtils.touch content_dir + '/../last_used'
      second_key_file = File.open(content_dir + '/../second_key', 'r')
      second_key_file.flock(File::LOCK_EX)
      # Clear any existing files out of cache directory
      FileUtils.rm_rf(content_dir + '/.')
    end

    # Copy files into content_dir
    files.each do |filename|
      FileUtils.cp(filename, content_dir)
    end
    FileUtils.chmod(permissions, Dir[content_dir + '/*'])

    # Release the lock
    second_key_file.close
    return content_dir
  rescue => e
    # Something went wrong, like a full disk or some other error.
    # Delete any work so we don't leave cache in corrupted state
    unless content_dir.nil?
      # Delete parent of content directory
      FileUtils.rm_rf(File.expand_path('..', content_dir))
    end
    log "ERROR: Could not set cache entry. #{e.to_s}"
    return 'ERROR: !NOT CACHED!'
  end

end
</code>```

答:
You could make use of any of the method calls you know are happening inside of the method you need to test, and stub them so they raise an error. E.g. FileUtils.touch is called a number of times, so we could do:

```<code>it 'handles file write error gracefully' do
  allow(FileUtils).to receive(:touch).and_raise('oh no')
  # your expectations
  # your test trigger
end
</code>```

Body:
I need to unit test scenarios like the following:

The disk has 1MB free space. I try to copy 2MB of file(s) to the disk.

What's the best way to do this with Ruby RSpec?

For further information, I need to unit test the following file cache method, since it appears to have some issue:

def set first_key, second_key='', files=[]
  # If cache exists already, overwrite it.
  content_dir = get first_key, second_key
  second_key_file = nil

  begin
    if (content_dir.nil?)

      # Check the size of cache, and evict entries if too large
      check_cache_size if (rand(100) < check_size_percent)

      # Make sure cache dir doesn't exist already
      first_cache_dir = File.join(dir, first_key)
      if (File.exist?first_cache_dir)
        raise "BuildCache directory #{first_cache_dir} should be a directory" unless File.directory?(first_cache_dir)
      else
        FileUtils.mkpath(first_cache_dir)
      end
      num_second_dirs = Dir[first_cache_dir + '/*'].length
      cache_dir = File.join(first_cache_dir, num_second_dirs.to_s)
      # If cache directory already exists, then a directory must have been evicted here, so we pick another name
      while File.directory?cache_dir
        cache_dir = File.join(first_cache_dir, rand(num_second_dirs).to_s)
      end
      content_dir = File.join(cache_dir, '/content')
      FileUtils.mkpath(content_dir)

      # Create 'last_used' file
      last_used_filename = File.join(cache_dir, 'last_used')
      FileUtils.touch last_used_filename
      FileUtils.chmod(permissions, last_used_filename)

      # Copy second key
      second_key_file = File.open(cache_dir + '/second_key', 'w+')
      second_key_file.flock(File::LOCK_EX)
      second_key_file.write(second_key)

    else
      log "overwriting cache #{content_dir}"

      FileUtils.touch content_dir + '/../last_used'
      second_key_file = File.open(content_dir + '/../second_key', 'r')
      second_key_file.flock(File::LOCK_EX)
      # Clear any existing files out of cache directory
      FileUtils.rm_rf(content_dir + '/.')
    end

    # Copy files into content_dir
    files.each do |filename|
      FileUtils.cp(filename, content_dir)
    end
    FileUtils.chmod(permissions, Dir[content_dir + '/*'])

    # Release the lock
    second_key_file.close
    return content_dir
  rescue => e
    # Something went wrong, like a full disk or some other error.
    # Delete any work so we don't leave cache in corrupted state
    unless content_dir.nil?
      # Delete parent of content directory
      FileUtils.rm_rf(File.expand_path('..', content_dir))
    end
    log "ERROR: Could not set cache entry. #{e.to_s}"
    return 'ERROR: !NOT CACHED!'
  end

end

Body:
You could make use of any of the method calls you know are happening inside of the method you need to test, and stub them so they raise an error. E.g. FileUtils.touch is called a number of times, so we could do:

it 'handles file write error gracefully' do
  allow(FileUtils).to receive(:touch).and_raise('oh no')
  # your expectations
  # your test trigger
end


来源: stackexchange

问:
Is it possible to create a node in alfresco with a specific NodeRef?
I'm currently using openCMIS to create a node inside Alfresco. I want to specify that the newly made content uses a specific nodeRef id. For example:

workspace://SpacesStore/6e619192-61c0-46fc-85c1-81badbb9b93e

Currently I have this CMIS code:

```<code>Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
properties.put(PropertyIds.NAME, "TestFolder");
properties.put(PropertyIds.OBJECT_ID, "workspace://SpacesStore/6e619192-61c0-46fc-85c1-81badbb9b93e");
folder.createFolder(properties);
</code>```

I want it that the newly made folder Names "TestFolder" has an nodeRef that matches the OBJECT_ID specified. However Alfresco still generates a different unique nodeRef.

Is there a way to specify a nodeRef when creating content in Alfresco?

答:
No, it is not possible to set your own node reference. It's an implementation detail that, in theory, you shouldn't care about.

However, you may have a valid reason for this (for example, importing data from an existing repository?). If for some reason you need to keep this node reference, consider storing this noderef as a separate metadata property.

You may want to submit a separate question explaining in more detail why you want to do something like this.

ContentLicense: CC BY-SA 3.0

Body:
I'm currently using openCMIS to create a node inside Alfresco. I want to specify that the newly made content uses a specific nodeRef id. For example:

workspace://SpacesStore/6e619192-61c0-46fc-85c1-81badbb9b93e

Currently I have this CMIS code:

Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
properties.put(PropertyIds.NAME, "TestFolder");
properties.put(PropertyIds.OBJECT_ID, "workspace://SpacesStore/6e619192-61c0-46fc-85c1-81badbb9b93e");
folder.createFolder(properties);

I want it that the newly made folder Names "TestFolder" has an nodeRef that matches the OBJECT_ID specified. However Alfresco still generates a different unique nodeRef.

Is there a way to specify a nodeRef when creating content in Alfresco?


问:
Android Studio app crashes on real device, but works on emulator
I started using Android Studio a few weeks ago. I've worked on an app with a normal login screen and on the emulator everything works fine. But if I try to run the app on my Samsung Galaxy S7 Edge (Android 7.0) the app crashes instantly.

I've emulated an Nexus 5 with API 23, when I try it with an emulated Pixel with API 24 the emulator also crashes. So I guess the problem depends on the Android version?

Logcat (I tinified all images I am using, now this is my new Logcat):

```<code>03-30 15:53:13.841 31645-31645/de.mm.uchron E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: de.mm.uchron, PID: 31645
                                                                      java.lang.OutOfMemoryError: Failed to allocate a 3686412 byte allocation with 2474312 free bytes and 2MB until OOM
                                                                          at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                                          at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                                          at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:700)
                                                                          at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:535)
                                                                          at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1179)
                                                                          at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:770)
                                                                          at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:621)
                                                                          at android.content.res.Resources.loadDrawable(Resources.java:1727)
                                                                          at android.content.res.TypedArray.getDrawable(TypedArray.java:945)
                                                                          at android.widget.ImageView.<init>(ImageView.java:157)
                                                                          at android.widget.ImageButton.<init>(ImageButton.java:85)
                                                                          at android.widget.ImageButton.<init>(ImageButton.java:81)
                                                                          at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:60)
                                                                          at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:56)
                                                                          at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:118)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                                          at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:865)
                                                                          at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:525)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:378)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                          at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                          at de.mm.uchron.LoginActivity.onCreate(LoginActivity.java:32)
                                                                          at android.app.Activity.performCreate(Activity.java:6912)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
                                                                          at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6688)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
03-30 15:53:20.016 31645-31656/de.mm.uchron I/art: Clamp target GC heap from 261MB to 256MB
</code>```

I've also tried it with my another real device (Samsung GT-I9300 with Android 5.1.1, API 22). The MainActivity loads, but without the background image and if I try to login, the app crashes.

My SDK Tools have all the newest version

```<code>Android Emulator: 26.0.0
Android SDK Platform-Tools: 25.0.4
Android SDK Tools: 26.0.0
Google Play services, rev 39: 39.0.0
Google USB Driver, rev 11: 11.0.0
Google Web driver: 2
Intel x86 Emulator Accelerator (HAXM installer): 6.0.5
</code>```

xml file for the MainActivity (LoginActivity):

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:background="@drawable/loginbg">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:id="@+id/rect"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

    </LinearLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/signup_input_layout_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="300dp"
        android:layout_marginLeft="30dp">

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="222dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:textColor="#000"
        android:fontFamily="Montserrat"
        android:textSize="16dp"
        android:hint="BENUTZERNAME" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/signup_input_layout_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_below="@id/signup_input_layout_name">

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="223dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:fontFamily="Montserrat"
            android:hint="PASSWORT"
            android:inputType="textPassword"
            android:textColor="#000"
            android:textSize="16dp" />
    </android.support.design.widget.TextInputLayout>

    <ImageButton
        android:id="@+id/bSignIn"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:background="@null"
        android:layout_marginBottom="60dp"
        android:layout_marginLeft="260dp"
        android:fontFamily="Montserrat"
        android:scaleType="fitXY"
        android:src="@drawable/loginbutton"
        android:text="Login" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="NEUER ACCOUNT"
        android:id="@+id/tvRegisterLink"
        android:textSize="12sp"
        android:textColor="#B2B2B2"
        android:fontFamily="Montserrat"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_alignStart="@+id/signup_input_layout_pass" />

</RelativeLayout>
</code>```

Like I said I am new to Android Studio and I become exasperated with this problem.

Thanks in advance!

Solved: Resizing the images solved the problem. I used the suggestions from this link to reduce the resolution of my background files. Now everything works like a charm!

答:
Agree with Dod answer but I want to extend it a bit.
If you don't need transparency, use JPG and when you create Bitmaps, choose option which do not require transparencies and even lesser bit count.</p>

Body:
I started using Android Studio a few weeks ago. I've worked on an app with a normal login screen and on the emulator everything works fine. But if I try to run the app on my Samsung Galaxy S7 Edge (Android 7.0) the app crashes instantly.

I've emulated an Nexus 5 with API 23, when I try it with an emulated Pixel with API 24 the emulator also crashes. So I guess the problem depends on the Android version?

Logcat (I tinified all images I am using, now this is my new Logcat):

03-30 15:53:13.841 31645-31645/de.mm.uchron E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: de.mm.uchron, PID: 31645
                                                                      java.lang.OutOfMemoryError: Failed to allocate a 3686412 byte allocation with 2474312 free bytes and 2MB until OOM
                                                                          at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                                          at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                                          at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:700)
                                                                          at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:535)
                                                                          at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1179)
                                                                          at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:770)
                                                                          at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:621)
                                                                          at android.content.res.Resources.loadDrawable(Resources.java:1727)
                                                                          at android.content.res.TypedArray.getDrawable(TypedArray.java:945)
                                                                          at android.widget.ImageView.<init>(ImageView.java:157)
                                                                          at android.widget.ImageButton.<init>(ImageButton.java:85)
                                                                          at android.widget.ImageButton.<init>(ImageButton.java:81)
                                                                          at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:60)
                                                                          at android.support.v7.widget.AppCompatImageButton.<init>(AppCompatImageButton.java:56)
                                                                          at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:118)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                                          at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:865)
                                                                          at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:525)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
                                                                          at android.view.LayoutInflater.inflate(LayoutInflater.java:378)
                                                                          at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                          at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                          at de.mm.uchron.LoginActivity.onCreate(LoginActivity.java:32)
                                                                          at android.app.Activity.performCreate(Activity.java:6912)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
                                                                          at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1650)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6688)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
03-30 15:53:20.016 31645-31656/de.mm.uchron I/art: Clamp target GC heap from 261MB to 256MB

I've also tried it with my another real device (Samsung GT-I9300 with Android 5.1.1, API 22). The MainActivity loads, but without the background image and if I try to login, the app crashes.

My SDK Tools have all the newest version

Android Emulator: 26.0.0
Android SDK Platform-Tools: 25.0.4
Android SDK Tools: 26.0.0
Google Play services, rev 39: 39.0.0
Google USB Driver, rev 11: 11.0.0
Google Web driver: 2
Intel x86 Emulator Accelerator (HAXM installer): 6.0.5

xml file for the MainActivity (LoginActivity):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:background="@drawable/loginbg">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:id="@+id/rect"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true">

    </LinearLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/signup_input_layout_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="300dp"
        android:layout_marginLeft="30dp">

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="222dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:textColor="#000"
        android:fontFamily="Montserrat"
        android:textSize="16dp"
        android:hint="BENUTZERNAME" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/signup_input_layout_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_below="@id/signup_input_layout_name">

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="223dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:fontFamily="Montserrat"
            android:hint="PASSWORT"
            android:inputType="textPassword"
            android:textColor="#000"
            android:textSize="16dp" />
    </android.support.design.widget.TextInputLayout>

    <ImageButton
        android:id="@+id/bSignIn"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:background="@null"
        android:layout_marginBottom="60dp"
        android:layout_marginLeft="260dp"
        android:fontFamily="Montserrat"
        android:scaleType="fitXY"
        android:src="@drawable/loginbutton"
        android:text="Login" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="NEUER ACCOUNT"
        android:id="@+id/tvRegisterLink"
        android:textSize="12sp"
        android:textColor="#B2B2B2"
        android:fontFamily="Montserrat"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_alignStart="@+id/signup_input_layout_pass" />

</RelativeLayout>

Like I said I am new to Android Studio and I become exasperated with this problem.

Thanks in advance!

Solved: Resizing the images solved the problem. I used the suggestions from this link to reduce the resolution of my background files. Now everything works like a charm!


问:
What is the difference between service and server?
It seems that both service and server refer to some web based application. But is there any precise definition of the two terms?</p>

答:
a server is a piece of hardware or on a virtual machine

a service is a process that provides services normally over the network and runs on a server

but a server can also refer to a web server which is actual a service but it's sort of like one as it hosts services

i think those are reasonable working definitions

ContentLicense: CC BY-SA 2.5


问:
Javascript - How do I find out which condition(s) triggered?
Let's say I have the following statement:

```<code>if (height > 4.25 || length > 6 || weight > 1) {
  //Do Something
}
</code>```

Is there a way to tell which of the conditions was met in order for that statement to be true?

Something more elegant than below, which is obviously redundant:

```<code>if (height > 4.25 || length > 6 || weight > 1) {
  if (height > 4.25){...};
  if (length > 6){...};
  if (weight > 1){...};
}
</code>```

答:
Not possible!

You will have to check each option in a separate condition:

```<code>if (height > 4.25 || length > 6 || weight > 1) {

 if(height > 4.25){
  return true;
 }

 if(length > 6){
  return true;
 }

 if (weight > 1){
  return true;
 };

}
</code>```

And even then you won't know if when height was bigger than 4.25 length wasn't bigger than 6, to know these you will have to go over all the possible combinations:

```<code> if (height > 4.25 || length > 6 || weight > 1) {

     if(height > 4.25 && length > 6 &&  weight > 1){
      return true;
     }

     if(height > 4.25 && length > 6){
      return true;
     }

       //and so on...

    }
</code>```

Body:
Let's say I have the following statement:

if (height > 4.25 || length > 6 || weight > 1) {
  //Do Something
}

Is there a way to tell which of the conditions was met in order for that statement to be true?

Something more elegant than below, which is obviously redundant:

if (height > 4.25 || length > 6 || weight > 1) {
  if (height > 4.25){...};
  if (length > 6){...};
  if (weight > 1){...};
}

Body:
Not possible!

You will have to check each option in a separate condition:

if (height > 4.25 || length > 6 || weight > 1) {

 if(height > 4.25){
  return true;
 }

 if(length > 6){
  return true;
 }

 if (weight > 1){
  return true;
 };

}

And even then you won't know if when height was bigger than 4.25 length wasn't bigger than 6, to know these you will have to go over all the possible combinations:

 if (height > 4.25 || length > 6 || weight > 1) {

     if(height > 4.25 && length > 6 &&  weight > 1){
      return true;
     }

     if(height > 4.25 && length > 6){
      return true;
     }

       //and so on...

    }


问:
WCF with basicHttpBinding, encryption, signing and usernameToken over HTTP
I'm trying to configure WCF client to generate proper request.
In that request I need security header with usernameToken.
Also, I need to encrypt and sign request.
All this is communicated via plain HTTP.

So far, I have managed to make client sign and encrypt message.
Now I need to somehow incorporate usernameToken into this security header.

How can I do this?

I'm using basicHttpBinding, with security mode set to "Message" and clientCredentialType = "Certificate" for message.

I stumbled upon clearUsernameToken binding library but I see no way of incorporating all of this (usernameToken, sign and encrypt) into one client, and all that over HTTP.

Is this even possible?

答:
I have managed to do this with WSE 3.0.

Now in my SOAP request I have UsernameToken, BinarySecurityToken, digital signature and encryption. Of course, I had to do some custom WSE filters, but it wasn't that hard.

For me it's strange that this was easier to achieve in older framework like WSE, then by using WCF.


问:
c# most efficient way to extract non-overlapping sorted ranges
In order to highlight multiple search text elements in a single string, I have a routine computing the ranges to be highlighted within the string itself.

For example, if I search his+is string in string "this is my misk test" I get higlighted ranges [1,3], [2,3], [5,6], and [12,13].

So my desired result here would be [1,3], [5,6], and [12,13].

Is there a general way to extract non-overlapping ranges from the above list? Or event better, is there a string-specific way to get those?

答:
What do you understand by efficient? Fast? Least memory usage? Mantainable code?

There are tons of ways you could solve this, some of them can entail seemingly a lot of code but maybe thats not bad. For example, consider the following approach:

```<code>public struct Interval<T> where T: IComparable<T>
{
    public T LowerBound { get; }
    public T UpperBound { get; }

    public Interval(T lowerBound, T upperBound)
    {
        Debug.Assert(upperBound.CompareTo(lowerBound) > 0);
        LowerBound = lowerBound;
        UpperBound = upperBound;
    }

    public static bool AreOverlapping(Interval<T> first, Interval<T> second) =>
        first.UpperBound.CompareTo(second.LowerBound) > 0 &&
        second.UpperBound.CompareTo(first.LowerBound) > 0;

    public static Interval<T> Union(Interval<T> first, Interval<T> second)
    {
        Debug.Assert(AreOverlapping(first, second));
        return new Interval<T>(Min(first.LowerBound, second.LowerBound),
                               Max(first.UpperBound, second.UpperBound));
    }

    public override string ToString() => $"[{LowerBound}, {UpperBound}]";

    private static T Min(T t1, T t2)
    {
        if (t1.CompareTo(t2) <= 0)
            return t1;

        return t2;
    }

    private static T Max(T t1, T t2)
    {
        if (t1.CompareTo(t2) >= 0)
            return t1;

        return t2;
    }
}
</code>```

And now, our method to extract non-overlapping intervals would be:

```<code>public static IEnumerable<Interval<T>> GetOverlappingIntervals<T>(this IEnumerable<Interval<T>> intervals)
    where T : IComparable<T>
{
    var stack = new Stack<Interval<T>>();

    foreach (var interval in intervals.OrderBy(i => i.LowerBound))
    {
        if (stack.Count == 0)
        {
            stack.Push(interval);
        }
        else
        {
            var previous = stack.Peek();

            if (Interval<T>.AreOverlapping(interval, previous))
            {
                stack.Pop();
                stack.Push(Interval<T>.Union(interval, previous));
            }
            else
            {
                stack.Push(interval);
            }
        }
    }

    return stack;
}
</code>```

Note that this solution will not perform the union of adjacent intervals, not sure if this is what you want.

Is this solution mantainable? Yes, the code is pretty much self explanatory. Is it the most efficient? Well, probably not, but who cares if its "efficient" enough and it meets your performance goals. If it doesn't, then do start optimizing it.

Body:
What do you understand by efficient? Fast? Least memory usage? Mantainable code?

There are tons of ways you could solve this, some of them can entail seemingly a lot of code but maybe thats not bad. For example, consider the following approach:

public struct Interval<T> where T: IComparable<T>
{
    public T LowerBound { get; }
    public T UpperBound { get; }

    public Interval(T lowerBound, T upperBound)
    {
        Debug.Assert(upperBound.CompareTo(lowerBound) > 0);
        LowerBound = lowerBound;
        UpperBound = upperBound;
    }

    public static bool AreOverlapping(Interval<T> first, Interval<T> second) =>
        first.UpperBound.CompareTo(second.LowerBound) > 0 &&
        second.UpperBound.CompareTo(first.LowerBound) > 0;

    public static Interval<T> Union(Interval<T> first, Interval<T> second)
    {
        Debug.Assert(AreOverlapping(first, second));
        return new Interval<T>(Min(first.LowerBound, second.LowerBound),
                               Max(first.UpperBound, second.UpperBound));
    }

    public override string ToString() => $"[{LowerBound}, {UpperBound}]";

    private static T Min(T t1, T t2)
    {
        if (t1.CompareTo(t2) <= 0)
            return t1;

        return t2;
    }

    private static T Max(T t1, T t2)
    {
        if (t1.CompareTo(t2) >= 0)
            return t1;

        return t2;
    }
}

And now, our method to extract non-overlapping intervals would be:

public static IEnumerable<Interval<T>> GetOverlappingIntervals<T>(this IEnumerable<Interval<T>> intervals)
    where T : IComparable<T>
{
    var stack = new Stack<Interval<T>>();

    foreach (var interval in intervals.OrderBy(i => i.LowerBound))
    {
        if (stack.Count == 0)
        {
            stack.Push(interval);
        }
        else
        {
            var previous = stack.Peek();

            if (Interval<T>.AreOverlapping(interval, previous))
            {
                stack.Pop();
                stack.Push(Interval<T>.Union(interval, previous));
            }
            else
            {
                stack.Push(interval);
            }
        }
    }

    return stack;
}

Note that this solution will not perform the union of adjacent intervals, not sure if this is what you want.

Is this solution mantainable? Yes, the code is pretty much self explanatory. Is it the most efficient? Well, probably not, but who cares if its "efficient" enough and it meets your performance goals. If it doesn't, then do start optimizing it.


问:
How should I organize the contents of my CSS file(s)?
This question is about organizing the actual CSS directives themselves within a .css file.  When developing a new page or set of pages, I usually just add directives by hand to the .css file, trying to refactor when I can.  After some time, I have hundreds (or thousands) of lines and it can get difficult to find what I need when tweaking the layout.

Does anyone have advice for how to organize the directives?

Should I try to organize top-down, mimicking the DOM?

Should I organize functionally, putting directives for elements that support the same parts of the UI together?

Should I just sort everything alphabetically by selector?

Some combination of these approaches?

Also, is there a limit to how much CSS I should keep in one file before it might be a good idea to break it off into separate files?  Say, 1000 lines?  Or is it always a good idea to keep the whole thing in one place?

Related Question: What's the best way to organize CSS rules?

答:
ITCSS

By Harry Roberts (CSS Wizardry)

Defines global namespace and cascade, and helps keep selectors specificity low.

Structure

The first two only apply if you are using a preprocessor.

(Settings)

(Tools)

Generics

Elements

Objects

Components

Trumps

OwnerDisplayName: Adam Bellaire

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Adam Bellaire


问:
Jenkins pipeline share information between jobs
We are trying to define a set of jobs on Jenkins that will do really specific actions. JobA1 will build maven project, while JobA2 will build .NET code, JobB will upload it to Artifactory, JobC will download it from Artifactory and JobD will deploy it.
Every job will have a set of parameters so we can reuse the same job for any product (around 100).

The idea behind this is to create black boxes, I call a job with some input and I get always some output, whatever happens between is something that I don't care. On the other side, this allows us to improve each job separately, adding the required complexity, and instantly all products will get benefit.

We want to use Jenkins Pipeline to orchestrate the execution of actions. We are going to have a pipeline per environment/usage.

PipelineA will call JobA1, then JobB to upload to artifactory.

PipelineB will download package JobC and then deploy to staging.

PipelineC will download package JobC and then deploy to production based on some internal validations.

I have tried to get some variables from JobA1 (POM basic stuff such as ArtifactID or Version) injected to JobB but the information seems not to be transfered.
Same happens while downloading files, I call JobC but the file is in the job workspace not available for any other and I'm afraid that"External Workspace Manager" plugin adds too much complexity.

Is there any way rather than share the workspace to achieve my purpose? I understand that share the workspace will make it impossible to run two pipelines at the same time
Am I following the right path or am I doing something weird?

答: You could use the Pipelines shared groovy libraries plugin. Have a look at its documentation to implement libraries that multiple pipelines share and define shared global variables.</p>


问:
Logo center at navbar bootstrap with 2 button left and right
I create navbar with navbar boostrap 3, I insert logo and 2 button at left and right but I need to fix when screen mobile logo align to center with 2 button

Here My code right now, I create for wordpress

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2" aria-expanded="false" style="float: left;">
        Toggle navigation

      </button>
      <img class="img-responsive" src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />

      <form class="navbar-form navbar-right">

          <input type="text" class="form-control" placeholder="Search">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>

Link

Link

Link

```

How to make logo align to center when screen on mobile screen.

Thank you

答:
You can try something like this--

Example snippet

@media (max-width:767px){
.navbar-brand {
    position: absolute;
    width: 50%;

    text-align: center;

}
#logo {
   height: 40px;
   margin-left: 80%;

   margin-top: -10px;
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
          <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
        <img id="logo" class="img-responsive" src="https://www.w3schools.com/css/trolltunga.jpg" alt="" />
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2" aria-expanded="false" style="float: left;">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>

    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <form class="navbar-form navbar-right">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div><!-- /.navbar-collapse -->

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-2">
      <ul class="nav navbar-nav navbar-right">
        <li>Link</li>
        <li>Link</li>
        <li>Link</li>
      </ul>
    </div><!-- /.navbar-collapse -->

  </div><!-- /.container-fluid -->
</nav></code>```

Body:
I create navbar with navbar boostrap 3, I insert logo and 2 button at left and right but I need to fix when screen mobile logo align to center with 2 button

Here My code right now, I create for wordpress

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2" aria-expanded="false" style="float: left;">
        Toggle navigation

      </button>
      <img class="img-responsive" src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />

      <form class="navbar-form navbar-right">

          <input type="text" class="form-control" placeholder="Search">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>

Link

Link

Link

How to make logo align to center when screen on mobile screen.

Thank you

Body:
You can try something like this--

Example snippet

@media (max-width:767px){
.navbar-brand {
    position: absolute;
    width: 50%;

    text-align: center;

}
#logo {
   height: 40px;
   margin-left: 80%;

   margin-top: -10px;
}
}

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
          <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<nav class="navbar navbar-default">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
       <a class="navbar-brand" href=""> <img id="logo" class="img-responsive" src="https://www.w3schools.com/css/trolltunga.jpg" alt="" /></a>
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2" aria-expanded="false" style="float: left;">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>

    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <form class="navbar-form navbar-right">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div><!-- /.navbar-collapse -->

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-2">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->

  </div><!-- /.container-fluid -->
</nav>


问:
Create normal zip file programmatically
I have seen many tutorials on how to compress a single file in c#. But I need to be able to create a normal *.zip file out of more than just one file. Is there anything in .NET that can do this? What would you suggest (baring in mind I'm under strict rules and cannot use other libraries)

Thank you

答:
This can be done by adding a reference to System.IO.Compression and System.IO.Compression.Filesystem.

A sample createZipFile() method may look as following:

```<code>public static void createZipFile(string inputfile, string outputfile, CompressionLevel compressionlevel)
        {
            try
            {
                using (ZipArchive za = ZipFile.Open(outputfile, ZipArchiveMode.Update))
                {
                    //using the same file name as entry name
                    za.CreateEntryFromFile(inputfile, inputfile);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid input/output file.");
                Environment.Exit(-1);
            }
}
</code>```

where

inputfile= string with the file name to be compressed (for this
example, you have to add the extension)

outputfile= string with the destination zip file name

More details about ZipFile Class in MSDN

Title: Create normal zip file programmatically

Body:
This can be done by adding a reference to System.IO.Compression and System.IO.Compression.Filesystem.

A sample createZipFile() method may look as following:

public static void createZipFile(string inputfile, string outputfile, CompressionLevel compressionlevel)
        {
            try
            {
                using (ZipArchive za = ZipFile.Open(outputfile, ZipArchiveMode.Update))
                {
                    //using the same file name as entry name
                    za.CreateEntryFromFile(inputfile, inputfile);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid input/output file.");
                Environment.Exit(-1);
            }
}

where

inputfile= string with the file name to be compressed (for this
example, you have to add the extension)

outputfile= string with the destination zip file name

More details about ZipFile Class in MSDN


问:
Copy and paste rows from one WB to another, with different WB names weekly
So I am trying to copy data from one WB that I filter, and paste it into another WB at the bottom of the previous rows.

I run this report every Friday, and pull data 1 day at a time for the past 7 days. The names of the source WB will change for each day I pull and looks something like this: 20170323050000 for Thursday, March 23.

The name of the destination WB will change each week as such: WK12, WK13, WK14, etc.

Is there a macro that I wouldn't have to change each week when running my report again?

Updated

So I played around a little bit and this does pretty much exactly what I need BUT I still go back to the last part of the original question, is there something I can do to get around changing the " Windows(WK13 RIP.xlsm").Activate " to WK14, WK15, WK16, etc. every week that I do this?

```<code>Sub PackFilterl()

Range("A1").AutoFilter Field:=15, Criteria1:="EACH"

Range("A1").AutoFilter Field:=16, Criteria1:="Total"

Dim rng As Range
    Set rng = ActiveSheet.UsedRange

    Set rng = rng.Offset(1).Resize(rng.Rows.Count - 1)

    rng.Select
    rng.Copy
        Windows("WK13 RIP.xlsm").Activate
        Sheets("AFE Pack Volume").Select
            lMaxRows = Cells(Rows.Count, "A").End(xlUp).Row
            Range("A" & lMaxRows + 1).Select

ActiveSheet.Paste
</code>```

End Sub

答:
I think this is what you're looking for with one caveat.  You say you scroll to the bottom of the destination workbook to paste the copied range, but I don't have any way of knowing where the bottom is so I just set the target to A1.  You could add another line with and InputBox() call for the destination range, or write some code to figure out where the bottom is. The code below also assumes that the destination workbook is NOT already open.</p>

```<code>Sub PackFilterl()

    Dim WkShtNum As Integer
    Dim WkBkName As String
    Dim DestinationWorkbook As Excel.Workbook
    Dim DestinationWorksheet As Excel.Worksheet
    Dim rng As Range

    WkBkName = InputBox("Enter the Path of your destination Workbook")
    WkShtNum = InputBox("Enter the week number for the destination worksheet")

    Range("A1").AutoFilter Field:=15, Criteria1:="EACH"

    Range("A1").AutoFilter Field:=16, Criteria1:="Total"

    Set rng = ActiveSheet.UsedRange

    Set rng = rng.Offset(1).Resize(rng.Rows.Count - 1)

    rng.Select
    rng.Copy

    Set DestinationWorkbook = Workbooks.Open(WkBkName)
    Set DestinationWorksheet = DestinationWorkbook.Worksheets("WK" & CStr(WkShtNum))
    Set rng = DestinationWorksheet.Range("A1")
    rng.PasteSpecial (xlPasteValues)

End Sub
</code>```

Body:
So I am trying to copy data from one WB that I filter, and paste it into another WB at the bottom of the previous rows.

I run this report every Friday, and pull data 1 day at a time for the past 7 days. The names of the source WB will change for each day I pull and looks something like this: 20170323050000 for Thursday, March 23.

The name of the destination WB will change each week as such: WK12, WK13, WK14, etc.

Is there a macro that I wouldn't have to change each week when running my report again?

Updated

So I played around a little bit and this does pretty much exactly what I need BUT I still go back to the last part of the original question, is there something I can do to get around changing the " Windows(WK13 RIP.xlsm").Activate " to WK14, WK15, WK16, etc. every week that I do this?

Sub PackFilterl()

Range("A1").AutoFilter Field:=15, Criteria1:="EACH"

Range("A1").AutoFilter Field:=16, Criteria1:="Total"

Dim rng As Range
    Set rng = ActiveSheet.UsedRange

    Set rng = rng.Offset(1).Resize(rng.Rows.Count - 1)

    rng.Select
    rng.Copy
        Windows("WK13 RIP.xlsm").Activate
        Sheets("AFE Pack Volume").Select
            lMaxRows = Cells(Rows.Count, "A").End(xlUp).Row
            Range("A" & lMaxRows + 1).Select

ActiveSheet.Paste

End Sub

Body:
I think this is what you're looking for with one caveat.  You say you scroll to the bottom of the destination workbook to paste the copied range, but I don't have any way of knowing where the bottom is so I just set the target to A1.  You could add another line with and InputBox() call for the destination range, or write some code to figure out where the bottom is. The code below also assumes that the destination workbook is NOT already open.

Sub PackFilterl()

    Dim WkShtNum As Integer
    Dim WkBkName As String
    Dim DestinationWorkbook As Excel.Workbook
    Dim DestinationWorksheet As Excel.Worksheet
    Dim rng As Range

    WkBkName = InputBox("Enter the Path of your destination Workbook")
    WkShtNum = InputBox("Enter the week number for the destination worksheet")

    Range("A1").AutoFilter Field:=15, Criteria1:="EACH"

    Range("A1").AutoFilter Field:=16, Criteria1:="Total"

    Set rng = ActiveSheet.UsedRange

    Set rng = rng.Offset(1).Resize(rng.Rows.Count - 1)

    rng.Select
    rng.Copy

    Set DestinationWorkbook = Workbooks.Open(WkBkName)
    Set DestinationWorksheet = DestinationWorkbook.Worksheets("WK" & CStr(WkShtNum))
    Set rng = DestinationWorksheet.Range("A1")
    rng.PasteSpecial (xlPasteValues)

End Sub


问:
What is the default default value of a dependency property?
A WPF dependency property can be given a default value by passing a PropertyMetadata with the default value to the Register function:

```<code> public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(double), typeof(MyControl),
        new PropertyMetadata(0.0));
</code>```

What is the default value for the dependency property if no default value is specified, either by not passing a PropertyMetadata or by using a PropertyMetadata constructor which doesn't specify a default value?

This page says

(For cases where a property registration does not specify metadata, a default PropertyMetadata is created with default values for that class.)

but I haven't found anywhere that describes what these default values are.

答:
What is the default value for the dependency property if no default value is specified, either by not passing a PropertyMetadata or by using a PropertyMetadata constructor which doesn't specify a default value?

The default value is the default value of the type of the dependency property, i.e. for a double dependency property it is 0.0 (or default(double)).

You can easily confirm this yourself by creating an instance of your class and access the getter of CLR wrapper of the dependency property:

```<code>MyControl ctrl = new MyControl();
var x = ctrl.MyProperty; // = 0
</code>```

Body:
A WPF dependency property can be given a default value by passing a PropertyMetadata with the default value to the Register function:

 public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(double), typeof(MyControl),
        new PropertyMetadata(0.0));

What is the default value for the dependency property if no default value is specified, either by not passing a PropertyMetadata or by using a PropertyMetadata constructor which doesn't specify a default value?

This page says

(For cases where a property registration does not specify metadata, a default PropertyMetadata is created with default values for that class.)

but I haven't found anywhere that describes what these default values are.

Body:
What is the default value for the dependency property if no default value is specified, either by not passing a PropertyMetadata or by using a PropertyMetadata constructor which doesn't specify a default value?

The default value is the default value of the type of the dependency property, i.e. for a double dependency property it is 0.0 (or default(double)).

You can easily confirm this yourself by creating an instance of your class and access the getter of CLR wrapper of the dependency property:

MyControl ctrl = new MyControl();
var x = ctrl.MyProperty; // = 0


问:
Handling string search and substitution in R
I am a beginner in R, used Matlab before and I have been searching around for a solution to my problem but I do not appear to find one.
I have a very large vector with text entries. Something like

CAT06
6CAT
CAT 6
DOG3
3DOG

I would like to be able to find a function such that: If an entry is found and it contains "CAT" & "6" (no matter position), substitute cat6. If an entry is found and it contains "DOG" & "3" (no matter position) substitute dog3. So the outcome should be:

cat6 cat6 cat6 dog3 dog3

Can anybody help on this? Thank you very much, find myself a bit lost!

答:
First remove blank spaces i.e. elements like "CAT 6" to "CAT6":

```<code>sp = gsub(" ", "", c("CAT06", "6CAT", "CAT 6", "DOG3", "3DOG"))
</code>```

Then use some regex magic to find any combination of "CAT", "0", "6" and replace these matches with "cat6" as follows:

```<code>sp = gsub("^(?:CAT|0|6)*$", "cat6", sp)
</code>```

Same here with DOG case:

```<code>sp = gsub("^(?:DOG|0|3)*$", "dog3", sp)
</code>```

Body:
First remove blank spaces i.e. elements like "CAT 6" to "CAT6":

sp = gsub(" ", "", c("CAT06", "6CAT", "CAT 6", "DOG3", "3DOG"))

Then use some regex magic to find any combination of "CAT", "0", "6" and replace these matches with "cat6" as follows:

sp = gsub("^(?:CAT|0|6)*$", "cat6", sp)

Same here with DOG case:

sp = gsub("^(?:DOG|0|3)*$", "dog3", sp)


问:
react routing is able to handle different url path but tomcat returns 404 not available resources
I have a little project in reactjs to play with and learn it. I need to have to type of headers which will be shown based on url paths. So the following is my index.js which handles the routing:

```<code> const history = useRouterHistory(createHistory)({
     basename: '/test'
})
class Tj extends React.Component {

render() {

    return (
        <Router history={history}>
            <Route path={"/"} component={Bridge} >
                <IndexRoute component={Home} />
                <Route path={"user"} component={T} />
                <Route path={"home"} component={Home} />
            </Route>
            <Route path={"/t/"} component={Bridge2} >
                <IndexRoute component={T} />
                <Route path={"contact"} component={Home} />
            </Route>
        </Router>
    );
}
}
render(
<Provider store={store}>
    <Tj/>
</Provider>,
window.document.getElementById('mainContainer'));
</code>```

As you can see I am using test as a root directory and based on user's input for url I decide which header should I use. Also here is Bridge2.js:

```<code>export class Bridge2 extends React.Component {
render() {

    return (
        <div>
            <div className="row">
                <Header2/>
            </div>
            <div className="row">
                {this.props.children}
            </div>
        </div>
    );
}
}
</code>```

and Bridge.js:

```<code>export class Bridge extends React.Component {
render() {
  //  alert(this.props.children.type);
    var Content;

    if(this.props.children.type){
    Content=<div>
        <div className="row">
            <Header/>
        </div>
        <div className="row">
            {this.props.children}
        </div>
    </div>;
    }
    else{
        Content=<div>
            <div className="row">
                <Header/>
            </div>
            <div className="row">
                {this.props.children}
            </div>
        </div>;
    }
    return (
        Content
    );
}
}
</code>```

When I run this in webpack dev server every thing works fine. For instance when I use http://localhost:3003/test/ bridge.js is loaded and if I run http://localhost:3003/test/t/ bridge2.js is loaded which is expected.

However since web pack dev server is not a production server I use tomcat and for now I use the eclipse web application project and I copied my bundle.js file and index.html over there. Now the problem is when I run the tomcat server it is able to recognize and show this path fine:

http://localhost:8080/test/ but when for http://localhost:8080/test/t/ I get:

HTTP Status 404 - /test/t/

which basically says the resource file is not available. As far as what I observe this is not a problem in coding since routing works fine in web pack dev server but when it comes to tomcat it seems that react routing is not able to handle it. Is there anything wrong with what I am doing? Is doable this way at all?

答:
My solution is like a workaround for JSP engines (e.g. Tomcat), but it works great with minimal code.

I created an "index.jsp" parallel to "index.html" (in the content root folder) with following code:

index.jsp

```<code><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="index.html"%>
</code>```

I configured all urls to redirect to this JSP in web.xml

web.xml

```<code><servlet>
    <servlet-name>index</servlet-name>
    <jsp-file>index.jsp</jsp-file>
</servlet>
<servlet-mapping>
    <servlet-name>index</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</code>```

Now any URL requested to Tomcat will internally get redirected to index.jsp that is effectively index.html. Once react-router loads in browser, it takes care of rendering the right component and subsequent requests.

Body:
I have a little project in reactjs to play with and learn it. I need to have to type of headers which will be shown based on url paths. So the following is my index.js which handles the routing:

 const history = useRouterHistory(createHistory)({
     basename: '/test'
})
class Tj extends React.Component {

render() {

    return (
        <Router history={history}>
            <Route path={"/"} component={Bridge} >
                <IndexRoute component={Home} />
                <Route path={"user"} component={T} />
                <Route path={"home"} component={Home} />
            </Route>
            <Route path={"/t/"} component={Bridge2} >
                <IndexRoute component={T} />
                <Route path={"contact"} component={Home} />
            </Route>
        </Router>
    );
}
}
render(
<Provider store={store}>
    <Tj/>
</Provider>,
window.document.getElementById('mainContainer'));

As you can see I am using test as a root directory and based on user's input for url I decide which header should I use. Also here is Bridge2.js:

export class Bridge2 extends React.Component {
render() {

    return (

                <Header2/>

                {this.props.children}

    );
}
}

and Bridge.js:

export class Bridge extends React.Component {
render() {
  //  alert(this.props.children.type);
    var Content;

    if(this.props.children.type){
    Content=

            {this.props.children}

;
    }
    else{
        Content=

                {this.props.children}

;
    }
    return (
        Content
    );
}
}

When I run this in webpack dev server every thing works fine. For instance when I use http://localhost:3003/test/ bridge.js is loaded and if I run http://localhost:3003/test/t/ bridge2.js is loaded which is expected.

However since web pack dev server is not a production server I use tomcat and for now I use the eclipse web application project and I copied my bundle.js file and index.html over there. Now the problem is when I run the tomcat server it is able to recognize and show this path fine:

http://localhost:8080/test/ but when for http://localhost:8080/test/t/ I get:

HTTP Status 404 - /test/t/

which basically says the resource file is not available. As far as what I observe this is not a problem in coding since routing works fine in web pack dev server but when it comes to tomcat it seems that react routing is not able to handle it. Is there anything wrong with what I am doing? Is doable this way at all?

Body:
My solution is like a workaround for JSP engines (e.g. Tomcat), but it works great with minimal code.

I created an "index.jsp" parallel to "index.html" (in the content root folder) with following code:

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="index.html"%>

I configured all urls to redirect to this JSP in web.xml

web.xml

<servlet>
    <servlet-name>index</servlet-name>
    <jsp-file>index.jsp</jsp-file>
</servlet>
<servlet-mapping>
    <servlet-name>index</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

Now any URL requested to Tomcat will internally get redirected to index.jsp that is effectively index.html. Once react-router loads in browser, it takes care of rendering the right component and subsequent requests.


问:
OpenSSH server rejected connection
In BitBucket I have my SSH key:

In SourceTree I have:

When I try to clone I get:

I did some googling around and came across this post https://confluence.atlassian.com/bitbucket/troubleshoot-ssh-issues-271943403.html section General SSH troubleshooting and I get

(please note I am working remote but I have access to all network resources!, it is NOT a VPN issue)

However Vipul, my colleague, who is onsite, can clone repos w/o issue gets the following:

Which should not work according to the Confulence.Atlassian.com as:

I then added -v to get the debugger output

My collegue who is onsite gets:

Although it shows Permission denied (publickey) he can actually clone a repo w/o issues.

What should I do so I can clone the repo remotely while on VPN.  (before you ask, yes, I was able to clone a repo onsite partially, but I got an error I ignored so let's assume I can't clone anything)

I called our companies tech support but they verified my VPN connection is valid and works so they too are not sure why I am having the issue.

答: Was able to connect using GitBash so this is my workaround.</p>

Title: OpenSSH server rejected connection


问:
Executing javascript function after finishing method bean (<a4j:support>)
This is my first question. In my project, I'm using JSF 1.2 and richfaces 3.3. I want to execute a javascript function after finishing executing a bean's method.
The method of the bean worked very well and fill the table but the javascript function didn't work. This is my attempt :

```<code><h:form>
<h:commandButton value="Click" actionListener="#{bean.monActionListener}" reRender="table">
<a4j:support event="onClick" oncomplete="show()" />
</h:commandButton>
<h:form>

<h:form>
<rich:dataTable id="table" rendered="#{not empty bean.listU}"
value="#{bean.listU}" var="u">

 <h:column headerClass="headerleftfacet">
 <h:outputText value="#{u[0]}">
 </h:outputText>
 </h:column>
 <h:column headerClass="headermiddlefacet">
 <h:outputText  value="#{u[1]}" >
 </h:outputText>
 </h:column>

</rich:dataTable>
</code>```

Thanks in advance!

答:
I had the same problem and I resolved it by using <a4j:commandButton> and <a4j:outputPanel>:

```<code> <h:form>
 <a4j:commandButton value="Click" actionListener="#{bean.monActionListener}" reRender="tab" oncomplete="alert('ok')" />

 <h:form>

<a4j:outputPanel id="tab">
<h:form>
<rich:dataTable id="table" rendered="#{not empty bean.listU}"
 value="#{bean.listU}" var="u">

 <h:column headerClass="headerleftfacet">
 <h:outputText value="#{u[0]}">
  </h:outputText>
 </h:column>
 <h:column headerClass="headermiddlefacet">
 <h:outputText  value="#{u[1]}" >
 </h:outputText>
   </h:column>

  </rich:dataTable>
  </h:form>
  </a4j:outputPanel>
</code>```

Body:
This is my first question. In my project, I'm using JSF 1.2 and richfaces 3.3. I want to execute a javascript function after finishing executing a bean's method.
The method of the bean worked very well and fill the table but the javascript function didn't work. This is my attempt :

<h:form>
<h:commandButton value="Click" actionListener="#{bean.monActionListener}" reRender="table">
<a4j:support event="onClick" oncomplete="show()" />
</h:commandButton>
<h:form>

<h:form>
<rich:dataTable id="table" rendered="#{not empty bean.listU}"
value="#{bean.listU}" var="u">

 <h:column headerClass="headerleftfacet">
 <h:outputText value="#{u[0]}">
 </h:outputText>
 </h:column>
 <h:column headerClass="headermiddlefacet">
 <h:outputText  value="#{u[1]}" >
 </h:outputText>
 </h:column>

</rich:dataTable>

Thanks in advance!

Body:
I had the same problem and I resolved it by using <a4j:commandButton> and <a4j:outputPanel>:

 <h:form>
 <a4j:commandButton value="Click" actionListener="#{bean.monActionListener}" reRender="tab" oncomplete="alert('ok')" />

 <h:form>

<a4j:outputPanel id="tab">
<h:form>
<rich:dataTable id="table" rendered="#{not empty bean.listU}"
 value="#{bean.listU}" var="u">

 <h:column headerClass="headerleftfacet">
 <h:outputText value="#{u[0]}">
  </h:outputText>
 </h:column>
 <h:column headerClass="headermiddlefacet">
 <h:outputText  value="#{u[1]}" >
 </h:outputText>
   </h:column>

  </rich:dataTable>
  </h:form>
  </a4j:outputPanel>


问:
How to make current time automatically update in AVAudioplayer
I want to know that : How to make currentTime automatically update in AVAudioplayer.
I use this code

```<code>    let currentTime1 = Int((player1?.currentTime)!)
    let minutes = currentTime1/60
    let seconds = currentTime1 - minutes * 60
    curLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String
</code>```

Thanks.

答:
```<code>func startRecording() -> Void {
        ....
        ....
     let aSelector : Selector = #selector(CLASSNAME.updateTime)
     timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector,userInfo: nil, repeats: true)
     startTime = NSDate.timeIntervalSinceReferenceDate()

}

func updateTime() {
        let currentTime = NSDate.timeIntervalSinceReferenceDate()
        var elapsedTime: NSTimeInterval = currentTime - startTime
        let minutes = UInt8(elapsedTime / 60.0)
        elapsedTime -= (NSTimeInterval(minutes) * 60)
        let seconds = UInt8(elapsedTime)
        elapsedTime -= NSTimeInterval(seconds)
        let strMinutes = String(format: "%02d", minutes)
        let strSeconds = String(format: "%02d", seconds)
        YOUR-LABEL.text = "\(strMinutes):\(strSeconds)"

    }
</code>```

now when you call the startRecording() function it will start updating the text on YOUR-LABEL

Hope it is clear now

Body:
I want to know that : How to make currentTime automatically update in AVAudioplayer.
I use this code

    let currentTime1 = Int((player1?.currentTime)!)
    let minutes = currentTime1/60
    let seconds = currentTime1 - minutes * 60
    curLabel.text = NSString(format: "%02d:%02d", minutes,seconds) as String

Thanks.

Body:
func startRecording() -> Void {
        ....
        ....
     let aSelector : Selector = #selector(CLASSNAME.updateTime)
     timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector,userInfo: nil, repeats: true)
     startTime = NSDate.timeIntervalSinceReferenceDate()

}

func updateTime() {
        let currentTime = NSDate.timeIntervalSinceReferenceDate()
        var elapsedTime: NSTimeInterval = currentTime - startTime
        let minutes = UInt8(elapsedTime / 60.0)
        elapsedTime -= (NSTimeInterval(minutes) * 60)
        let seconds = UInt8(elapsedTime)
        elapsedTime -= NSTimeInterval(seconds)
        let strMinutes = String(format: "%02d", minutes)
        let strSeconds = String(format: "%02d", seconds)
        YOUR-LABEL.text = "\(strMinutes):\(strSeconds)"

    }

now when you call the startRecording() function it will start updating the text on YOUR-LABEL

Hope it is clear now


问:
R: how to convert a binary interactions dataframe into a matrix?
I have a interaction datframe in R, like this:

```<code>> interaction
     x y   z
[1,] 4 1 112
[2,] 3 1 104
[3,] 2 4  19
[4,] 1 3 154
[5,] 3 5 332
[6,] 4 1 187
[7,] 5 5 489
[8,] 2 2 149
</code>```

i want to covert it into a matrix, take x as rownames, take y as colnames, and take z as their interaction value, x,y can take same value.

anybody knows how to convert? maybe just one step in R. Please.
 thank you very much!
-------------------2017/3/31---------------------------------------
or there is another edition of my question:

```<code>interactions <-data.frame(x=c(40,30,20,10,30,40,50,80),y=c(50,10,40,30,50,10,50,90),z=c(112,104,19,154,332,187,489,149))

m <- matrix(0,10,10)

colnames(m)<-c(10,20,30,40,50,60,70,80,90,100)
rownames(m)<-c(10,20,30,40,50,60,70,80,90,100)
</code>```

how to covert the interactions data into matrix "m".
thank you!

答:
Is this the sort of thing...? It assumes you want to add duplicates - such as rows 1 and 6 (both (4,1)). (See much better solution in comment below!)

```<code>intn <- data.frame(x=c(4,3,2,1,3,4,5,2),y=c(1,1,4,3,5,1,5,2),z=c(112,104,19,154,332,187,489,149))

m <- matrix(0,nrow=max(intn$x),ncol=max(intn$y))

for(i in seq_len(nrow(intn))) {
       m[intn$x[i],intn$y[i]] <- m[intn$x[i],intn$y[i]] + intn$z[i]
       }

m
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0  154    0    0
[2,]    0  149    0   19    0
[3,]  104    0    0    0  332
[4,]  299    0    0    0    0
[5,]    0    0    0    0  489
</code>```

In response to follow-up question - if there are more possible values of x and y, you can still use xtabs but add in some dummy data with the valid x and y values.  The row and column names will be the combined dummy and actual values (as characters rather than numeric).  Something like this...

```<code>xvals <- c(-2,0,1,2,3,4,5,2.5,7) #possible x values
yvals <- c(-1,1,2,2.5,3,4,5,6,7) #possible y values
dum <- data.frame(x=xvals,y=yvals) #xvals and yvals need to be same length
dum$z <- 0

m2 <- xtabs(z~x+y,rbind(dum,intn))

m2

     y
x      -1   1   2 2.5   3   4   5   6   7
  -2    0   0   0   0   0   0   0   0   0
  0     0   0   0   0   0   0   0   0   0
  1     0   0   0   0 154   0   0   0   0
  2     0   0 149   0   0  19   0   0   0
  2.5   0   0   0   0   0   0   0   0   0
  3     0 104   0   0   0   0 332   0   0
  4     0 299   0   0   0   0   0   0   0
  5     0   0   0   0   0   0 489   0   0
  7     0   0   0   0   0   0   0   0   0
</code>```

Body:
I have a interaction datframe in R, like this:

> interaction
     x y   z
[1,] 4 1 112
[2,] 3 1 104
[3,] 2 4  19
[4,] 1 3 154
[5,] 3 5 332
[6,] 4 1 187
[7,] 5 5 489
[8,] 2 2 149

i want to covert it into a matrix, take x as rownames, take y as colnames, and take z as their interaction value, x,y can take same value.

anybody knows how to convert? maybe just one step in R. Please.
 thank you very much!
-------------------2017/3/31---------------------------------------
or there is another edition of my question:

interactions <-data.frame(x=c(40,30,20,10,30,40,50,80),y=c(50,10,40,30,50,10,50,90),z=c(112,104,19,154,332,187,489,149))

m <- matrix(0,10,10)

colnames(m)<-c(10,20,30,40,50,60,70,80,90,100)
rownames(m)<-c(10,20,30,40,50,60,70,80,90,100)

how to covert the interactions data into matrix "m".
thank you!

Body:
Is this the sort of thing...? It assumes you want to add duplicates - such as rows 1 and 6 (both (4,1)). (See much better solution in comment below!)

intn <- data.frame(x=c(4,3,2,1,3,4,5,2),y=c(1,1,4,3,5,1,5,2),z=c(112,104,19,154,332,187,489,149))

m <- matrix(0,nrow=max(intn$x),ncol=max(intn$y))

for(i in seq_len(nrow(intn))) {
       m[intn$x[i],intn$y[i]] <- m[intn$x[i],intn$y[i]] + intn$z[i]
       }

m
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0  154    0    0
[2,]    0  149    0   19    0
[3,]  104    0    0    0  332
[4,]  299    0    0    0    0
[5,]    0    0    0    0  489

In response to follow-up question - if there are more possible values of x and y, you can still use xtabs but add in some dummy data with the valid x and y values.  The row and column names will be the combined dummy and actual values (as characters rather than numeric).  Something like this...

xvals <- c(-2,0,1,2,3,4,5,2.5,7) #possible x values
yvals <- c(-1,1,2,2.5,3,4,5,6,7) #possible y values
dum <- data.frame(x=xvals,y=yvals) #xvals and yvals need to be same length
dum$z <- 0

m2 <- xtabs(z~x+y,rbind(dum,intn))

m2

     y
x      -1   1   2 2.5   3   4   5   6   7
  -2    0   0   0   0   0   0   0   0   0
  0     0   0   0   0   0   0   0   0   0
  1     0   0   0   0 154   0   0   0   0
  2     0   0 149   0   0  19   0   0   0
  2.5   0   0   0   0   0   0   0   0   0
  3     0 104   0   0   0   0 332   0   0
  4     0 299   0   0   0   0   0   0   0
  5     0   0   0   0   0   0 489   0   0
  7     0   0   0   0   0   0   0   0   0


问:
How do I put indexes and words together to make 1 final string/array? (Java)
Background to question

I have been working on developing code that is able to read a string, compress it an send it to a new file in a compressed form. (e.g. "hello, hello" -> "hello[0, 1]) and this works great at the moment. Here is the link for anyone who wants to use it: https://pastebin.com/v6YF34mU . The next stage is being able to re-create the file using the indexes and the words.

Question

I currently have got this code:

```<code>public static void main(String[] args) {
        // TODO code application logic here
        Pattern seaPattern = Pattern.compile("(.*?)\\[(.*?)\\],");
            String compressedSea = "see[2, 4, 5],sea[0, 1, 3],";
            Matcher seaMatcher = seaPattern.matcher(compressedSea);
            while (seaMatcher.find()) {
                String seaWords = seaMatcher.group(1);
                String[] seaIndexes = seaMatcher.group(2).split(", ");
                for (String str : seaIndexes) {
                    int seaIndex = Integer.parseInt(str);
                    System.out.print(seaIndex);
                    }
</code>```

In short. I reads the string and splits it up into to different arrays. One of the arrays contains the indexes and the other contains the words. The next stage is putting these together and creating 1 string that is able to be compressed. I am relatively new to Java so I am not completely sure how I would go about doing this.

If anyone has got any ideas on how to do this it would be much appreciated!

答:
Are you just asking how to put two strings into one string? Or am I understanding wrong?
If it's just adding two strings, that can be done by using the + sign.

```<code>String newString = string1 + string2;
</code>```

If you're asking how to put them into a hashmap (so key-value pair), that would be:

```<code>HashMap<Integer, String> map = new HashMap<>();
map.put(value, word);
</code>```

Body:
Background to question

I have been working on developing code that is able to read a string, compress it an send it to a new file in a compressed form. (e.g. "hello, hello" -> "hello[0, 1]) and this works great at the moment. Here is the link for anyone who wants to use it: https://pastebin.com/v6YF34mU . The next stage is being able to re-create the file using the indexes and the words.

Question

I currently have got this code:

public static void main(String[] args) {
        // TODO code application logic here
        Pattern seaPattern = Pattern.compile("(.*?)\\[(.*?)\\],");
            String compressedSea = "see[2, 4, 5],sea[0, 1, 3],";
            Matcher seaMatcher = seaPattern.matcher(compressedSea);
            while (seaMatcher.find()) {
                String seaWords = seaMatcher.group(1);
                String[] seaIndexes = seaMatcher.group(2).split(", ");
                for (String str : seaIndexes) {
                    int seaIndex = Integer.parseInt(str);
                    System.out.print(seaIndex);
                    }

In short. I reads the string and splits it up into to different arrays. One of the arrays contains the indexes and the other contains the words. The next stage is putting these together and creating 1 string that is able to be compressed. I am relatively new to Java so I am not completely sure how I would go about doing this.

If anyone has got any ideas on how to do this it would be much appreciated!

Body:
Are you just asking how to put two strings into one string? Or am I understanding wrong?
If it's just adding two strings, that can be done by using the + sign.

String newString = string1 + string2;

If you're asking how to put them into a hashmap (so key-value pair), that would be:

HashMap<Integer, String> map = new HashMap<>();
map.put(value, word);


问:
SOLID vs. YAGNI
One of the most frequent arguments I hear for not adhering to the SOLID principles in object-oriented design is YAGNI (although the arguer often doesn't call it that):

"It is OK that I put both feature X and feature Y into the same class. It is so simple why bother adding a new class (i.e. complexity)."

"Yes, I can put all my business logic directly into the GUI code it is much easier and quicker. This will always be the only GUI and it is highly unlikely that significant new requirements will ever come in."

"If in the unlikely case of new requirements my code gets too cluttered I still can refactor for the new requirement. So your 'What if you later need to…' argument doesn't count."

What would be your most convincing arguments against such practice? How can I really show that this is an expensive practice, especially to somebody that doesn't have too much experience in software development.

答:
There is no answer, or rather, there is an answer neither you nor your interlocutor might like: both YAGNI and SOLID can be wrong approaches.

Attempting to go for SOLID with an inexperienced team, or a team with tight delivery objectives pretty much guarantees you will end up with an expensive, over-engineered bunch of code... that will NOT be SOLID, just over-engineered (aka welcome to the real-world).

Attempting to go YAGNI for a long term project and hope you can refactor later only works to an extent (aka welcome to the real-world). YAGNI excels at proof-of-concepts and demonstrators, getting the market/contract and then be able to invest into something more SOLID.

You need both, at different points in time.

Title: SOLID vs. YAGNI


问:
Php MySQL Query is out of memory in hosting with limited resources
Hello everyone before anything I want to set important facts that cannot be changed:

The hosting can't be changed

The php_ini max memory setted in php won't work

The php.ini cannot be edited

The php can't be updated

We have a webapi (similar to a restful service) where with an url, the users can be shown in a json way. But we have 85k+ records, when we try to brig them all, the php crashes (that doesn't happen when we look just for 1 record), we have 2 codes to work with, but none of them bring all the users

Version 1

```<code><?php
//security variables
$variableName = 'name';
$variableValue = 'value';

//system variables

ob_end_flush();
ob_start();
if(isset($_GET[$variableName]) && $_GET[$variableName]== $variableValue){
    $dbVars = array();
    $query = 'SELECT * FROM users_data ';
    foreach ($_GET as $key => $value) {

        if( $key != $variableName && $key != 'sized' && $key != 'devmode'){
            array_push($dbVars, $key."='".$value."'");
        }
    }
    if( count($dbVars) > 0 ){

        $query .= 'WHERE '.implode(' AND ', $dbVars);
    }
    $result = mysql($w['database'], $query);
    $results = array();
    while($row = mysql_fetch_assoc($result)){
        array_push($results, $row);
    }
    echo json_encode($results);
}
?>
</code>```

Version 2 (using flush)

```<code><?php
//security variables
$variableName = 'name';
$variableValue = 'value';

//system variables

ob_end_flush();
ob_start();
if(isset($_GET[$variableName]) && $_GET[$variableName]== $variableValue){
    $dbVars = array();
    $query = 'SELECT * FROM users_data ';
    foreach ($_GET as $key => $value) {

        if( $key != $variableName && $key != 'sized' && $key != 'devmode'){
            array_push($dbVars, $key."='".$value."'");
        }
    }
    if( count($dbVars) > 0 ){

        $query .= 'WHERE '.implode(' AND ', $dbVars);
    }
    $result = mysql($w['database'], $query);
    echo "[";
    while($row = mysql_fetch_assoc($result)){
        $results = array();
        foreach($row as $key => $value){
            array_push($results, '"'.$key.'":"'.$value.'"');
        }
        echo '{'.implode(',',$results).'}';
        ob_flush();
    }
    echo "]";
}
?>
</code>```

When we want to get all the users in database are 85k, the result is none because memory limit
How can we made this work for all the users?

答:
First of all, your code is filled to the brim with SQL injection vulnerabilities. Anyone can own your database. This is your problem.

Now, the reason PHP runs out of memory is that you are using buffered queries.

http://php.net/manual/en/mysqlinfo.concepts.buffering.php

Queries are using the buffered mode by default. This means that query results are immediately transferred from the MySQL Server to PHP and then are kept in the memory of the PHP process.

Read the link I provided (which uses mysqli, for chrissakes) and use unbuffered mode to stream your result set to the client.

Also, don't array_push() the entire result set into an array.

Also, obviously,

```<code>array_push($dbVars, $key."='".$value."'");
</code>```

will generate invalid JSON if any value contains a " or other escape chars.

Body:
Hello everyone before anything I want to set important facts that cannot be changed:

The hosting can't be changed

The php_ini max memory setted in php won't work

The php.ini cannot be edited

The php can't be updated

We have a webapi (similar to a restful service) where with an url, the users can be shown in a json way. But we have 85k+ records, when we try to brig them all, the php crashes (that doesn't happen when we look just for 1 record), we have 2 codes to work with, but none of them bring all the users

Version 1

<?php
//security variables
$variableName = 'name';
$variableValue = 'value';

//system variables

ob_end_flush();
ob_start();
if(isset($_GET[$variableName]) && $_GET[$variableName]== $variableValue){
    $dbVars = array();
    $query = 'SELECT * FROM users_data ';
    foreach ($_GET as $key => $value) {

        if( $key != $variableName && $key != 'sized' && $key != 'devmode'){
            array_push($dbVars, $key."='".$value."'");
        }
    }
    if( count($dbVars) > 0 ){

        $query .= 'WHERE '.implode(' AND ', $dbVars);
    }
    $result = mysql($w['database'], $query);
    $results = array();
    while($row = mysql_fetch_assoc($result)){
        array_push($results, $row);
    }
    echo json_encode($results);
}
?>

Version 2 (using flush)

<?php
//security variables
$variableName = 'name';
$variableValue = 'value';

//system variables

ob_end_flush();
ob_start();
if(isset($_GET[$variableName]) && $_GET[$variableName]== $variableValue){
    $dbVars = array();
    $query = 'SELECT * FROM users_data ';
    foreach ($_GET as $key => $value) {

        if( $key != $variableName && $key != 'sized' && $key != 'devmode'){
            array_push($dbVars, $key."='".$value."'");
        }
    }
    if( count($dbVars) > 0 ){

        $query .= 'WHERE '.implode(' AND ', $dbVars);
    }
    $result = mysql($w['database'], $query);
    echo "[";
    while($row = mysql_fetch_assoc($result)){
        $results = array();
        foreach($row as $key => $value){
            array_push($results, '"'.$key.'":"'.$value.'"');
        }
        echo '{'.implode(',',$results).'}';
        ob_flush();
    }
    echo "]";
}
?>

When we want to get all the users in database are 85k, the result is none because memory limit
How can we made this work for all the users?

Body:
First of all, your code is filled to the brim with SQL injection vulnerabilities. Anyone can own your database. This is your problem.

Now, the reason PHP runs out of memory is that you are using buffered queries.

http://php.net/manual/en/mysqlinfo.concepts.buffering.php

Queries are using the buffered mode by default. This means that query results are immediately transferred from the MySQL Server to PHP and then are kept in the memory of the PHP process.

Read the link I provided (which uses mysqli, for chrissakes) and use unbuffered mode to stream your result set to the client.

Also, don't array_push() the entire result set into an array.

Also, obviously,

array_push($dbVars, $key."='".$value."'");

will generate invalid JSON if any value contains a " or other escape chars.


问:
start the service when app gets closed
I want to start a service when I press the home button or just press back (when the app is in the background but not killed)
how can I do a function that checks that ?
thanks to all</p>

答:
You need a BaseActivity,and all Activities must extand this BaseActivity:</p>

```<code>public class BaseActivity extends Activity {
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
        startService(new Intent(this, AService.class));
        //maybe you need check the AService is running here```
    }
    return super.onKeyDown(keyCode, event);
}
}
</code>```

Title: start the service when app gets closed

Body:
You need a BaseActivity,and all Activities must extand this BaseActivity:

public class BaseActivity extends Activity {
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
        startService(new Intent(this, AService.class));
        //maybe you need check the AService is running here```
    }
    return super.onKeyDown(keyCode, event);
}
}


问:
sunspot solr undefined field type
I'm having a problem with my sunspot and solr. In development it worked like charme but in production I get the following error out of my rails production log:

RSolr::RequestError (Solr Response: undefined field type):
  app/controllers/search_controller.rb:7:in `index'

I guess it has something to do with the schema.xml. But I'm quite new to solr. So can anybody help me?

OK:

Controller

```<code>def index
 unless params[:q].blank?
  @search = Question.search do
    fulltext params[:q]
  end
  @results = @search.results

else
  @results = nil
end
@searchterm = params[:q]
</code>```

end

model (Question)

...

```<code>searchable do
  text :title
  text :content
end
</code>```

答: For me it was in Heroku addon Websolr dashboard, the default configuration was set to blacklight, and I had to change it to sunspot.</p>

Title: sunspot solr undefined field type

Body:
I'm having a problem with my sunspot and solr. In development it worked like charme but in production I get the following error out of my rails production log:

RSolr::RequestError (Solr Response: undefined field type):
  app/controllers/search_controller.rb:7:in `index'

I guess it has something to do with the schema.xml. But I'm quite new to solr. So can anybody help me?

OK:

Controller

def index
 unless params[:q].blank?
  @search = Question.search do
    fulltext params[:q]
  end
  @results = @search.results

else
  @results = nil
end
@searchterm = params[:q]

end

model (Question)

...

searchable do
  text :title
  text :content
end